├── docs ├── requirements.txt ├── source │ ├── libmk │ │ ├── enums │ │ │ ├── model.rst │ │ │ ├── size.rst │ │ │ ├── effect.rst │ │ │ ├── layout.rst │ │ │ ├── result.rst │ │ │ ├── controlmode.rst │ │ │ └── index.rst │ │ ├── structs │ │ │ ├── device.rst │ │ │ ├── handle.rst │ │ │ ├── firmware.rst │ │ │ ├── effect_details.rst │ │ │ └── index.rst │ │ ├── funcs │ │ │ ├── lib.rst │ │ │ ├── handles.rst │ │ │ ├── comms.rst │ │ │ ├── index.rst │ │ │ ├── ctrl.rst │ │ │ ├── leds.rst │ │ │ └── mgmt.rst │ │ ├── index.rst │ │ └── consts │ │ │ └── index.rst │ ├── masterkeys │ │ └── index.rst │ ├── libmkc │ │ ├── enums │ │ │ └── index.rst │ │ ├── index.rst │ │ ├── structs │ │ │ └── index.rst │ │ └── funcs │ │ │ └── index.rst │ ├── examples │ │ ├── photo.rst │ │ ├── ambilight.rst │ │ └── index.rst │ └── devices.rst ├── FindSphinx.cmake ├── index.rst ├── CMakeLists.txt └── conf.py ├── clean.sh ├── utils ├── README.md ├── main.c ├── ctrl.c └── record.c ├── examples ├── README.md ├── photoviewer │ └── viewer.py ├── notifications │ ├── notifications.py │ ├── capture.h │ └── mk_notifications.c └── ambilight │ └── ambilight.c ├── .gitignore ├── .travis.yml ├── setup.py ├── CMakeLists.txt ├── INTERFACE.md ├── README.md ├── libmk ├── libmkc.h ├── libmkc.c ├── libmk.h └── libmk.c ├── masterkeys ├── __init__.py └── masterkeys.c └── LICENSE.md /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | breathe 2 | -------------------------------------------------------------------------------- /docs/source/libmk/enums/model.rst: -------------------------------------------------------------------------------- 1 | LibMK_Model 2 | =========== 3 | 4 | .. doxygenenum:: LibMK_Model 5 | -------------------------------------------------------------------------------- /docs/source/libmk/enums/size.rst: -------------------------------------------------------------------------------- 1 | LibMK_Size 2 | ========== 3 | 4 | .. doxygenenum:: LibMK_Size 5 | -------------------------------------------------------------------------------- /docs/source/libmk/enums/effect.rst: -------------------------------------------------------------------------------- 1 | LibMK_Effect 2 | ============ 3 | 4 | .. doxygenenum:: LibMK_Effect 5 | -------------------------------------------------------------------------------- /docs/source/libmk/enums/layout.rst: -------------------------------------------------------------------------------- 1 | LibMK_Layout 2 | ============ 3 | 4 | .. doxygenenum:: LibMK_Layout 5 | -------------------------------------------------------------------------------- /docs/source/libmk/enums/result.rst: -------------------------------------------------------------------------------- 1 | LibMK_Result 2 | ============ 3 | 4 | .. doxygenenum:: LibMK_Result 5 | -------------------------------------------------------------------------------- /docs/source/libmk/enums/controlmode.rst: -------------------------------------------------------------------------------- 1 | LibMK_ControlMode 2 | ================= 3 | 4 | .. doxygenenum:: LibMK_ControlMode 5 | -------------------------------------------------------------------------------- /docs/source/libmk/structs/device.rst: -------------------------------------------------------------------------------- 1 | LibMK_Device 2 | ============ 3 | 4 | .. doxygenstruct:: LibMK_Device 5 | :members: 6 | -------------------------------------------------------------------------------- /docs/source/libmk/structs/handle.rst: -------------------------------------------------------------------------------- 1 | LibMK_Handle 2 | ============ 3 | 4 | .. doxygenstruct:: LibMK_Handle 5 | :members: 6 | -------------------------------------------------------------------------------- /docs/source/masterkeys/index.rst: -------------------------------------------------------------------------------- 1 | masterkeys 2 | ========== 3 | 4 | .. automodule:: masterkeys 5 | :members: 6 | :undoc-members: -------------------------------------------------------------------------------- /docs/source/libmk/structs/firmware.rst: -------------------------------------------------------------------------------- 1 | LibMK_Firmware 2 | ============== 3 | 4 | .. doxygenstruct:: LibMK_Firmware 5 | :members: 6 | -------------------------------------------------------------------------------- /docs/source/libmk/funcs/lib.rst: -------------------------------------------------------------------------------- 1 | Library Control 2 | =============== 3 | 4 | .. doxygenfunction:: libmk_init 5 | 6 | .. doxygenfunction:: libmk_exit 7 | -------------------------------------------------------------------------------- /docs/source/libmkc/enums/index.rst: -------------------------------------------------------------------------------- 1 | Enums 2 | ===== 3 | 4 | .. doxygenenum:: LibMK_Controller_State 5 | .. doxygenenum:: LibMK_Instruction_Type 6 | 7 | -------------------------------------------------------------------------------- /docs/source/libmkc/index.rst: -------------------------------------------------------------------------------- 1 | Documentation 2 | ============= 3 | 4 | .. toctree:: 5 | 6 | enums/index 7 | funcs/index 8 | structs/index 9 | -------------------------------------------------------------------------------- /docs/source/libmk/structs/effect_details.rst: -------------------------------------------------------------------------------- 1 | LibMK_Effect_Details 2 | ==================== 3 | 4 | .. doxygenstruct:: LibMK_Effect_Details 5 | :members: 6 | -------------------------------------------------------------------------------- /docs/source/libmk/structs/index.rst: -------------------------------------------------------------------------------- 1 | Structs 2 | ======= 3 | 4 | .. toctree:: 5 | 6 | firmware 7 | device 8 | handle 9 | effect_details 10 | -------------------------------------------------------------------------------- /clean.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rm -rf CMakeFiles CMakeCache.txt _skbuild CMakeTmp build dist cmake 3 | rm record main cmake_install.cmake ambilight record *.so* 4 | -------------------------------------------------------------------------------- /docs/source/libmk/enums/index.rst: -------------------------------------------------------------------------------- 1 | Enums 2 | ===== 3 | 4 | .. toctree:: 5 | 6 | controlmode 7 | effect 8 | layout 9 | model 10 | result 11 | size 12 | -------------------------------------------------------------------------------- /docs/source/libmk/index.rst: -------------------------------------------------------------------------------- 1 | Documentation 2 | ============= 3 | 4 | .. toctree:: 5 | 6 | consts/index 7 | enums/index 8 | funcs/index 9 | structs/index 10 | -------------------------------------------------------------------------------- /docs/source/libmkc/structs/index.rst: -------------------------------------------------------------------------------- 1 | Structs 2 | ======= 3 | 4 | .. doxygenstruct:: LibMK_Instruction 5 | :members: 6 | .. doxygenstruct:: LibMK_Controller 7 | :members: 8 | 9 | -------------------------------------------------------------------------------- /docs/source/libmk/funcs/handles.rst: -------------------------------------------------------------------------------- 1 | Handles 2 | ======= 3 | 4 | .. doxygenfunction:: libmk_create_handle 5 | .. doxygenfunction:: libmk_free_handle 6 | .. doxygenfunction:: libmk_set_device 7 | -------------------------------------------------------------------------------- /docs/source/libmk/funcs/comms.rst: -------------------------------------------------------------------------------- 1 | Communication 2 | ============= 3 | 4 | .. doxygenfunction:: libmk_send_packet 5 | .. doxygenfunction:: libmk_exch_packet 6 | .. doxygenfunction:: libmk_build_packet 7 | -------------------------------------------------------------------------------- /docs/source/libmk/funcs/index.rst: -------------------------------------------------------------------------------- 1 | Functions 2 | ========= 3 | 4 | .. toctree:: 5 | :caption: Categories: 6 | 7 | lib 8 | mgmt 9 | handles 10 | ctrl 11 | comms 12 | leds 13 | -------------------------------------------------------------------------------- /docs/source/libmk/funcs/ctrl.rst: -------------------------------------------------------------------------------- 1 | Control 2 | ======= 3 | 4 | .. doxygenfunction:: libmk_enable_control 5 | .. doxygenfunction:: libmk_disable_control 6 | .. doxygenfunction:: libmk_claim_interface 7 | .. doxygenfunction:: libmk_send_control_packet 8 | .. doxygenfunction:: libmk_reset 9 | -------------------------------------------------------------------------------- /docs/source/libmk/consts/index.rst: -------------------------------------------------------------------------------- 1 | Constants 2 | ========= 3 | 4 | libmk defines various constants that make interaction with the library 5 | easier. The following is a list of the definitions that can be used 6 | while interacting with the library. 7 | 8 | .. doxygendefine:: LIBMK_MAX_ROWS 9 | .. doxygendefine:: LIBMK_MAX_COLS 10 | -------------------------------------------------------------------------------- /docs/source/libmk/funcs/leds.rst: -------------------------------------------------------------------------------- 1 | LED Control 2 | =========== 3 | 4 | .. doxygenfunction:: libmk_set_effect 5 | .. doxygenfunction:: libmk_set_effect_details 6 | .. doxygenfunction:: libmk_set_full_color 7 | .. doxygenfunction:: libmk_set_all_led_color 8 | .. doxygenfunction:: libmk_set_single_led 9 | .. doxygenfunction:: libmk_get_offset 10 | -------------------------------------------------------------------------------- /docs/source/libmk/funcs/mgmt.rst: -------------------------------------------------------------------------------- 1 | Device Management 2 | ================= 3 | 4 | .. doxygenfunction:: libmk_detect_devices 5 | .. doxygenfunction:: libmk_open_device 6 | .. doxygenfunction:: libmk_create_device 7 | .. doxygenfunction:: libmk_free_device 8 | .. doxygenfunction:: libmk_append_device 9 | .. doxygenfunction:: libmk_ident_model 10 | -------------------------------------------------------------------------------- /docs/source/examples/photo.rst: -------------------------------------------------------------------------------- 1 | Photo Viewer 2 | ============ 3 | 4 | Simple Python program that reads a specified image file and calculates 5 | a color matrix based on this image by averaging the pixels. The image is 6 | then set on the keyboard. 7 | 8 | .. literalinclude:: ../../../examples/photoviewer/viewer.py 9 | :language: python 10 | :linenos: 11 | -------------------------------------------------------------------------------- /docs/source/examples/ambilight.rst: -------------------------------------------------------------------------------- 1 | AmbiLight 2 | ========= 3 | 4 | Fast screenshot capture program that calculates the dominant color 5 | (average of colors with high hue) visible on the screen and sets it as 6 | the only color of the keyboard. Is capable of reaching somewhere between 7 | 20 and 30 FPS on most machines. 8 | 9 | .. literalinclude:: ../../../examples/ambilight/ambilight.c 10 | :language: c 11 | :linenos: 12 | -------------------------------------------------------------------------------- /docs/FindSphinx.cmake: -------------------------------------------------------------------------------- 1 | # Author: RedFantom 2 | # License: GNU GPLv3 3 | # Copyright (c) 2018-2019 RedFantom 4 | # Source: https://eb2.co/blog/2012/03 5 | find_program(SPHINX_EXECUTABLE NAMES sphinx-build 6 | HINTS $ENV{SPHINX_DIR} PATH_SUFFIXES BIN 7 | DOC "Sphinx Documentation Generator") 8 | include(FindPackageHandleStandardArgs) 9 | find_package_handle_standard_args(Sphinx DEFAULT_MSG SPHINX_EXECUTABLE) 10 | mark_as_advanced(SPHINX_EXECUTABLE) 11 | -------------------------------------------------------------------------------- /docs/source/examples/index.rst: -------------------------------------------------------------------------------- 1 | Examples 2 | ======== 3 | 4 | In this section, a set of examples is provided as a simple reference on 5 | how the libraries may be used in a practical manner. The examples are 6 | extensively tested and a good way to determine whether building and 7 | installing the libraries was successful and the library is capable of 8 | controlling your device. 9 | 10 | .. toctree:: 11 | Photo Viewer: Python 12 | AmbiLight: C 13 | -------------------------------------------------------------------------------- /docs/source/libmkc/funcs/index.rst: -------------------------------------------------------------------------------- 1 | Functions 2 | ========= 3 | 4 | .. doxygenfunction:: libmk_create_controller 5 | .. doxygenfunction:: libmk_free_controller 6 | .. doxygenfunction:: libmk_sched_instruction 7 | .. doxygenfunction:: libmk_cancel_instruction 8 | .. doxygenfunction:: libmk_start_controller 9 | .. doxygenfunction:: libmk_run_controller 10 | .. doxygenfunction:: libmk_stop_controller 11 | .. doxygenfunction:: libmk_wait_controller 12 | .. doxygenfunction:: libmk_join_controller 13 | .. doxygenfunction:: libmk_set_controller_error 14 | .. doxygenfunction:: libmk_create_instruction 15 | .. doxygenfunction:: libmk_create_instruction_full 16 | .. doxygenfunction:: libmk_create_instruction_all 17 | .. doxygenfunction:: libmk_create_instruction_flash 18 | .. doxygenfunction:: libmk_create_instruction_single 19 | .. doxygenfunction:: libmk_free_instruction 20 | .. doxygenfunction:: libmk_exec_instruction 21 | -------------------------------------------------------------------------------- /utils/README.md: -------------------------------------------------------------------------------- 1 | # Utilities 2 | 3 | ## main 4 | The program `main.c` is the testing executable for the functionality 5 | of `libmk`. Run this to check if your keyboard is properly supported. 6 | Tests include setting full keyboard color, effects, individual LED 7 | control and profile control. The profile in slot 4 will be overwritten! 8 | 9 | ## ctrl 10 | The program `ctrl.c` is the testing executable for the functionality 11 | of `libmkc` and shows of the performance of the Cooler Master MasterKeys 12 | RGB keyboards using a high speed, high refresh-rate software defined 13 | color wave. `libmkc` works asynchronously to allow programs to achieve 14 | such fast effects. 15 | 16 | ## record 17 | The program `record.c` is used for adding support for new layouts for 18 | devices with an already known protocol. Unfortunately, supporting 19 | keyboards with a different protocol requires significant work in packet 20 | sniffing to reverse engineer the protocol used. 21 | -------------------------------------------------------------------------------- /docs/source/devices.rst: -------------------------------------------------------------------------------- 1 | Device Support 2 | ============== 3 | 4 | As Cooler Master Inc. has not provided any support, this library can 5 | only support a limited amount of devices, specifically, it can only 6 | support devices for which the record executable target has been 7 | executed. This program uses the library to register an offset for each 8 | key, which is required for the library to be able to control individual 9 | keys. Effects and full lighting colors can be set regardless of these 10 | offsets. 11 | 12 | The current list of supported devices includes: 13 | 14 | - MasterKeys Pro L RGB ANSI 15 | - MasterKeys Pro S RGB ANSI (untested) 16 | - MasterKeys Pro L RGB ISO (untested) 17 | 18 | If you would like for your device to be supported as well, please run 19 | the ``record`` executable. 20 | 21 | Keyboards with only monochrome lighting may use a different protocol and 22 | thus they would probably require more modifications than just adding a 23 | key layout matrix. Do not hesitate to open an issue if you have a 24 | monochrome keyboard, would like to see support and are willing to do 25 | some USB packet sniffing. 26 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | libmk documentation 2 | =================== 3 | |Travis| |LicenseGPL| |PyPI| 4 | 5 | ``libmk`` and the Python wrapper ``masterkeys`` provide a low-level 6 | interface to the LEDs on the MasterKeys keyboard series. 7 | 8 | .. toctree:: 9 | :maxdepth: 2 10 | :caption: Contents: 11 | 12 | source/devices 13 | source/examples/index 14 | Documentation: libmk 15 | Documentation: libmkc 16 | Documentation: masterkeys 17 | 18 | .. |Travis| image:: https://api.travis-ci.com/RedFantom/masterkeys-linux.svg 19 | :alt: Travis-CI Build Status 20 | :target: https://travis-ci.org/RedFantom/masterkeys-linux 21 | .. |LicenseGPL| image:: https://img.shields.io/badge/License-GPL%20v3-blue.svg 22 | :alt: GNU GPLv3 23 | :target: http://www.gnu.org/licenses/gpl-3.0 24 | .. |PyPI| image:: https://badge.fury.io/py/masterkeys.svg 25 | :alt: PyPI Version 26 | :target: https://pypi.python.org/pypi/masterkeys 27 | .. |Docs| image:: https://readthedocs.org/projects/masterkeys-linux/badge/?version=latest 28 | :alt: Documentation 29 | :target: https://masterkeys-linux.readthedocs.io/en/latest 30 | -------------------------------------------------------------------------------- /docs/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Author: RedFantom 2 | # License: GNU GPLv3 3 | # Copyright (c) 2018-2019 RedFantom 4 | # Source: https://eb2.co/blog/2012/03 5 | cmake_minimum_required(VERSION 3.9) 6 | set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}") 7 | find_package(Sphinx REQUIRED) 8 | if(NOT DEFINED SPHINX_THEME) 9 | set(SPHINX_THEME readthedocs) 10 | endif() 11 | if(NOT DEFINED SPHINX_THEME_DIR) 12 | set(SPHINX_THEME_DIR) 13 | endif() 14 | 15 | set(BINARY_BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/_build") 16 | set(SPHINX_CACHE_DIR "${CMAKE_CURRENT_BINARY_DIR}/_doctrees") 17 | set(SPHINX_HTML_DIR "${CMAKE_CURRENT_BINARY_DIR}/_build/html") 18 | set(SPHINX_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") 19 | 20 | configure_file( 21 | "${CMAKE_CURRENT_SOURCE_DIR}/conf.py" 22 | "${BINARY_BUILD_DIR}/conf.py" 23 | @ONLY) 24 | add_custom_target(libmk_docs ALL 25 | ${SPHINX_EXECUTABLE} 26 | -q -b html 27 | -c "${BINARY_BUILD_DIR}" 28 | -d "${SPHINX_CACHE_DIR}" 29 | "${SPHINX_SOURCE_DIR}" 30 | "${SPHINX_HTML_DIR}" 31 | DEPENDS doxygen 32 | COMMENT "Building HTML documentation") 33 | 34 | add_custom_target(doxygen 35 | COMMAND doxygen doxygen.conf 36 | COMMENT "Building Doxygen XML files") 37 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Custom Lighting Examples 2 | This folder contains a set of examples that make use of either the 3 | Python library or the native C library to show interactive or otherwise 4 | interesting LED effects on the keyboard. Some examples may require 5 | additional dependencies to run. 6 | 7 | ## AmbiLight 8 | This example turns the connected keyboard into an ambilight-like device 9 | by showing the average color of the screen (determined using libx11, 10 | so Wayland is currently not supported). 11 | 12 | ## PhotoViewer 13 | Takes the average of sections of the image to correspond to the color 14 | of a single key, thus showing the image selected on the keyboard in 15 | a much reduced resolution. As it is pure Python and it loops over a PIL 16 | pixel access object, the current implementation is quite slow. 17 | 18 | ## Notifications 19 | Mostly an improvement of the AmbiLight example, the notifications 20 | example is a completely rewritten version that runs from Python. 21 | Performance critical functions are implemented in C. 22 | 23 | Where AmbiLight only displays the dominant color shown on the screen, 24 | the notifications example will interrupt the AmbiLight color stream and 25 | flash the keyboard in the dominant color of a notification. 26 | 27 | Options are available to be set through the Python file 28 | `notifications.py`. The notifications example shows the potential of 29 | RGB keyboards as more than just gimmicks. 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Object files 5 | *.o 6 | *.ko 7 | *.obj 8 | *.elf 9 | 10 | # Linker output 11 | *.ilk 12 | *.map 13 | *.exp 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Libraries 20 | *.lib 21 | *.a 22 | *.la 23 | *.lo 24 | 25 | # Shared objects (inc. Windows DLLs) 26 | *.dll 27 | *.so 28 | *.so.* 29 | *.dylib 30 | 31 | # Executables 32 | *.exe 33 | *.out 34 | *.app 35 | *.i*86 36 | *.x86_64 37 | *.hex 38 | 39 | # Debug files 40 | *.dSYM/ 41 | *.su 42 | *.idb 43 | *.pdb 44 | 45 | # Kernel Module Compile Results 46 | *.mod* 47 | *.cmd 48 | .tmp_versions/ 49 | modules.order 50 | Module.symvers 51 | Mkfile.old 52 | dkms.conf 53 | 54 | # CLion 55 | /.idea 56 | 57 | # CMake 58 | /CMakeFiles 59 | /cmake-build* 60 | 61 | # Code::Blocks 62 | *.layout 63 | *.cbp 64 | *.depend 65 | 66 | # Project Files 67 | Makefile 68 | main-* 69 | layout.* 70 | !layout.rst 71 | /_skbuild 72 | 73 | # CMake 74 | CMakeCache.txt 75 | /CMakeTmp 76 | *CMakeTmp* 77 | *CMakeFiles* 78 | *CMakeCache.txt 79 | *cmake_install.cmake 80 | install_manifest.txt 81 | 82 | # Python packages 83 | /*.egg-info 84 | /build 85 | /dist 86 | *.pyc 87 | MANIFEST 88 | /venv 89 | 90 | # Executables 91 | /record 92 | /main 93 | /ambilight 94 | /ctrl 95 | 96 | # Documentation 97 | /docs/_build 98 | /docs/html 99 | /docs/_doctrees 100 | /docs/doxygen/xml 101 | /html 102 | /latex 103 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | sudo: required 3 | dist: trusty 4 | compiler: gcc 5 | matrix: 6 | include: 7 | - os: linux 8 | python: '2.7' 9 | - os: linux 10 | python: '3.4' 11 | - os: linux 12 | python: '3.5' 13 | - os: linux 14 | python: '3.6' 15 | addons: 16 | apt: 17 | packages: 18 | - libusb-1.0.0-dev 19 | - python-dev 20 | - python3-dev 21 | install: 22 | - python -m pip install -U pip scikit-build 23 | before_script: 24 | - mkdir cmake-build 25 | script: 26 | - cd cmake-build 27 | - cmake .. 28 | - make 29 | - sudo make install 30 | - cd .. 31 | - python setup.py install 32 | - cd .. 33 | - python -c 'import masterkeys' 34 | - cd masterkeys-linux 35 | - python setup.py bdist_wheel 36 | - cd examples/notifications 37 | - python -c 'import mk_notifications' 38 | deploy: 39 | provider: releases 40 | api_key: 41 | secure: lXCsKO3uk3IxAnTmy+ES6oOYivGEBNYnR6LPA1AhclMiYMEY37qb0EFWZF9ne2TI4bzIwoe9sDGA11IPXuL8yVwayPNjOG60viTv+LAB2y3gHXziGAy8PdEqcO3jXnY8M07HxG5DwwJMHaAnfJeuzv+nsYGoMEmXfHPWXEb/OiaQ8ieqrHlxysSHkpNt8zzfW26jenbEQHnq2hw5s41f47eCvYCVBph2KeJAcpy8DfRhTeYo+tb7umwCU2mT8w3y6/jwwVh4FNMq+D5MVHD+0crW0dIY9bmA/p05YLN64qE51z6l2Tpo+OL7Aafd3RWJ2r1NnEdMxJpQbb/AFoBZHSxbKkAp3TDOl+/i9ZUAfoZ+JJ5gPi5WuBy69Y1JLAO7OtzPG6Sgb3WtSRAPojmE4389Q6/tvwcPFUudytLuC23tRuaOUm66nUVBmbadA+vhMbScwf6cINwPvUYQbsrX0/77N3zVJZ0ZLNhFucfp2vFnnGBxsqAM7PK2rLIMxx9nNi/3Yy/Fjy4eDD8v10wJQDFsNk3pvsisFi+JkqFw2cB3QURVVn9Ao2/EoDIlU5Yr6O99ZefaHPTlNXjs24H9LI/mae1Ct0t5R8qUKndoanDIwvwukvHU8nLmWrBFi8fxH5aC0Gta09ku9q6tmz5Wpbn+kpT9wWJf03GwMfa1yVg= 42 | file: dist/*.whl 43 | file_glob: true 44 | on: 45 | tags: true 46 | repo: RedFantom/masterkeys-linux 47 | branch: master 48 | skip_cleanup: true 49 | -------------------------------------------------------------------------------- /examples/photoviewer/viewer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: RedFantom 3 | License: GNU GPLv3 4 | Copyright (c) 2018-2019 RedFantom 5 | """ 6 | import masterkeys as mk 7 | from os import path 8 | from PIL import Image 9 | import sys 10 | 11 | 12 | def print_progress(done, total): 13 | """Print a progress bar using #""" 14 | filled, percent = int(60 * done / total), done * 100 / total 15 | bar = "[{}]".format("#" * filled + " " * (60 - filled)) 16 | sys.stdout.write("\r{} {:02.1f}%\r".format(bar, percent)) 17 | sys.stdout.flush() 18 | 19 | 20 | if __name__ == '__main__': 21 | """ 22 | Open a file from a path given on input and process that to create a 23 | grid of key colors to set on the keyboard. 24 | """ 25 | # Open the file 26 | file = input("File: ") 27 | if not path.exists(file): 28 | print("That file does not exist.") 29 | exit(-1) 30 | img = Image.open(file) 31 | 32 | # Process the image 33 | w, h = img.size 34 | pixels = img.load() 35 | layout = mk.build_layout_list() 36 | w_p_c, h_p_r = (w // mk.MAX_COLS), (h // mk.MAX_ROWS) 37 | done, total = 0, mk.MAX_ROWS * mk.MAX_COLS 38 | for r in range(mk.MAX_ROWS): 39 | for c in range(mk.MAX_COLS): 40 | sums = [0, 0, 0] 41 | xrange = list(range(w_p_c * c, w_p_c * (c + 1))) 42 | yrange = list(range(h_p_r * r, h_p_r * (r + 1))) 43 | for x in xrange: 44 | for y in yrange: 45 | for i in range(3): 46 | sums[i] += pixels[x, y][i] 47 | color = (v // (w_p_c * h_p_r) for v in sums) 48 | color = tuple(map(int, color)) 49 | layout[r][c] = color 50 | 51 | done += 1 52 | print_progress(done, total) 53 | print() 54 | 55 | # Update the color of the keyboard 56 | devices = mk.detect_devices() 57 | if len(devices) == 0: 58 | print("No devices connected.") 59 | exit(-2) 60 | mk.set_device(devices[0]) 61 | mk.enable_control() 62 | mk.set_all_led_color(layout) 63 | mk.disable_control() 64 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: RedFantom 3 | License: GNU GPLv3 4 | Copyright (c) 2018-2019 RedFantom 5 | """ 6 | try: 7 | from skbuild import setup 8 | from skbuild.command.build import build 9 | except ImportError: 10 | print("scikit-build is required to build this project") 11 | raise 12 | from shutil import copyfile 13 | import glob 14 | import os 15 | 16 | 17 | def read(file_name): 18 | with open(file_name) as fi: 19 | contents = fi.read() 20 | return contents 21 | 22 | 23 | class BuildCommand(build): 24 | """Intercept the build command to copy modules""" 25 | def run(self): 26 | build.run(self) 27 | if len(glob.glob("./_skbuild/linux*")) != 0: 28 | source = os.path.join("./_skbuild/linux*/cmake-build/*notifications.so*") 29 | else: 30 | source = os.path.join("./_skbuild/cmake-build/*notifications.so*") 31 | target = os.path.join("./examples/notifications/mk_notifications.so") 32 | copyfile(glob.glob(source)[0], target) 33 | 34 | 35 | setup( 36 | name="masterkeys", 37 | version="0.3.0", 38 | packages=["masterkeys"], 39 | description="MasterKeys Control Library for Linux", 40 | author="RedFantom", 41 | url="https://github.com/RedFantom/masterkeys-linux", 42 | download_url="https://github.com/RedFantom/masterkeys-linux/releases", 43 | license="GNU GPLv3", 44 | classifiers=[ 45 | "Programming Language :: Python :: 2.7", 46 | "Programming Language :: Python :: 3", 47 | "Programming Language :: C", 48 | "Development Status :: 3 - Alpha", 49 | "Intended Audience :: Developers", 50 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 51 | "Operating System :: POSIX :: Linux", 52 | "Topic :: Software Development :: Libraries :: Python Modules", 53 | "Topic :: System :: Hardware", 54 | ], 55 | long_description=read("README.md"), 56 | long_description_content_type="text/markdown", 57 | zip_safe=False, 58 | install_requires=["scikit-build"], 59 | cmdclass={"build": BuildCommand} 60 | ) 61 | -------------------------------------------------------------------------------- /examples/notifications/notifications.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: RedFantom 3 | License: GNU GPLv3 4 | Copyright (c) 2019 RedFantom 5 | """ 6 | import gi 7 | gi.require_version("GdkPixbuf", "2.0") 8 | from gi.repository import GLib as glib 9 | from gi.repository import GdkPixbuf as pixbuf 10 | import mk_notifications 11 | import time 12 | import dbus 13 | from dbus.mainloop.glib import DBusGMainLoop 14 | import traceback 15 | import numpy 16 | from PIL import Image 17 | 18 | 19 | def notifications(bus, message): 20 | try: 21 | handle_notification(message) 22 | except Exception: 23 | print("Exception in notification handler!") 24 | print(traceback.format_exc()) 25 | 26 | 27 | def handle_notification(message): 28 | for arg in message.get_args_list(): 29 | if type(arg) == dbus.Dictionary: 30 | arg = {str(k): v for k, v in arg.items()} 31 | print(list(arg.keys())) 32 | if "image-data" not in arg or len(arg["image-data"]) != 7: 33 | print(len(arg), list(arg.keys())) 34 | print("Invalid message:", message) 35 | continue 36 | w, h, r, a, b, d, data = arg["image-data"] 37 | data = bytes([int(b) for b in data]) 38 | mode = "RGB" if not a else "RGBA" 39 | image = Image.frombytes( 40 | mode, (w, h), data, "raw", mode, r) 41 | if mode == "RGBA": 42 | image = image.convert("RGB") 43 | array = numpy.array(image) 44 | data = [[tuple(int(e) for e in column) for column in row] for row in array] 45 | color = mk_notifications.calculate_dominant_color( 46 | data, 1, len(data), len(data[0]), 25, 700, 60, 1) 47 | mk_notifications.flash_keyboard(*color) 48 | 49 | 50 | if __name__ == '__main__': 51 | r = mk_notifications.init(2, 25, 700, 60, 1, 20.0, 2, .5) 52 | if r is None: 53 | raise RuntimeError() 54 | mk_notifications.start() 55 | 56 | DBusGMainLoop(set_as_default=True) 57 | bus = dbus.SessionBus() 58 | bus.add_match_string_non_blocking("eavesdrop=true, interface='org.freedesktop.Notifications', member='Notify'") 59 | bus.add_message_filter(notifications) 60 | 61 | mainloop = glib.MainLoop() 62 | mainloop.run() 63 | print("mainloop done.") 64 | 65 | mk_notifications.stop() 66 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Author: RedFantom 2 | # License: GNU GPLv3 3 | # Copyright (c) 2018-2019 RedFantom 4 | cmake_minimum_required(VERSION 3.9) 5 | set(CMAKE_C_FLAGS "-std=c99" CACHE STRING "compiler flags") 6 | project(libmk VERSION 0.3.0 DESCRIPTION "MasterKeys RGB Library") 7 | 8 | # Dependencies 9 | set(LIBUSB_INCLUDE_DIR /usr/include/libusb-1.0) 10 | FIND_PATH(LIBUSB_INCLUDE_DIR libusb.h 11 | HINTS $ENV{LIBUSB_ROOT} 12 | PATHS ${PC_LIBUSB_INCLUDEDIR} ${PC_LIBUSB_INCLUDE_DIRS} 13 | PATH_SUFFIXES include) 14 | FIND_LIBRARY(LIBUSB_LIBRARIES NAMES usb-1.0 15 | HINTS $ENV{LIBUSB_ROOT} 16 | PATHS ${PC_LIBUSB_LIBDIR} ${PC_LIBUSB_LIBRARY_DIRS} 17 | PATH_SUFFIXES lib) 18 | message("CMake found libusb: " ${LIBUSB_INCLUDE_DIR} ", usb-1.0") 19 | find_package(X11 REQUIRED) 20 | 21 | include_directories(${LIBUSB_INCLUDE_DIR} ${X11_INCLUDE_DIRS} libmk) 22 | link_libraries(usb-1.0 ${X11_LIBRARIES}) 23 | 24 | # libmk library 25 | add_library(mk SHARED libmk/libmk.c) 26 | set_target_properties(mk PROPERTIES 27 | VERSION ${PROJECT_VERSION} 28 | PUBLIC_HEADER libmk/libmk.h) 29 | add_library(mkc SHARED libmk/libmkc.c) 30 | set_target_properties(mkc PROPERTIES 31 | VERSION ${PROJECT_VERSION} 32 | PUBLIC_HEADER libmk/libmkc.h) 33 | target_link_libraries(mkc mk) 34 | install(TARGETS mk 35 | LIBRARY DESTINATION lib 36 | PUBLIC_HEADER DESTINATION include) 37 | install(TARGETS mkc 38 | LIBRARY DESTINATION lib 39 | PUBLIC_HEADER DESTINATION include) 40 | 41 | # utils 42 | add_executable(main utils/main.c) 43 | target_link_libraries(main mk) 44 | add_executable(record utils/record.c) 45 | target_link_libraries(record mk) 46 | add_executable(ctrl utils/ctrl.c) 47 | target_link_libraries(ctrl mk mkc) 48 | 49 | # examples 50 | add_executable(ambilight examples/ambilight/ambilight.c) 51 | target_link_libraries(ambilight mk pthread) 52 | 53 | # masterkeys Python module 54 | if (SKBUILD) # python setup.py 55 | find_package(PythonInterp REQUIRED) 56 | find_package(PythonLibs REQUIRED) 57 | find_package(PythonExtensions) 58 | 59 | message("CMake found Python: " ${PYTHON_LIBRARIES}) 60 | 61 | project(masterkeys VERSION 0.3.0 DESCRIPTION "Wrapper around libmk") 62 | add_library(masterkeys MODULE 63 | masterkeys/masterkeys.c 64 | libmk/libmk.c libmk/libmk.h) 65 | python_extension_module(masterkeys) 66 | target_link_libraries(masterkeys ${PYTHON_LIBRARIES}) 67 | set_target_properties(masterkeys PROPERTIES 68 | OUTPUT_NAME "masterkeys") 69 | install(TARGETS masterkeys LIBRARY DESTINATION masterkeys) 70 | 71 | project(mk_notifications VERSION 0.3.0) 72 | add_library(mk_notifications MODULE 73 | examples/notifications/mk_notifications.c 74 | libmk/libmk.c libmk/libmk.h) 75 | target_link_libraries(mk_notifications ${PYTHON_LIBRARIES} mk) 76 | set_target_properties(mk_notifications PROPERTIES 77 | OUTPUT_NAME "mk_notifications") 78 | endif() 79 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # libmk documentation build configuration file, created by 5 | # sphinx-quickstart on Wed Feb 27 11:02:22 2019. 6 | # 7 | 8 | import subprocess 9 | import os 10 | import sys 11 | 12 | rtd_build = os.environ.get('READTHEDOCS', None) == 'True' 13 | if rtd_build: 14 | subprocess.call("doxygen doxygen.conf", shell=True) 15 | 16 | 17 | os.chdir(".." if rtd_build else "../..") 18 | print("Building documentation from:", os.getcwd()) 19 | sys.path.append(os.getcwd()) 20 | 21 | 22 | # -- General configuration ------------------------------------------------ 23 | 24 | # If your documentation needs a minimal Sphinx version, state it here. 25 | # 26 | # needs_sphinx = "1.0" 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named "sphinx.ext.*") or your custom 30 | # ones. 31 | extensions = [ 32 | "sphinx.ext.autodoc", 33 | "sphinx.ext.autosummary", 34 | "sphinx.ext.viewcode", 35 | "breathe"] 36 | 37 | # Add any paths that contain templates here, relative to this directory. 38 | templates_path = ["_templates"] 39 | 40 | # The suffix(es) of source filenames. 41 | # You can specify multiple suffix as a list of string: 42 | # 43 | # source_suffix = [".rst", ".md"] 44 | source_suffix = ".rst" 45 | 46 | # The master toctree document. 47 | master_doc = "index" 48 | 49 | # General information about the project. 50 | project = "libmk" 51 | copyright = "2019, RedFantom" 52 | author = "RedFantom" 53 | 54 | # The version info for the project you"re documenting, acts as replacement for 55 | # |version| and |release|, also used in various other places throughout the 56 | # built documents. 57 | # 58 | # The short X.Y version. 59 | version = "0.3.0" 60 | # The full version, including alpha/beta/rc tags. 61 | release = "0.3.0" 62 | 63 | # The language for content autogenerated by Sphinx. Refer to documentation 64 | # for a list of supported languages. 65 | # 66 | # This is also used if you do content translation via gettext catalogs. 67 | # Usually you set "language" from the command line for these cases. 68 | language = None 69 | 70 | # List of patterns, relative to source directory, that match files and 71 | # directories to ignore when looking for source files. 72 | # This patterns also effect to html_static_path and html_extra_path 73 | exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] 74 | 75 | # The name of the Pygments (syntax highlighting) style to use. 76 | pygments_style = "sphinx" 77 | 78 | # If true, `todo` and `todoList` produce output, else they produce nothing. 79 | todo_include_todos = True 80 | 81 | # -- Options for HTML output ---------------------------------------------- 82 | 83 | # The theme to use for HTML and HTML Help pages. See the documentation for 84 | # a list of builtin themes. 85 | # 86 | html_theme = "sphinx_rtd_theme" 87 | html_theme_path = [""] 88 | 89 | # Theme options are theme-specific and customize the look and feel of a theme 90 | # further. For a list of options available for each theme, see the 91 | # documentation. 92 | # 93 | # html_theme_options = {} 94 | 95 | # Add any paths that contain custom static files (such as style sheets) here, 96 | # relative to this directory. They are copied after the builtin static files, 97 | # so a file named "default.css" will overwrite the builtin "default.css". 98 | html_static_path = ["_static"] 99 | 100 | # Custom sidebar templates, must be a dictionary that maps document names 101 | # to template names. 102 | # 103 | # This is required for the alabaster theme 104 | # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars 105 | html_sidebars = { 106 | "**": [ 107 | "relations.html", # needs "show_related": True theme option to display 108 | "searchbox.html", 109 | ] 110 | } 111 | 112 | # -- Options for manual page output --------------------------------------- 113 | 114 | # One entry per manual page. List of tuples 115 | # (source start file, name, description, authors, manual section). 116 | man_pages = [ 117 | (master_doc, "libmk", "libmk Documentation", 118 | [author], 1) 119 | ] 120 | 121 | # -- Options for Breathe Extension ---------------------------------------- 122 | breathe_projects = { 123 | "libmk": "../doxygen/xml" if not rtd_build else "doxygen/xml" 124 | } 125 | breathe_default_project = "libmk" 126 | -------------------------------------------------------------------------------- /utils/main.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: RedFantom 3 | * License: GNU GPLv3 4 | * Copyright (c) 2018-2019 RedFantom 5 | */ 6 | #include "../libmk/libmk.h" 7 | #include 8 | #include 9 | #include 10 | #include "libusb.h" 11 | 12 | 13 | int max(int a, int b) { 14 | return a > b ? a : b; 15 | } 16 | 17 | 18 | int main(void) { 19 | /** Run some tests on the masterkeys library */ 20 | bool c = libmk_init(); 21 | if (!c) { 22 | printf("Failed to initialize LibMK Library.\n"); 23 | return -1; 24 | } 25 | LibMK_Model* models = NULL; 26 | int n = libmk_detect_devices(&models); 27 | printf("Detected %d devices.\n", n); 28 | for (int i = 0; i < n; i++) { 29 | printf("Detected device: %d, %s\n", models[i], LIBMK_MODEL_STRINGS[i]); 30 | 31 | printf(" Enabling device... "); 32 | int r = libmk_set_device(models[i], NULL); 33 | if (r == LIBMK_SUCCESS) 34 | printf("Done.\n"); 35 | else { 36 | printf("Failed: %d.\n", r); 37 | continue; 38 | } 39 | 40 | printf(" Acquiring control... "); 41 | r = libmk_enable_control(NULL); 42 | if (r != LIBMK_SUCCESS) { 43 | printf("Failed: %d.\n", r); 44 | libmk_reset(NULL); 45 | continue; 46 | } else 47 | printf("Done.\n"); 48 | 49 | LibMK_Firmware* fw; 50 | printf(" Retrieving firmware info... "); 51 | r = libmk_get_firmware_version(NULL, &fw); 52 | if (r == LIBMK_SUCCESS) { 53 | printf("Done.\n"); 54 | printf(" Keyboard firmware version: %s\n", fw->string); 55 | printf(" Keyboard firmware layout: %d\n", fw->layout); 56 | } else 57 | printf("Failed: %d.\n", r); 58 | 59 | char profile; 60 | printf(" Retrieving active profile... "); 61 | r = libmk_get_active_profile(NULL, &profile); 62 | if (r == LIBMK_SUCCESS) 63 | printf("Done: %d.\n", profile); 64 | else 65 | printf("Failed: %d.\n", r); 66 | 67 | printf(" Setting full color... "); 68 | r = libmk_set_full_color(NULL, 255, 255, 0); 69 | if (r != LIBMK_SUCCESS) 70 | printf("Failed: %d\n", r); 71 | else 72 | printf("Done.\n"); 73 | sleep(1); 74 | 75 | printf(" Setting LED effect... "); 76 | r = libmk_set_effect(NULL, LIBMK_EFF_WAVE); 77 | if (r != LIBMK_SUCCESS) 78 | printf("Failed: %d.\n", r); 79 | else 80 | printf("Done.\n"); 81 | sleep(2); 82 | 83 | printf(" Setting active profile... "); 84 | r = libmk_set_active_profile(NULL, 4); 85 | if (r != LIBMK_SUCCESS) 86 | printf("Failed: %d.\n", r); 87 | else 88 | printf("Done.\n"); 89 | 90 | printf(" Retrieving active profile... "); 91 | r = libmk_get_active_profile(NULL, &profile); 92 | if (r == LIBMK_SUCCESS) 93 | printf("Done: %d.\n", profile); 94 | else 95 | printf("Failed: %d.\n", r); 96 | 97 | unsigned char colors[LIBMK_MAX_ROWS][LIBMK_MAX_COLS][3] = {0}; 98 | for (short row=0; row < LIBMK_MAX_ROWS; row++) 99 | for (short col=0; col < LIBMK_MAX_COLS; col++) { 100 | colors[row][col][0] = 0; 101 | colors[row][col][1] = 50 * row; 102 | colors[row][col][2] = 200; 103 | } 104 | printf(" Setting LED pattern... "); 105 | r = libmk_set_all_led_color(NULL, (unsigned char*) colors); 106 | if (r != LIBMK_SUCCESS) 107 | printf("Failed: %d.\n", r); 108 | else 109 | printf("Done.\n"); 110 | sleep(4); 111 | 112 | printf(" Saving to profile %d... ", profile); 113 | r = libmk_save_profile(NULL); 114 | if (r == LIBMK_SUCCESS) 115 | printf("Done.\n"); 116 | else 117 | printf("Failed: %d.\n", r); 118 | 119 | printf(" Setting single LED... "); 120 | r = libmk_set_single_led(NULL, 0, 0, 255, 255, 0); 121 | if (r == LIBMK_SUCCESS) 122 | printf("Done.\n"); 123 | else 124 | printf("Failed: %d.\n", r); 125 | sleep(2); 126 | 127 | printf(" Disabling LED control... "); 128 | r = libmk_disable_control(NULL); 129 | if (r != LIBMK_SUCCESS) 130 | printf("Failed: %d.\n", r); 131 | else 132 | printf("Done.\n"); 133 | libmk_reset(NULL); 134 | } 135 | libmk_exit(); 136 | return 0; 137 | } 138 | -------------------------------------------------------------------------------- /utils/ctrl.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: RedFantom 3 | * License: GNU GPLv3 4 | * Copyright (c) 2018 RedFantom 5 | * 6 | * The HSV to RGB conversion algorithm was copied from: 7 | * https://stackoverflow.com/questions/3018313 8 | * The answer by Leszek Szary 9 | */ 10 | #include "../libmk/libmkc.h" 11 | #include 12 | #include 13 | #include 14 | #include "libusb.h" 15 | 16 | 17 | typedef struct RgbColor { 18 | unsigned char r; 19 | unsigned char g; 20 | unsigned char b; 21 | } RgbColor; 22 | 23 | typedef struct HsvColor { 24 | unsigned char h; 25 | unsigned char s; 26 | unsigned char v; 27 | } HsvColor; 28 | 29 | 30 | RgbColor* HsvToRgb(HsvColor* hsv) { 31 | RgbColor* rgb = malloc(sizeof(RgbColor)); 32 | unsigned char region, remainder, p, q, t; 33 | 34 | if (hsv->s == 0) { 35 | rgb->r = hsv->v; 36 | rgb->g = hsv->v; 37 | rgb->b = hsv->v; 38 | return rgb; 39 | } 40 | 41 | region = hsv->h / 43; 42 | remainder = (hsv->h - (region * 43)) * 6; 43 | 44 | p = (hsv->v * (255 - hsv->s)) >> 8; 45 | q = (hsv->v * (255 - ((hsv->s * remainder) >> 8))) >> 8; 46 | t = (hsv->v * (255 - ((hsv->s * (255 - remainder)) >> 8))) >> 8; 47 | 48 | switch (region) { 49 | case 0: 50 | rgb->r = hsv->v; rgb->g = t; rgb->b = p; 51 | break; 52 | case 1: 53 | rgb->r = q; rgb->g = hsv->v; rgb->b = p; 54 | break; 55 | case 2: 56 | rgb->r = p; rgb->g = hsv->v; rgb->b = t; 57 | break; 58 | case 3: 59 | rgb->r = p; rgb->g = q; rgb->b = hsv->v; 60 | break; 61 | case 4: 62 | rgb->r = t; rgb->g = p; rgb->b = hsv->v; 63 | break; 64 | default: 65 | rgb->r = hsv->v; rgb->g = p; rgb->b = q; 66 | break; 67 | } 68 | return rgb; 69 | } 70 | 71 | 72 | 73 | int main(void) { 74 | libmk_init(); 75 | printf("Detecting devices...\n"); 76 | LibMK_Model* models = NULL; 77 | int n = libmk_detect_devices(&models); 78 | printf("%d devices detected.\n", n); 79 | for (int i=0; i < n; i++) { 80 | printf(" Detected: %d\n", models[i]); 81 | LibMK_Handle* handle; 82 | int r = libmk_set_device(models[i], &handle); 83 | if (r != LIBMK_SUCCESS) { 84 | printf(" Could not open this device.\n"); 85 | continue; 86 | } 87 | 88 | LibMK_Controller* ctrl = libmk_create_controller(handle); 89 | if (ctrl == NULL) { 90 | printf(" Could not create controller for this device.\n"); 91 | continue; 92 | } 93 | 94 | fprintf(stdout, " Starting controlller... "); 95 | libmk_start_controller(ctrl); 96 | printf("Done.\n"); 97 | 98 | fprintf(stdout, " Scheduling instructions... "); 99 | 100 | unsigned char red[3] = {255, 0, 0}; 101 | LibMK_Instruction* full = libmk_create_instruction_flash(red, 10000, 255); 102 | unsigned int n = libmk_sched_instruction(ctrl, full); 103 | 104 | unsigned char yellow[3] = {255, 255, 0}; 105 | full = libmk_create_instruction_full(yellow); 106 | full->duration = 1000000; 107 | libmk_sched_instruction(ctrl, full); 108 | 109 | unsigned char blank[3] = {0}; 110 | LibMK_Instruction* wave = libmk_create_instruction_full(blank); 111 | LibMK_Instruction* a, * b; 112 | a = wave; 113 | HsvColor color; 114 | color.s = 255; 115 | color.v = 255; 116 | 117 | unsigned char map[LIBMK_MAX_ROWS][LIBMK_MAX_COLS][3]; 118 | for (int i=0; i<1000; i++) { 119 | for (int r=0; rr; 124 | map[r][c][1] = rgb->g; 125 | map[r][c][2] = rgb->b; 126 | free(rgb); 127 | } 128 | } 129 | b = libmk_create_instruction_all(map); 130 | b->duration = 10000; 131 | a->next = b; 132 | a = b; 133 | } 134 | libmk_sched_instruction(ctrl, wave); 135 | 136 | 137 | printf("Done: %d.\n", full->id); 138 | 139 | fprintf(stdout, " Awaiting controller... "); 140 | libmk_wait_controller(ctrl); 141 | printf("Done.\n"); 142 | 143 | printf("\n Now the controller will automatically exit after all instructions are done.\n"); 144 | printf(" You can let your program do other stuff while the instructions execute.\n\n"); 145 | 146 | LibMK_Controller_State s = libmk_join_controller(ctrl, 40); 147 | if (s != LIBMK_STATE_STOPPED) 148 | printf(" Could not stop the Controller: %d\n", s); 149 | libmk_free_handle(handle); 150 | printf(" Controller test ended.\n"); 151 | } 152 | } -------------------------------------------------------------------------------- /utils/record.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: RedFantom 3 | * License: GNU GPLv3 4 | * Copyright (c) 2018-2019 RedFantom 5 | */ 6 | #include "../libmk/libmk.h" 7 | #include 8 | #include 9 | #include 10 | 11 | 12 | void write_file(unsigned char layout[LIBMK_MAX_ROWS][LIBMK_MAX_COLS], 13 | int bVendor, int bDevice, LibMK_Firmware* fw) { 14 | /** Write a layout matrix with device details to a file 15 | * 16 | * The layout is stored in a file so that it can be submitted into the code 17 | * and then more devices can be supported by the library. The vendor and 18 | * device id are included in hex format, followed by the layout in the same 19 | * format as it is included in libmk.c for each layout. 20 | */ 21 | int r, c; 22 | FILE* file = fopen("layout.c", "w"); 23 | fprintf(file, "{\n"); 24 | fprintf(file, "Vendor: 0x%04x, Device: 0x%04x, Firmware: %d.%d.%d\n", 25 | bVendor, bDevice, fw->major, fw->minor, fw->patch); 26 | for (r=0; r < LIBMK_MAX_ROWS; r++) { 27 | fprintf(file, "\t{"); 28 | for (c=0; c < LIBMK_MAX_COLS; c++) { 29 | fprintf(file, "0x%02x", layout[r][c]); 30 | if (c != LIBMK_MAX_COLS - 1) 31 | fprintf(file, ", "); 32 | } 33 | fprintf(file, "},\n"); 34 | } 35 | fprintf(file, "}\n"); 36 | fclose(file); 37 | } 38 | 39 | 40 | int main(void) { 41 | /** Loop over all offsets for keys and match them to key coordinates 42 | * 43 | * Requires user input in the form of 'r,c' to read the key 44 | * coordinates. The key coordinates must be matched to the layout 45 | * of the specific keyboard. 46 | */ 47 | libmk_init(); 48 | LibMK_Model* models; 49 | int result; 50 | result = libmk_detect_devices(&models); 51 | if (result < 0) 52 | return -1; 53 | 54 | LibMK_Model model; 55 | if (result == 0) { 56 | printf("No devices detected.\n"); 57 | return 0; 58 | } else if (result == 1) { 59 | printf("Detected model %d.\n", models[0]); 60 | model = models[0]; 61 | } else { 62 | printf("Detected %d devices:\n", result); 63 | for (short i=0; i < result; i++) 64 | printf("Model: %d\n", models[i]); 65 | printf("Please select the model to analyze: "); 66 | int r = scanf("%d", &model); 67 | if (r != 1) 68 | return -3; 69 | } 70 | 71 | LibMK_Handle* handle; 72 | result = libmk_set_device(model, &handle); 73 | if (result < 0) 74 | return -2; 75 | 76 | unsigned char layout[LIBMK_MAX_ROWS][LIBMK_MAX_COLS]; 77 | int r, c; 78 | for (r=0; r < LIBMK_MAX_ROWS; r++) 79 | for (c=0; c < LIBMK_MAX_COLS; c++) 80 | layout[r][c] = 0x00; 81 | libmk_enable_control(handle); 82 | 83 | LibMK_Firmware* fw; 84 | result = libmk_get_firmware_version(handle, &fw); 85 | if (result != LIBMK_SUCCESS) { 86 | printf("Failed to retrieve keyboard firmware information: %d\n", result); 87 | libmk_disable_control(handle); 88 | libmk_free_handle(handle); 89 | libmk_exit(); 90 | return -4; 91 | } 92 | printf("Keyboard Firmware version: %d.%d.%d\n", fw->major, fw->minor, fw->patch); 93 | 94 | printf("Now, one by one, the keys will be turned on in the color red.\n" 95 | "Please enter the coordinates of the key that was turned on in \n" 96 | "the format `row,col\\n`. Use `-1,-1` to indicate that no led \n" 97 | "was turned on. Use `-2,-2` to indicate that all leds have \n" 98 | "passed.\n\n"); 99 | 100 | for (unsigned char offset=0x00; offset < 0xFF; offset++) { 101 | unsigned char* packet = libmk_build_packet( 102 | 8, 0xC0, 0x01, 0x01, 0x00, 0x00, 0xFF, 0x00, 0x00); 103 | packet[4] = offset; 104 | packet[5] = 0xFF; 105 | result = libmk_send_packet(handle, packet); 106 | if (result != LIBMK_SUCCESS) { 107 | printf("LibMK Error Code: %d\n", result); 108 | libmk_disable_control(handle); 109 | libmk_free_handle(handle); 110 | libmk_exit(); 111 | return -3; 112 | } 113 | printf("Offset %d, color red: ", offset); 114 | int read = 0; 115 | do { 116 | read = scanf("%d,%d", &r, &c); 117 | if (read != 2) 118 | printf("Invalid input.\n"); 119 | } while (read != 2); 120 | if (r == -1 || c == -1) 121 | continue; 122 | else if (r == -2 || c == -2) 123 | break; 124 | layout[r][c] = offset; 125 | packet = libmk_build_packet( 126 | 8, 0xC0, 0x01, 0x01, 0x00, 0x00, 0x00, 0xFF, 0x00); 127 | packet[4] = offset; 128 | result = libmk_send_packet(handle, packet); 129 | if (result != LIBMK_SUCCESS) { 130 | printf("LibMK Error Code: %d\n", result); 131 | libmk_disable_control(handle); 132 | libmk_free_handle(handle); 133 | libmk_exit(); 134 | return -3; 135 | } 136 | write_file(layout, handle->bVendor, handle->bDevice, fw); 137 | } 138 | libmk_disable_control(handle); 139 | libmk_free_handle(handle); 140 | printf("\nPlease share the created file along with your model on the \n" 141 | "GitHub repository to help support more devices.\n"); 142 | libmk_exit(); 143 | return 0; 144 | } 145 | -------------------------------------------------------------------------------- /INTERFACE.md: -------------------------------------------------------------------------------- 1 | # MasterKeys Pro Interface Description 2 | This document assumes at least some knowledge of how USB works. If you 3 | do not understand the different transfer modes, interfaces and endpoints 4 | described by the USB standard, it is recommended that you first spend 5 | some time understanding the details of that. 6 | 7 | ## Device Descriptors 8 | The Cooler Master `bVendor` is `0x2516`, which is the same for all 9 | keyboards. However, each keyboard has a different `bDevice`, even 10 | devices with the same name. 11 | 12 | My own keyboard has a `bDevice` value of `0x003b`. However, the [USB 13 | ID repository](https://usb-ids.gowdy.us/read/UD/2516) also reports 14 | `0x0047` as a `bDevice` for the `MasterKeys Pro L`. 15 | 16 | **Revisions and switches** 17 | 18 | Personally, I would guess that the differences in `bDevice` values stem 19 | from two things. First off, there are at least two revisions of the 20 | `MasterKeys Pro L` keyboard. The first revision was prone to [having 21 | some issues with specific keys](https://www.reddit.com/r/MechanicalKeyboards/comments/4ui8v9/help_cooler_master_masterkeys_pro_l_nonresponsive/). 22 | The second revision (as I can attest to) does not have these issues. 23 | 24 | Second, there might be different device ids for the keyboards with 25 | different layouts. There are two main layouts available (independent of 26 | QWERTY OR QWERTZ): US (ANSI) and ISO (EU). My device is ANSI. 27 | 28 | **Library Implementation** 29 | 30 | This library does not implement device detection by using the vendor 31 | and device ids, but instead loops over a list of the devices and checks 32 | if the descriptor strings (`iManufacturer` and `iProduct`) contain the 33 | identifying marks of a `MasterKeys` keyboard. 34 | 35 | ## Connection 36 | The MasterKeys keyboard present themselves to the system with three 37 | interfaces, each of them recognized as a HID device. These interfaces 38 | are: 39 | ```markdown 40 | - Interface 0: HID Device 41 | EndPoint 1 IN, 8 byte packets, 0x81 42 | - Interface 1: HID Device 43 | EndPoint 3 IN, 64 byte packets, 0x83 44 | EndPoint 4 OUT, 64 byte packets, 0x04 45 | - Interface 2: HID Device 46 | EndPoint 2 IN, 64 byte packets, 0x82 47 | ``` 48 | 49 | It is the second interface, numbered 1, with the endpoints 3 and 4 that 50 | is used for LED control. The commands should be written in 64 byte 51 | packets to EndPoint 4, return data is received on EndPoint 4. This data 52 | can be the data stored in the keyboard itself and confirmation messages. 53 | 54 | ## Packets 55 | All packets must be 64 bytes in size. The packets are created in the 56 | library using the `libmk_build_packet` function. At the top of `libmk.c` 57 | is a list of packet headers (first byte) and opcodes (second byte). 58 | There ought to be a pattern discoverable in the headers and opcodes, 59 | but so far it is unclear what each and exact bit does. Further analysis 60 | of the protocol with more instructions may yield more insight. 61 | 62 | **Disclaimer**: Following is a list of packet descriptions. Note that 63 | these were written based on the `MasterKeys Pro L ANSI`, and that 64 | different keyboards, particularly with only monochrome LEDs, may work 65 | differently. 66 | 67 | #### Enable 68 | Enable keyboard LED control. Control is not automatically released. Sets 69 | the currently active LED profile to be altered. 70 | ```hex 71 | 41 02 00 ... 72 | ``` 73 | 74 | #### Disable 75 | Release keyboard LED control. Automatically released (and then 76 | reclaimed) when a new Enable packet is received. 77 | ```hex 78 | 41 00 00 ... 79 | ``` 80 | 81 | #### Flush 82 | Flush the keyboard color data that is in cache on the chip to the 83 | actual LED controllers. Used in `libmk_set_all_led_color`. 84 | ```hex 85 | 50 55 00 ... 86 | ``` 87 | 88 | #### Effects 89 | **Simple**: 90 | An effect can simply be enabled based on the last given settings 91 | (generally default) using the 'simple' effect setting method. 92 | ```hex 93 | 41 01 00 ... 94 | 95 | 51 28 00 00 xx 00 ... 96 | xx: Effect number (enum LibMK_Effect) 97 | ``` 98 | The first packet somehow puts the keyboard into a different mode. The 99 | exact purpose is currently unknown. The second packet sets the actual 100 | effect. 101 | 102 | **Detailed**: 103 | Effects can take additional arguments through specific bytes. 104 | ```hex 105 | 51 28 00 00 nn ss dd aa FF FF fr fg fb br bg bb FF FF ... 106 | nn: Effect number (enum LibMK_Effect) 107 | ss: Effect speed 108 | dd: Effect direction (00, 02, 04, 06, %8) 109 | aa: Effect amount (purpose differs wildly) 110 | f*: Foreground color r, g, b 111 | b*: Background color r, g, b 112 | The rest of the packet is filled with FF. 113 | ``` 114 | 115 | #### All LED colors 116 | Effect `LIBMK_EFF_CUSTOM` should be enabled before sending these 117 | packets. The amount of packets (probably) depends on the size of the 118 | keyboard. The offset conversion tables are used to build the packets. 119 | Each packet contains the data for `LIBMK_ALL_LED_PER_PCK` LEDs. For 120 | a full keyboard, that is `LIBMK_ALL_LED_PCK_NUM` packets. 121 | ```hex 122 | 51 A8 xx 00 00 yy yy yy ... 00 00 00 123 | 124 | xx: Offset of this package: 2 * (key offset % LIBMK_ALL_PER_PCK) 125 | 00, 02, 04 ... etc. 126 | yy: 3 element color values for 16 LEDs: rr gg bb rr gg bb ... etc. 127 | The rest of the packet is filled up with zeros. 128 | ``` 129 | 130 | #### Single LED color 131 | Currently lights only a single LED on the keyboard (so even if 132 | `libmk_set_single_led` is called multiple times, the previously lit 133 | LEDs will turn off once a new one is turned on). There should be a way 134 | to allow setting the color of multiple LEDs this way, but that it is 135 | as of yet unclear how to achieve this. 136 | ```hex 137 | C0 01 01 00 oo rr gg bb 00 00 ... 138 | oo: Key offset 139 | ``` 140 | 141 | ## TODO-list 142 | - Determine how to read effect profiles from the keyboard 143 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MasterKeys Linux SDK 2 | [![Build Status](https://travis-ci.com/RedFantom/masterkeys-linux.svg?token=UBcv5ZyxSrELyQhSpadq&branch=master)](https://travis-ci.com/RedFantom/masterkeys-linux) 3 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) 4 | [![PyPI version](https://badge.fury.io/py/masterkeys.svg)](https://pypi.org/project/masterkeys/) 5 | [![Documentation](https://readthedocs.org/projects/masterkeys-linux/badge/?version=latest)](https://masterkeys-linux.readthedocs.io/en/latest) 6 | 7 | Cooler Master provides an SDK for its MasterKeys series of keyboards 8 | for use under Windows, but not for Linux. The SDK communicates with an 9 | OUT-endpoint in the USB HID-device of the keyboard. This library aims to 10 | make this communication accessible from Linux by using libusb. 11 | 12 | This is the first time I have written such a large project in C, let 13 | alone an actual shared library, so you may spot things that are bad 14 | practice, bugs or other issues. Please let me know in the issues section 15 | if you spot anything! 16 | 17 | ## Disclaimer 18 | This library is not endorsed or supported by Cooler Master Inc. or any 19 | of its affiliates. They have explicitly refused to help in the 20 | development of this library. There is no official support for this 21 | library from Cooler Master Inc. Any and all questions should be posted 22 | on the issues page. 23 | 24 | ## Device support 25 | As Cooler Master Inc. has not provided any support, this library can 26 | only support a limited amount of devices, specifically, it can only 27 | support devices for which the `record` executable target has been 28 | executed. This program uses the library to register an offset for each 29 | key, which is required for the library to be able to control individual 30 | keys. Effects and full lighting colors can be set regardless of these 31 | offsets. 32 | 33 | The current list of supported devices includes: 34 | - MasterKeys Pro L RGB ANSI 35 | - MasterKeys Pro S RGB ANSI (untested) 36 | - MasterKeys Pro L RGB ISO (untested) 37 | 38 | If you would like for your device to be supported as well, please run 39 | the `record` executable. Enter the row and column coordinates of each 40 | key according to the Cooler Master reference each time for the key that 41 | lights up in red. The shared `layout.c` can be attached to an issue, and 42 | then your device is added in no-time! 43 | 44 | Keyboards with only monochrome lighting may use a different protocol and 45 | thus they would probably require more modifications than just adding a 46 | key layout matrix. Do not hesitate to open an issue if you have a 47 | monochrome keyboard, would like to see support and are willing to do 48 | some USB packet sniffing. 49 | 50 | ## Compiling and installing 51 | To be able to compile and install any of the targets in this library, 52 | `cmake` and its dependencies are required. Depending on your specific 53 | distribution, the name of the packages (if they are provided) may 54 | differ from the ones given here. The reference commands are for Ubuntu. 55 | ```bash 56 | # libx11-dev is for the AmbiLight and notifications examples 57 | # python3-gtk2.0 is for the notifications example 58 | sudo apt-get install cmake libusb-1.0.0-dev libx11-dev 59 | cd Source/masterkeys-linux # Or wherever you have cloned the repo 60 | 61 | # Builds library, utilities and C examples 62 | # Exclude them from the file if you don't want them to be built 63 | cmake . 64 | make 65 | sudo make install 66 | 67 | # For the Python library (system-wide install) and Python examples 68 | sudo python -m pip install scikit-build # Needed for building 69 | sudo python -m pip install PyGObject dbus-python # Notifications example 70 | sudo python setup.py build install # Python examples not installed 71 | 72 | # Or if you would rather install from PyPI, still requires dependencies 73 | sudo python -m pip install masterkeys 74 | ``` 75 | 76 | Wheels are not provided at this time because building `manylinux` wheels 77 | requires a different environment. It is considered as a possibility 78 | though. Until that time, it is possible to use the normal `linux_x86_64` 79 | wheels provided on the [releases-page](https://github.com/RedFantom/masterkeys-linux/releases). 80 | 81 | ## Contributing 82 | Pull Requests and contributions in other forms (such as issue reports) 83 | as well as tips or possible improvements are very welcome! As mentioned, 84 | this is my first C library, and any help is greatly appreciated! If it 85 | comes in the form of code, you will be credited for your work in the 86 | copyright notice. 87 | 88 | If you would like for your device to be supported, please read the 89 | `Device Support` section of this file. 90 | 91 | Given the small size of this project, there is no code of conduct or 92 | `CONTRIBUTING.md` with guidelines, but keep things professional. Also, 93 | use descriptive commit messages. Force pushing to forks while a PR is 94 | open is fine (as long as it does not completely remove the 95 | contributions). 96 | 97 | ## License 98 | ```license 99 | MasterKeys Linux - C Library to control RGB keyboards 100 | Copyright (C) 2018 RedFantom 101 | 102 | This program is free software: you can redistribute it and/or modify 103 | it under the terms of the GNU General Public License as published by 104 | the Free Software Foundation, version 3. 105 | 106 | This program is distributed in the hope that it will be useful, 107 | but WITHOUT ANY WARRANTY; without even the implied warranty of 108 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 109 | GNU General Public License for more details. 110 | 111 | You should have received a copy of the GNU General Public License 112 | along with this program. If not, see . 113 | ``` 114 | 115 | ## Credits 116 | Part of the implementation of the `libmk` library is based on the more 117 | extensive protocol description written by [`chmod222`](https://github.com/chmod222), 118 | available under the LGPLv3 license in [`libcmmk`](https://github.com/chmod222/libcmmk), 119 | which has the same goal as this project. 120 | -------------------------------------------------------------------------------- /examples/notifications/capture.h: -------------------------------------------------------------------------------- 1 | /** Author: RedFantom 2 | * License: GNU GPLv3 3 | * Copyright (c) 2018-2019 RedFantom 4 | */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | 14 | typedef struct CaptureArgs { 15 | unsigned char* target_color; 16 | pthread_mutex_t* target_lock; 17 | pthread_mutex_t* exit_lock; 18 | pthread_mutex_t* keyboard_lock; 19 | bool* exit_flag; 20 | Display* display; 21 | Window root; 22 | XWindowAttributes gwa; 23 | int divider; 24 | int saturation_bias; 25 | int upper_threshold; 26 | int lower_threshold; 27 | bool brightness_norm; 28 | } CaptureArgs; 29 | 30 | 31 | typedef struct Screenshot { 32 | unsigned char* data; 33 | unsigned int w, h; 34 | } Screenshot; 35 | 36 | 37 | unsigned char calc_diff(unsigned char one, unsigned char two) { 38 | /** Calculate the absolute difference between two values */ 39 | int diff = (int) one - (int) two; 40 | return diff < 0 ? -diff : diff; 41 | } 42 | 43 | 44 | CaptureArgs* init_capture(int divider, int sat_bias, int lower, int upper, 45 | bool brightness_norm, unsigned char* target_color, 46 | pthread_mutex_t* target_lock, bool* exit_flag, 47 | pthread_mutex_t* exit_lock, pthread_mutex_t* kb_lock) { 48 | /** Initialize a CaptureArgs struct that can be passed as thread argument */ 49 | CaptureArgs* args = (CaptureArgs*) malloc(sizeof(CaptureArgs)); 50 | 51 | args->divider = divider; 52 | args->saturation_bias = sat_bias; 53 | args->lower_threshold = lower; 54 | args->upper_threshold = upper; 55 | args->brightness_norm = brightness_norm; 56 | args->target_color = target_color; 57 | args->target_lock = target_lock; 58 | args->exit_flag = exit_flag; 59 | args->exit_lock = exit_lock; 60 | args->keyboard_lock = kb_lock; 61 | 62 | args->display = XOpenDisplay(NULL); 63 | args->root = DefaultRootWindow(args->display); 64 | if (XGetWindowAttributes(args->display, args->root, &(args->gwa)) < 0) { 65 | XCloseDisplay(args->display); 66 | free(args); 67 | return NULL; 68 | } 69 | 70 | return args; 71 | } 72 | 73 | 74 | void capture(Screenshot** screenshot, XWindowAttributes gwa, 75 | Display* display, Window root) { 76 | /** Capture screenshot and save it to Screenshot struct 77 | * 78 | * The data captured from X.org is in long int format (32-bit 79 | * integers), which have to be converted to three separate 8-bit 80 | * integers representing the pixels. 81 | */ 82 | (*screenshot) = (Screenshot*) malloc(sizeof(Screenshot)); 83 | int width = gwa.width, height = gwa.height; 84 | 85 | (*screenshot)->data = (unsigned char*) malloc( 86 | width*height*3*sizeof(unsigned char)); 87 | (*screenshot)->w = width; 88 | (*screenshot)->h = height; 89 | 90 | XImage* img = XGetImage( 91 | display, root, 0, 0, width, height, AllPlanes, ZPixmap); 92 | unsigned long masks[3] = { 93 | img->red_mask, img->green_mask, img->blue_mask}; 94 | 95 | for (int x=0; xdata[(x+width*y) * 3 + i] = 100 | (unsigned char) (pix >> (2-i) * 8); 101 | } 102 | 103 | XDestroyImage(img); 104 | } 105 | 106 | 107 | void calc_dominant_color(unsigned char* data, int w, int h, 108 | unsigned char* target, int divider, int sat_bias, 109 | int lower, int upper, bool brightness_norm) { 110 | /** Calculate the dominant color in an array of pixels 111 | * 112 | * 113 | */ 114 | unsigned char temp[3]; 115 | unsigned long colors[3] = {0}; 116 | unsigned long n_pixels = 0; 117 | 118 | divider = divider == 0 ? 1 : divider; 119 | int width = w / divider; 120 | 121 | /// Summing of pixels fitting criteria 122 | for (int x=0; x max_diff ? diff : max_diff; 131 | sum += pixel[i]; 132 | } 133 | if (sum < lower || sum > upper || max_diff < sat_bias) 134 | continue; 135 | for (int i=0; i<3; i++) 136 | colors[i] += pixel[i]; 137 | n_pixels += 1; 138 | } 139 | } 140 | 141 | /// Averaging 142 | unsigned char max = 0; 143 | for (int i=0; i<3; i++) { 144 | if (n_pixels == 0) { 145 | target[i] = 0xFF; // Error condition 146 | continue; 147 | } 148 | target[i] = (unsigned char) (colors[i] / n_pixels); 149 | max = target[i] > max ? target[i] : max; 150 | } 151 | 152 | max = max == 0 ? 0xFF : max; 153 | 154 | /// Normalization 155 | if (brightness_norm && max != 0xFF) 156 | for (int i=0; i<3; i++) 157 | target[i] = (unsigned char) ((double) target[i] * (255.0 / (double) max)); 158 | 159 | } 160 | 161 | 162 | void capturer(struct CaptureArgs* args) { 163 | /** Function designed to be run in a thread, captures screenshots 164 | * 165 | */ 166 | unsigned char target[3], previous[3]; 167 | 168 | while (true) { 169 | pthread_mutex_lock(args->exit_lock); 170 | bool exit = *(args->exit_flag); 171 | pthread_mutex_unlock(args->exit_lock); 172 | if (exit) 173 | break; 174 | 175 | Screenshot* screenshot; 176 | 177 | capture(&screenshot, args->gwa, args->display, args->root); 178 | 179 | calc_dominant_color(screenshot->data, screenshot->w, screenshot->h, 180 | target, args->divider, args->saturation_bias, 181 | args->lower_threshold, args->upper_threshold, 182 | args->brightness_norm); 183 | 184 | free(screenshot->data); 185 | free(screenshot); 186 | 187 | pthread_mutex_lock(args->keyboard_lock); 188 | pthread_mutex_lock(args->target_lock); 189 | for (int i=0; i<3; i++) { 190 | args->target_color[i] = target[i]; 191 | previous[i] = target[i]; 192 | } 193 | pthread_mutex_unlock(args->target_lock); 194 | pthread_mutex_unlock(args->keyboard_lock); 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /examples/ambilight/ambilight.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: RedFantom 3 | * License: GNU GPLv3 4 | * Copyright (c) 2018-2019 RedFantom 5 | */ 6 | #include "libmk.h" 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | 17 | #define MAX_WIDTH -1 // 0: Full width, -1: / 2, n_pixels otherwise 18 | #define SATURATION_BIAS 60 19 | #define BRIGHTNESS_NORM 20 | #define UPPER_TRESHOLD 700 21 | #define LOWER_TRESHOLD 25 22 | 23 | 24 | bool exit_requested = false; 25 | unsigned char target_color[3] = {0}; 26 | pthread_mutex_t exit_req_lock = PTHREAD_MUTEX_INITIALIZER; 27 | pthread_mutex_t target_color_lock = PTHREAD_MUTEX_INITIALIZER; 28 | pthread_mutex_t keyboard_lock = PTHREAD_MUTEX_INITIALIZER; 29 | Display* display; 30 | Window root; 31 | XWindowAttributes gwa; 32 | 33 | 34 | typedef struct Screenshot { 35 | unsigned char* data; 36 | unsigned int width, height; 37 | } Screenshot; 38 | 39 | 40 | void interrupt_handler(int signal) { 41 | /** Handle a Control-C command to exit the loop */ 42 | pthread_mutex_lock(&exit_req_lock); 43 | exit_requested = true; 44 | pthread_mutex_unlock(&exit_req_lock); 45 | } 46 | 47 | 48 | int capture_screenshot(Screenshot** screenshot) { 49 | /** Capture a screenshot and store it in an array */ 50 | (*screenshot) = (Screenshot*) malloc(sizeof(Screenshot)); 51 | int width = gwa.width, height = gwa.height; 52 | (*screenshot)->data = (unsigned char*) malloc( 53 | width * height * 3 * sizeof(unsigned char)); 54 | 55 | XImage* img = XGetImage( 56 | display, root, 0, 0, width, height, AllPlanes, ZPixmap); 57 | 58 | unsigned long rm = img->red_mask, gm = img->green_mask, bm = img->blue_mask; 59 | unsigned long masks[3] = {rm, gm, bm}; 60 | unsigned char pixel[3]; 61 | 62 | for (int x=0; x < width; x++) 63 | for (int y = 0; y < height; y++) { 64 | unsigned long pix = XGetPixel(img, x, y); 65 | for (int i = 0; i < 3; i++) 66 | (*screenshot)->data[(x + width * y) * 3 + i] = 67 | (unsigned char) (pix >> (2 - i) * 8); 68 | } 69 | XDestroyImage(img); 70 | return 0; 71 | } 72 | 73 | 74 | void* calculate_keyboard_color(void *void_ptr) { 75 | /** Continuously capture screens and calculate the dominant colour 76 | * 77 | * Options are given in defines: 78 | * MAX_WIDTH: If 0, uses full screen width. If -1, uses only the 79 | * first half of the pixel columns for double monitors. Otherwise, 80 | * limited to value of MAX_WIDTH. 81 | * LOWER_THRESHOLD: Minimum summed value of the RGB triplet, used 82 | * for filtering out dark pixels. 83 | * UPPER_THRESHOLD: Maximum summed value of the RGB triplet, used 84 | * for filtering out bright pixels. 85 | * SATURATION_BIAS: Minimum required difference between any pair 86 | * of bytes of the RGB triplet of a pixel. 87 | * BRIGHTNESS_NORM: If defined, target colors sent to the keyboard 88 | * are scaled so that at least one of the RGB values of the 89 | * triplet is the maximum of 255. 90 | */ 91 | Screenshot* screen; 92 | 93 | while (true) { 94 | 95 | pthread_mutex_lock(&exit_req_lock); 96 | if (exit_requested) { 97 | printf("Exit requested.\n"); 98 | pthread_mutex_unlock(&exit_req_lock); 99 | break; 100 | } 101 | pthread_mutex_unlock(&exit_req_lock); 102 | if (capture_screenshot(&screen) < 0) { 103 | int code = -2; 104 | pthread_exit(&code); 105 | } 106 | 107 | int w = gwa.width, h = gwa.height; 108 | 109 | unsigned char temp[3]; 110 | unsigned long colors[3] = {0}; 111 | unsigned long n_pixels = 0; 112 | unsigned int sum; 113 | 114 | int lim; 115 | if (MAX_WIDTH == 0) { 116 | lim = w; 117 | } else if (MAX_WIDTH == -1) { 118 | lim = w / 2; 119 | } else { 120 | lim = MAX_WIDTH; 121 | } 122 | 123 | // Sum 124 | for (int x = 0; x < lim; x++) { 125 | for (int y = 0; y < h; y++) { 126 | sum = 0; 127 | int max_diff = 0; 128 | for (int i = 0; i < 3; i++) { 129 | int first = i, second = i + 1; 130 | if (i == 2) 131 | second = 0; 132 | int diff = screen->data[(x + y * w) * 3 + first] - 133 | screen->data[(x + y * w) * 3 + second]; 134 | if (diff > max_diff) 135 | max_diff = diff; 136 | 137 | temp[i] = screen->data[(x + y * w) * 3 + i]; 138 | sum += temp[i]; 139 | } 140 | if (sum < LOWER_TRESHOLD || 141 | sum > UPPER_TRESHOLD || 142 | max_diff < SATURATION_BIAS) 143 | continue; 144 | for (int i = 0; i < 3; i++) 145 | colors[i] += temp[i]; 146 | n_pixels += 1; 147 | } 148 | } 149 | unsigned char color[3]; 150 | unsigned char max = 0; 151 | 152 | // Average 153 | for (int i = 0; i < 3; i++) { 154 | if (n_pixels == 0) { 155 | color[i] = 0xFF; 156 | continue; 157 | } 158 | color[i] = (unsigned char) (colors[i] / n_pixels); 159 | if (color[i] > max) 160 | max = color[i]; 161 | } 162 | 163 | #ifdef BRIGHTNESS_NORM 164 | // Normalize 165 | if (max != 0) 166 | for (int i = 0; i < 3; i++) 167 | color[i] = (unsigned char) ((int) color[i] * (255.0 / max)); 168 | #endif 169 | 170 | // Copy color over to thread-safe variable 171 | pthread_mutex_lock(&target_color_lock); 172 | for (int i=0; i < 3; i++) 173 | target_color[i] = color[i]; 174 | pthread_mutex_unlock(&target_color_lock); 175 | 176 | // Clean up 177 | free(screen->data); 178 | free(screen); 179 | } 180 | pthread_exit(0); 181 | } 182 | 183 | 184 | void* update_keyboard_color(void* ptr) { 185 | unsigned char color[3] = {0}, prev[3] = {0}; 186 | while (true) { 187 | pthread_mutex_lock(&exit_req_lock); 188 | if (exit_requested) { 189 | pthread_mutex_unlock(&exit_req_lock); 190 | break; 191 | } 192 | pthread_mutex_unlock(&exit_req_lock); 193 | 194 | int diff; 195 | bool equal = true; 196 | pthread_mutex_lock(&target_color_lock); 197 | for (int i=0; i < 3; i++) { 198 | diff = (int) target_color[i] - color[i]; 199 | prev[i] = color[i]; 200 | color[i] += (unsigned char) (diff / 20.0); 201 | equal = (prev[i] == target_color[i]) && equal; 202 | } 203 | pthread_mutex_unlock(&target_color_lock); 204 | 205 | if (equal) 206 | continue; 207 | 208 | pthread_mutex_lock(&keyboard_lock); 209 | int r = libmk_set_full_color(NULL, color[0], color[1], color[2]); 210 | if (r != LIBMK_SUCCESS) 211 | printf("LibMK Error: %d\n", r); 212 | pthread_mutex_unlock(&keyboard_lock); 213 | 214 | struct timespec time; 215 | time.tv_nsec = 100000000 / 4; 216 | nanosleep(&time, NULL); 217 | } 218 | pthread_exit(0); 219 | } 220 | 221 | 222 | int main() { 223 | /** Run a loop that grabs a screenshot and updated lighting */ 224 | signal(SIGINT, interrupt_handler); 225 | libmk_init(); 226 | 227 | // Set up libmk 228 | LibMK_Model* devices; 229 | int n = libmk_detect_devices(&devices); 230 | if (n < 0) { 231 | printf("libmk_detect_devices failed: %d\n", n); 232 | return n; 233 | } 234 | libmk_set_device(devices[0], NULL); 235 | libmk_enable_control(NULL); 236 | 237 | // Open the XDisplay 238 | display = XOpenDisplay(NULL); 239 | root = DefaultRootWindow(display); 240 | if (XGetWindowAttributes(display, root, &gwa) < 0) 241 | return -1; 242 | 243 | pthread_t keyboard, screenshot; 244 | 245 | // Run the loop 246 | pthread_create(&screenshot, NULL, calculate_keyboard_color, NULL); 247 | pthread_create(&keyboard, NULL, update_keyboard_color, NULL); 248 | 249 | pthread_join(screenshot, NULL); 250 | pthread_join(keyboard, NULL); 251 | 252 | // Perform closing actions 253 | libmk_disable_control(NULL); 254 | libmk_exit(); 255 | return 0; 256 | } 257 | -------------------------------------------------------------------------------- /libmk/libmkc.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: RedFantom 3 | * License: GNU GPLv3 4 | * Copyright (c) 2018 RedFantom 5 | */ 6 | #include "libmk.h" 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | 13 | /// @brief Controller States 14 | typedef enum LibMK_Controller_State { 15 | LIBMK_STATE_ACTIVE = 0, ///< Controller is active 16 | LIBMK_STATE_STOPPED = 1, ///< Controller was active, but is now stopped 17 | LIBMK_STATE_PRESTART = 2, ///< Controller has not yet been active 18 | LIBMK_STATE_ERROR = 3, ///< Controller was stopped by an error 19 | LIBMK_STATE_JOIN_ERR = 4, ///< Failed to join the controller 20 | LIBMK_STATE_START_ERR = 5, ///< Failed to start the controller 21 | } LibMK_Controller_State; 22 | 23 | /// @brief Instruction types 24 | typedef enum LibMK_Instruction_Type { 25 | LIBMK_INSTR_FULL = 0, ///< Full keyboard color instruction 26 | LIBMK_INSTR_ALL = 1, ///< All LEDs individually instruction 27 | LIBMK_INSTR_SINGLE = 2, ///< Instruction for a single key 28 | } LibMK_Instruction_Type; 29 | 30 | /** @brief Single instruction that can be executed by a controller 31 | * 32 | * An instruction should not be executed multiple times. An instruction 33 | * is bound to a specific controller as its id attribute is bound to the 34 | * linked list of instructions of a controller. 35 | */ 36 | typedef struct LibMK_Instruction { 37 | unsigned char r, c; ///< LIBMK_INSTR_SINGLE, row and column coords 38 | unsigned char* colors; ///< LIBMK_INSTR_ALL, key color matrix 39 | unsigned char color[3]; ///< LIBMK_INSTR_SINGLE, LIBMK_INSTR_FULL 40 | unsigned int duration; ///< Delay after execution of instruction 41 | unsigned int id; ///< ID number set by the scheduler 42 | struct LibMK_Instruction* next; ///< Linked list attribute 43 | LibMK_Instruction_Type type; ///< For the instruction execution 44 | } LibMK_Instruction; 45 | 46 | /** @brief Controller for a keyboard managing a single handle 47 | * 48 | * Access to the various attributes of the Controller is 49 | * protected by mutexes and the attributes of the controller should 50 | * therefore not be accessed directly. 51 | */ 52 | typedef struct LibMK_Controller { 53 | LibMK_Handle* handle; ///< Handle of the keyboard to control 54 | LibMK_Instruction* instr; ///< Linked list of instructions 55 | pthread_mutex_t instr_lock; ///< Protects LibMK_Instruction* instr 56 | pthread_t thread; ///< Thread for libmk_run_controller 57 | pthread_mutex_t exit_flag_lock; ///< Protects bool exit_flag and wait_flag 58 | bool exit_flag; ///< Exit event: Thread exits immediately 59 | bool wait_flag; ///< Wait event: Thread exits when all instructions are done 60 | pthread_mutex_t state_lock; ///< Protects LibMK_Controller_State state 61 | LibMK_Controller_State state; ///< Stores current state of controller 62 | pthread_mutex_t error_lock; ///< Protects LibMK_Result error 63 | LibMK_Result error; ///< Set for LIBMK_STATE_ERROR 64 | } LibMK_Controller; 65 | 66 | /** @brief Create a new LibMK_Controller for a defined handle 67 | * 68 | * After initialization of the Controller, the Handle may no longer be 69 | * used directly. The lifecycle of the created controller is the 70 | * responsibility of the user. 71 | */ 72 | LibMK_Controller* libmk_create_controller(LibMK_Handle* handle); 73 | 74 | /** @brief Free a LibMK_Controller 75 | * 76 | * First performs a check to see if the controller is still active. An 77 | * active controller may not be freed. Returns LIBMK_ERR_STILL_ACTIVE 78 | * if the controller is still active. 79 | */ 80 | LibMK_Result libmk_free_controller(LibMK_Controller* c); 81 | 82 | /** @brief Schedule a linked-list of instructions 83 | * 84 | * Instruction scheduler than schedules the given linked-list of 85 | * instructions at the end of the list of the controller in the given 86 | * order. After scheduling, all instructions are given an ID number 87 | * and they may not be scheduled again. After execution, the 88 | * instructions are freed and thus after scheduling an instruction may 89 | * not be accessed again. 90 | * 91 | * Returns the instruction ID of the first instruction in the linked 92 | * list (it is the user's responsibility to derive the ID number of the 93 | * other instructions) upon success (postive integer) or a LibMK_Result 94 | * (negative integer) upon failure. 95 | */ 96 | int libmk_sched_instruction( 97 | LibMK_Controller* controller, LibMK_Instruction* instruction); 98 | 99 | /** @brief Cancel a scheduled instruction by its ID number 100 | * 101 | * If the instruction has already been executed, the instruction is not 102 | * cancelled and the function fails quietly. Does not cancel any 103 | * successive instructions even if the instruction was scheduled as 104 | * part of a linked-list. 105 | */ 106 | LibMK_Result libmk_cancel_instruction(LibMK_Controller* c, unsigned int id); 107 | 108 | /** @brief Start a new Controller thread 109 | * 110 | * Start the execution of instructions upon the keyboard in a different 111 | * thread. This function enables control of the keyboard and initializes 112 | * the thread. 113 | */ 114 | LibMK_Result libmk_start_controller(LibMK_Controller* controller); 115 | 116 | /** @brief Internal Function. Execute Controller instructions. */ 117 | void libmk_run_controller(LibMK_Controller* controller); 118 | 119 | /** @brief Request an exit on a running controller 120 | * 121 | * The request is passed using the exit_flag, and thus the Controller 122 | * may not immediately be stopped. To assure that the controller has 123 | * stopped, use libmk_join_controller. 124 | */ 125 | void libmk_stop_controller(LibMK_Controller* controller); 126 | 127 | /** @brief Indicate the controller to finish only pending instructions 128 | * 129 | * If instructions are scheduled in the mean-time, they are added to the 130 | * linked list and still executed by the Controller before exiting. Only 131 | * after the linked list has become empty does the Controller exit. 132 | * 133 | * This function sets the wait_flag, and thus the Controller has not 134 | * necessarily stopped after this function ends. To assure that the 135 | * Controller has stopped, use libmk_join_controller. 136 | */ 137 | void libmk_wait_controller(LibMK_Controller* controller); 138 | 139 | /** @brief Join the Controller thread 140 | * 141 | * @param t: Timeout in seconds 142 | * @returns LIBMK_STATE_JOIN_ERR upon timeout, controller state after 143 | * exiting upon success. 144 | */ 145 | LibMK_Controller_State libmk_join_controller(LibMK_Controller* c, double t); 146 | 147 | /** @brief Internal Function. */ 148 | void libmk_set_controller_error(LibMK_Controller* c, LibMK_Result r); 149 | 150 | /** @brief Allocate a new LibMK_Instruction struct */ 151 | LibMK_Instruction* libmk_create_instruction(); 152 | 153 | /** @brief Create a new instruction to set the full keyboard color 154 | * 155 | * @param c: RGB color triplet that is copied to the instruction. 156 | * @returns Pointer to single LibMK_Instruction. Duration may be set 157 | * by the caller. 158 | */ 159 | LibMK_Instruction* libmk_create_instruction_full(unsigned char c[3]); 160 | 161 | /** @brief Create a new instruction to set all leds individually 162 | * 163 | * @param c: RGB color matrix that is copied to the instruction. 164 | * @returns Pointer to single LibMK_Instruction. Duration may be set 165 | * by the caller. 166 | */ 167 | LibMK_Instruction* libmk_create_instruction_all( 168 | unsigned char c[LIBMK_MAX_ROWS][LIBMK_MAX_COLS][3]); 169 | 170 | /** @brief Create a new list of instructions to flash the keyboard 171 | * 172 | * Makes use of LIBMK_INSTR_FULL type instructions. Builds a linked list 173 | * of n instructions. 174 | * 175 | * @param c: RGB color triplet that is copied to the instruction. 176 | * @param delay: Duration set for each individual instruction of the 177 | * linked list in microseconds, excluding the time required for 178 | * instruction execution itself. 179 | * @param n: Number of instructions in the linked list to be built. 180 | * 181 | * @returns Pointer to linked list of LibMK_Instruction. 182 | */ 183 | LibMK_Instruction* libmk_create_instruction_flash( 184 | unsigned char c[3], unsigned int delay, unsigned char n); 185 | 186 | 187 | /** @brief Create a new instruction to set the color of a single key 188 | * 189 | * Overridden by a LIBMK_INSTR_FULL, just as in synchronous keyboard 190 | * control. When changing six or more keys, using a LIBMK_INSTR_ALL is 191 | * faster. 192 | * 193 | * @param row: Row coordinate of the key 194 | * @param column: Column coordinate of the key 195 | * @param c: RGB triplet to be copied to the instruction 196 | * 197 | * @returns Single LibMK_Instruction, duration may be set by the user. 198 | */ 199 | LibMK_Instruction* libmk_create_instruction_single( 200 | unsigned char row, unsigned char column, unsigned char c[3]); 201 | 202 | /** @brief Free a single LibMK_Instruction 203 | * 204 | * The instruction is expected to longer be part of a linked list. This 205 | * instruction is automatically called after an instruction has been 206 | * executed and should only be called by the user if an instruction must 207 | * be freed before it is scheduled. Use libmk_cancel_instruction to 208 | * cancel scheduled instructions, which are then freed after cancelling. 209 | */ 210 | void libmk_free_instruction(LibMK_Instruction* i); 211 | 212 | /** @brief Internal Function. Execute a single instruction. NOT THREAD-SAFE. */ 213 | LibMK_Result libmk_exec_instruction(LibMK_Handle* h, LibMK_Instruction* i); 214 | -------------------------------------------------------------------------------- /masterkeys/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: RedFantom 3 | License: GNU GPLv3 4 | Copyright (c) 2018-2019 RedFantom 5 | """ 6 | try: 7 | from . import masterkeys as _mk 8 | except ImportError: 9 | import warnings 10 | warnings.warn("Failed to import masterkeys C library", ImportWarning) 11 | try: 12 | from typing import Dict, List, Tuple 13 | except ImportError: # PyCharm typing 14 | pass 15 | 16 | 17 | MAX_ROWS = 7 18 | MAX_COLS = 24 19 | 20 | 21 | class ResultCode: 22 | # Success codes 23 | SUCCESS = 0 24 | 25 | # Device Errors 26 | ERR_INVALID_DEV = -1 27 | ERR_DEV_NOT_CONNECTED = -2 28 | ERR_DEV_NOT_SET = -3 29 | ERR_UNKNOWN_LAYOUT = -14 30 | ERR_DEV_NOT_CLOSED = -15 31 | ERR_DEV_RESET_FAILED = -16 32 | 33 | # Interface Errors 34 | ERR_IFACE_CLAIM_FAILED = -4 35 | ERR_IFACE_RELEASE_FAILED = -5 36 | ERR_DEV_CLOSE_FAILED = -6 37 | ERR_DEV_OPEN_FAILED = -7 38 | 39 | # Kernel Driver Errors 40 | ERR_KERNEL_DRIVER = -8 41 | 42 | # Communication Errors 43 | ERR_DEV_LIST = -9 44 | ERR_TRANSFER = -10 45 | ERR_DESCR = -11 46 | 47 | # Protocol Errors 48 | ERR_PROTOCOL = -13 49 | 50 | 51 | class Effect: 52 | EFF_FULL_ON = 0 53 | EFF_BREATH = 1 54 | EFF_BREATH_CYCLE = 2 55 | EFF_SINGLE = 3 56 | EFF_WAVE = 4 57 | EFF_RIPPLE = 5 58 | EFF_CROSS = 6 59 | EFF_RAIN = 7 60 | EFF_STAR = 8 61 | EFF_SNAKE = 9 62 | EFF_REC = 10 63 | EFF_SPECTRUM = 11 64 | EFF_RAPID_FIRE = 12 65 | 66 | 67 | class Model: 68 | MODEL_RGB_L = 0 69 | MODEL_RGB_M = 5 70 | MODEL_RGB_S = 1 71 | 72 | MODEL_WHITE_L = 2 73 | MODEL_WHITE_M = 3 74 | MODEL_WHITE_S = 7 75 | 76 | MODEL_NOT_SET = -1 77 | MODEL_ANY = -2 78 | MODEL_UNKNOWN = -3 79 | 80 | 81 | class ControlMode: 82 | FIRMWARE_CTRL = 0x00 83 | EFFECT_CTRL = 0x01 84 | CUSTOM_CTRL = 0x02 85 | PROFILE_CTRL = 0x03 86 | 87 | 88 | MODEL_STRINGS = { 89 | 0: "MasterKeys Pro L RGB", 90 | 5: "MasterKeys Pro M RGB", 91 | 1: "MasterKeys Pro S RGB", 92 | 2: "MasterKeys Pro L White", 93 | 3: "MasterKeys Pro M White", 94 | 7: "MasterKeys Pro S White", 95 | -1: "Model not set", 96 | -2: "Any supported model", 97 | -3: "Unknown model" 98 | } 99 | 100 | 101 | def detect_devices(): 102 | # type: () -> Tuple[int, ...] 103 | """ 104 | Detect supported connected devices and return a tuple of models 105 | 106 | :return: Tuple of integers (:class:`.Model`) 107 | :rtype: Tuple[int, ...] 108 | :raises: ``RuntimeError`` upon internal Python error 109 | """ 110 | return _mk.detect_devices() 111 | 112 | 113 | def set_device(model): 114 | # type: (int) -> int 115 | """ 116 | Set the device to be controlled by the library to the specified model 117 | 118 | :param model: Model to be controlled by the library. Only one device 119 | is supported in the Python library. Only the first found device 120 | of the specified model is controlled. 121 | :type model: int 122 | :return: Result code (:class:`.ResultCode`) 123 | :rtype: int 124 | :raises: ``TypeError`` upon invalid argument type 125 | """ 126 | return _mk.set_device(model) 127 | 128 | 129 | def enable_control(): 130 | # type: () -> int 131 | """ 132 | Enable control on the device that has been set 133 | 134 | :return: Result code (:class:`.ResultCode`) 135 | :rtype: int 136 | """ 137 | return _mk.enable_control() 138 | 139 | 140 | def disable_control(): 141 | # type: () -> int 142 | """ 143 | Disable control on the device that has been set and is controlled 144 | 145 | :return: Result code (:class:`.ResultCode`) 146 | :rtype: int 147 | """ 148 | return _mk.disable_control() 149 | 150 | 151 | def set_effect(effect): 152 | # type: (int) -> int 153 | """ 154 | Set the effect to be active on the controlled keyboard 155 | 156 | :param effect: Effect number to set to be active (:class:`.Effect`) 157 | :type effect: int 158 | :return: Result code (:class:`.ResultCode`) 159 | :rtype: int 160 | :raises: ``TypeError`` upon invalid argument type 161 | """ 162 | return _mk.set_effect(effect) 163 | 164 | 165 | def set_all_led_color(layout): 166 | # type: (List[List[Tuple[int, int, int], ...], ...]) -> int 167 | """ 168 | Set the color of all LEDs on the keyboard individually 169 | 170 | :param layout: List of lists of color tuples such as created by 171 | build_layout_list() 172 | :type layout: List[List[Tuple[int, int, int], ...], ...] 173 | :return: Result code (:class:`.ResultCode`) 174 | :rtype: int 175 | :raises: ``ValueError`` if the wrong amount of elements is in the 176 | list 177 | :raises: ``TypeError`` if invalid argument type (any element) 178 | """ 179 | return _mk.set_all_led_color(layout) 180 | 181 | 182 | def set_full_led_color(r, g, b): 183 | # type: (int, int, int) -> int 184 | """ 185 | Set the color of all the LEDs on the keyboard to a single color 186 | 187 | :param r: red color byte 188 | :type r: int 189 | :param g: green color byte 190 | :type g: int 191 | :param b: blue color byte 192 | :type b: int 193 | :return: Result code (:class:`.ResultCode`) 194 | :rtype: int 195 | """ 196 | return _mk.set_full_led_color(r, g, b) 197 | 198 | 199 | def set_ind_led_color(row, col, r, g, b): 200 | # type: (int, int, int, int, int) -> int 201 | """ 202 | Set the color of a single, individual key on the keyboard 203 | 204 | :param row: zero-indexed row index < MAX_ROWS 205 | :type row: int 206 | :param col: zero-indexed column index < MAX_COLS 207 | :type col: int 208 | :param r: red color byte 209 | :type r: int 210 | :param g: green color byte 211 | :type g: int 212 | :param b: blue color byte 213 | :type b: int 214 | :return: Result code (:class:`.ResultCode`) 215 | :rtype: int 216 | :raises: ``TypeError`` upon invalid argument type 217 | """ 218 | return _mk.set_ind_led_color(row, col, r, g, b) 219 | 220 | 221 | def get_device_ident(): 222 | # type: () -> int 223 | """ 224 | Return the bDevice USB descriptor value for the controlled keyboard 225 | 226 | :return: bDevice USB descriptor value or result code (<0) 227 | :rtype: int 228 | """ 229 | return _mk.get_device_ident() 230 | 231 | 232 | def set_all_led_color_dict(keys): 233 | # type: (Dict[Tuple[int, int], Tuple[int, int, int]]) -> int 234 | """ 235 | Set the color of all LEDs on the controlled device with a dictionary 236 | 237 | The keys should be specified in a dictionary of the format 238 | {(row, col): (r, g, b)} 239 | 240 | :param keys: Dictionary containing key color data 241 | :type keys: Dict[Tuple[int, int], Tuple[int, int, int]] 242 | :return: Result code (:class:`.ResultCode`) 243 | :rtype: int 244 | """ 245 | layout = build_layout_list() 246 | for (row, col), (r, g, b) in keys.items(): 247 | layout[row][col] = (r, g, b) 248 | return _mk.set_all_led_color(layout) 249 | 250 | 251 | def build_layout_list(): 252 | # type: () -> List[List[Tuple[int, int, int], ...], ...] 253 | """ 254 | Return a list of the right proportions for full LED layout 255 | 256 | :return: Empty layout list 257 | :rtype: List[List[Tuple[int, int, int], ...], ...] 258 | """ 259 | layout = list() 260 | for i in range(MAX_ROWS): 261 | column = list() 262 | for j in range(MAX_COLS): 263 | column.append((0x00, 0x00, 0x00)) 264 | layout.append(column) 265 | return layout 266 | 267 | 268 | def set_effect_details(effect, direction=0, speed=0x60, amount=0x00, 269 | foreground=(0xFF, 0xFF, 0xFF), 270 | background=(0x00, 0x00, 0x00)): 271 | # type: (int, int, int, int, Tuple[int, int, int], Tuple[int, int, int]) -> int 272 | """ 273 | Set an effect with custom parameters 274 | 275 | For more details about the parameters, please see the libmk 276 | documentation. 277 | 278 | :param effect: Effect number (:class:`.Effect`) 279 | :type effect: int 280 | :param direction: Direction of the animation of the effect 281 | :type direction: int 282 | :param speed: Speed of the animation of the effect 283 | :type speed: int 284 | :param amount: Amount/intensity of the effect 285 | :type amount: int 286 | :param foreground: Foreground color of the effect 287 | :type foreground: Tuple[int, int, int] 288 | :param background: Background color of the effect 289 | :type background: Tuple[int, int, int] 290 | :return: Result code (:class:`.ResultCode`) 291 | :rtype: int 292 | """ 293 | return _mk.set_effect_details( 294 | effect, direction, speed, amount, foreground, background) 295 | 296 | 297 | def get_active_profile(): 298 | # type: () -> int 299 | """ 300 | Return the number of the profile active on the keyboard 301 | 302 | :return: Result code (:class:`.ResultCode`) or profile number 303 | :rtype: int 304 | """ 305 | return _mk.get_active_profile() 306 | 307 | 308 | def set_active_profile(profile): 309 | # type: (int) -> int 310 | """ 311 | Activate a profile on the keyboard 312 | 313 | :param profile: Number of profile to activate 314 | :type profile: int 315 | :return: Result code (:class:`.ResultCode`) 316 | :rtype: int 317 | """ 318 | return _mk.set_active_profile(profile) 319 | 320 | 321 | def save_profile(): 322 | # type: () -> int 323 | """ 324 | Save the changes made to the lighting to the active profile 325 | 326 | :return: Result code (:class:`.ResultCode`) 327 | :rtype: int 328 | """ 329 | return _mk.save_profile() 330 | 331 | 332 | def set_control_mode(mode): 333 | # type: (int) -> int 334 | """ 335 | Change the control mode of the keyboard manually 336 | 337 | :param mode: New control mode to set (:class:`.ControlMode`) 338 | :type mode: int 339 | :return: Result code (:class:`.ResultCode`) 340 | :rtype: int 341 | """ 342 | return _mk.set_control_mode(mode) 343 | 344 | -------------------------------------------------------------------------------- /libmk/libmkc.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: RedFantom 3 | * License: GNU GPLv3 4 | * Copyright (c) 2018 RedFantom 5 | */ 6 | #include "libmkc.h" 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #define LIBMKC_DEBUG 13 | 14 | 15 | LibMK_Controller* libmk_create_controller(LibMK_Handle* handle) { 16 | LibMK_Controller* controller = (LibMK_Controller*) malloc( 17 | sizeof(LibMK_Controller)); 18 | if (controller == NULL) 19 | return NULL; 20 | controller->handle = handle; 21 | pthread_mutex_init(&controller->state_lock, NULL); 22 | pthread_mutex_init(&controller->exit_flag_lock, NULL); 23 | pthread_mutex_init(&controller->instr_lock, NULL); 24 | pthread_mutex_init(&controller->error_lock, NULL); 25 | controller->instr = NULL; 26 | controller->state = LIBMK_STATE_PRESTART; 27 | controller->exit_flag = false; 28 | controller->wait_flag = false; 29 | return controller; 30 | } 31 | 32 | 33 | LibMK_Controller_State libmk_get_controller_state(LibMK_Controller* c) { 34 | pthread_mutex_lock(&(c->state_lock)); 35 | LibMK_Controller_State b = c->state; 36 | pthread_mutex_unlock(&c->state_lock); 37 | return b; 38 | } 39 | 40 | 41 | LibMK_Result libmk_get_controller_error(LibMK_Controller* c) { 42 | pthread_mutex_lock(&(c->error_lock)); 43 | LibMK_Result r = c->error; 44 | pthread_mutex_unlock(&(c->error_lock)); 45 | return r; 46 | } 47 | 48 | 49 | LibMK_Result libmk_free_controller(LibMK_Controller* c) { 50 | if (libmk_get_controller_state(c) == LIBMK_STATE_ACTIVE) 51 | return LIBMK_ERR_STILL_ACTIVE; 52 | pthread_mutex_destroy(&c->state_lock); 53 | pthread_mutex_destroy(&c->exit_flag_lock); 54 | pthread_mutex_destroy(&c->instr_lock); 55 | pthread_mutex_destroy(&c->error_lock); 56 | int r = libmk_free_handle(c->handle); 57 | if (r != LIBMK_SUCCESS) 58 | return (LibMK_Result) r; 59 | free(c); 60 | return LIBMK_SUCCESS; 61 | 62 | } 63 | 64 | 65 | LibMK_Result libmk_start_controller(LibMK_Controller* controller) { 66 | LibMK_Result r = (LibMK_Result) libmk_enable_control(controller->handle); 67 | if (r != LIBMK_SUCCESS) 68 | return r; 69 | pthread_create( 70 | &controller->thread, NULL, 71 | (void*) libmk_run_controller, (void*) controller); 72 | return LIBMK_SUCCESS; 73 | } 74 | 75 | 76 | void libmk_run_controller(LibMK_Controller* controller) { 77 | pthread_mutex_lock(&(controller->state_lock)); 78 | controller->state = LIBMK_STATE_ACTIVE; 79 | pthread_mutex_unlock(&(controller->state_lock)); 80 | bool exit_flag, wait_flag; 81 | while (true) { 82 | pthread_mutex_lock(&(controller->exit_flag_lock)); 83 | exit_flag = controller->exit_flag; 84 | wait_flag = controller->wait_flag; 85 | pthread_mutex_unlock(&(controller->exit_flag_lock)); 86 | if (exit_flag) 87 | break; 88 | pthread_mutex_lock(&(controller->instr_lock)); 89 | if (controller->instr == NULL) { 90 | pthread_mutex_unlock(&(controller->instr_lock)); 91 | if (wait_flag) 92 | break; 93 | usleep(1000); 94 | continue; 95 | } 96 | LibMK_Result r = (LibMK_Result) libmk_exec_instruction( 97 | controller->handle, controller->instr); 98 | if (r != LIBMK_SUCCESS) { 99 | libmk_set_controller_error(controller, r); 100 | pthread_mutex_unlock(&(controller->instr_lock)); 101 | break; 102 | } 103 | usleep(controller->instr->duration); 104 | // Move on to next instruction 105 | LibMK_Instruction* old = controller->instr; 106 | controller->instr = controller->instr->next; 107 | libmk_free_instruction(old); 108 | pthread_mutex_unlock(&(controller->instr_lock)); 109 | } 110 | int r = libmk_disable_control(controller->handle); 111 | if (r != LIBMK_SUCCESS) { 112 | libmk_set_controller_error(controller, (LibMK_Result) r); 113 | } 114 | pthread_mutex_lock(&(controller->state_lock)); 115 | controller->state = LIBMK_STATE_STOPPED; 116 | pthread_mutex_unlock(&(controller->state_lock)); 117 | } 118 | 119 | 120 | void libmk_set_controller_error(LibMK_Controller* c, LibMK_Result e) { 121 | pthread_mutex_lock(&(c->error_lock)); 122 | if (c->error == LIBMK_SUCCESS) 123 | c->error = e; 124 | pthread_mutex_unlock(&(c->error_lock)); 125 | } 126 | 127 | 128 | LibMK_Result libmk_exec_instruction(LibMK_Handle* h, LibMK_Instruction* i) { 129 | if (i == NULL) 130 | return libmk_send_control_packet(h); 131 | else if (i->type == LIBMK_INSTR_ALL) { 132 | return libmk_set_all_led_color(h, i->colors); 133 | } else if (i->type == LIBMK_INSTR_FULL) { 134 | return libmk_set_full_color(h, i->color[0], i->color[1], i->color[2]); 135 | } else if (i->type == LIBMK_INSTR_SINGLE) { 136 | return libmk_set_single_led( 137 | h, i->r, i->c, i->color[0], i->color[1], i->color[2]); 138 | } 139 | } 140 | 141 | 142 | void libmk_stop_controller(LibMK_Controller* controller) { 143 | pthread_mutex_lock(&(controller->exit_flag_lock)); 144 | controller->exit_flag = true; 145 | pthread_mutex_unlock(&(controller->exit_flag_lock)); 146 | } 147 | 148 | 149 | void libmk_wait_controller(LibMK_Controller* controller) { 150 | pthread_mutex_lock(&(controller->exit_flag_lock)); 151 | controller->wait_flag = true; 152 | pthread_mutex_unlock(&(controller->exit_flag_lock)); 153 | } 154 | 155 | 156 | LibMK_Controller_State libmk_join_controller( 157 | LibMK_Controller* controller, double timeout) { 158 | LibMK_Controller_State s; 159 | clock_t t = clock(); 160 | double elapsed; 161 | while (true) { 162 | pthread_mutex_lock(&(controller->state_lock)); 163 | s = controller->state; 164 | pthread_mutex_unlock(&(controller->state_lock)); 165 | if (s != LIBMK_STATE_ACTIVE) 166 | break; 167 | elapsed = ((double) (clock() - t)) / CLOCKS_PER_SEC; 168 | if (elapsed > timeout) 169 | return LIBMK_STATE_JOIN_ERR; 170 | } 171 | return s; 172 | } 173 | 174 | 175 | void libmk_free_instruction(LibMK_Instruction* i) { 176 | fflush(stdout); 177 | if (i->colors != NULL) 178 | free(i->colors); 179 | free(i); 180 | } 181 | 182 | 183 | LibMK_Instruction* libmk_create_instruction() { 184 | LibMK_Instruction* i = 185 | (LibMK_Instruction*) malloc(sizeof(LibMK_Instruction)); 186 | i->duration = 0; 187 | i->id = -1; 188 | i->type = -1; 189 | i->next = NULL; 190 | i->colors = NULL; 191 | return i; 192 | } 193 | 194 | 195 | LibMK_Instruction* libmk_create_instruction_single( 196 | unsigned char row, unsigned char column, unsigned char color[3]) { 197 | LibMK_Instruction* i = libmk_create_instruction(); 198 | i->type = LIBMK_INSTR_SINGLE; 199 | for (unsigned char j=0; j<3; j++) 200 | i->color[j] = color[j]; 201 | i->r = row; 202 | i->c = column; 203 | return i; 204 | } 205 | 206 | 207 | LibMK_Instruction* libmk_create_instruction_full(unsigned char c[3]) { 208 | LibMK_Instruction* i = libmk_create_instruction(); 209 | for (unsigned char j=0; j<3; j++) 210 | i->color[j] = c[j]; 211 | i->type = LIBMK_INSTR_FULL; 212 | return i; 213 | } 214 | 215 | 216 | LibMK_Instruction* libmk_create_instruction_all( 217 | unsigned char c[LIBMK_MAX_ROWS][LIBMK_MAX_COLS][3]) { 218 | LibMK_Instruction* i = libmk_create_instruction(); 219 | i->colors = (unsigned char*) malloc( 220 | sizeof(unsigned char) * LIBMK_MAX_ROWS * LIBMK_MAX_COLS * 3); 221 | memcpy(i->colors, c, LIBMK_MAX_ROWS * LIBMK_MAX_COLS * 3); 222 | i->type = LIBMK_INSTR_ALL; 223 | return i; 224 | } 225 | 226 | 227 | LibMK_Instruction* libmk_create_instruction_flash( 228 | unsigned char c[3], unsigned int delay, unsigned char n) { 229 | unsigned char color[3] = {0}; 230 | LibMK_Instruction* i = libmk_create_instruction_full(color); 231 | LibMK_Instruction* k = i; 232 | LibMK_Instruction* l; 233 | for (unsigned char j=0; jduration = delay; 239 | k->next = l; 240 | k = l; 241 | } 242 | for (unsigned char j=n; j>0; j--) { 243 | color[0] = ((double) j / (double) n) * c[0]; 244 | color[1] = ((double) j / (double) n) * c[1]; 245 | color[2] = ((double) j / (double) n) * c[2]; 246 | l = libmk_create_instruction_full(color); 247 | l->duration = delay; 248 | k->next = l; 249 | k = l; 250 | } 251 | return i; 252 | } 253 | 254 | 255 | int libmk_sched_instruction( 256 | LibMK_Controller* c, LibMK_Instruction* i) { 257 | pthread_mutex_lock(&(c->instr_lock)); 258 | if (i->id != -1) 259 | return LIBMK_ERR_INVALID_ARG; // Instruction already scheduled! 260 | if (c->instr == NULL) { 261 | c->instr = i; 262 | c->instr->id = 1; 263 | } else { 264 | LibMK_Instruction* t = c->instr; 265 | while (t != NULL) { 266 | if (t->next == NULL) { 267 | t->next = i; 268 | t->next->id = t->id + 1; 269 | break; 270 | } 271 | t = t->next; 272 | } 273 | } 274 | if (i->next != NULL) { 275 | LibMK_Instruction *k = i->next; 276 | unsigned int id = i->id; 277 | while (k != NULL) { 278 | id += 1; 279 | k->id = id; 280 | k = k->next; 281 | } 282 | } 283 | int first_id = i->id; 284 | pthread_mutex_unlock(&(c->instr_lock)); 285 | return first_id; 286 | } 287 | 288 | 289 | LibMK_Result libmk_cancel_instruction(LibMK_Controller* c, unsigned int id) { 290 | pthread_mutex_lock(&(c->instr_lock)); 291 | LibMK_Instruction* prev = NULL; 292 | LibMK_Instruction* curr = c->instr; 293 | while (curr != NULL) { 294 | if (curr->id == id) { 295 | // Cancel this instruction 296 | if (prev != NULL) 297 | prev->next = curr->next; 298 | else // First instruction in Linked List 299 | c->instr = curr->next; 300 | libmk_free_instruction(curr); 301 | break; 302 | } 303 | prev = curr; 304 | curr = curr->next; 305 | } 306 | pthread_mutex_unlock(&(c->instr_lock)); 307 | return LIBMK_SUCCESS; 308 | } 309 | -------------------------------------------------------------------------------- /examples/notifications/mk_notifications.c: -------------------------------------------------------------------------------- 1 | /** Author: RedFantom 2 | * License: GNU GPLv3 3 | * Copyright (c) 2018-2019 RedFantom 4 | */ 5 | #include "capture.h" 6 | #include "libmk.h" 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #if PY_MAJOR_VERSION >= 3 15 | #define PyInt_FromLong PyLong_FromLong 16 | #define PyInt_Check PyLong_Check 17 | #define PyInt_AsLong PyLong_AsLong 18 | #endif 19 | 20 | /// Global variables 21 | bool exit_requested = false; 22 | unsigned char target_color[3] = {0}; 23 | bool target_override = false; 24 | double speed = 20.0; 25 | int flash_repeat = 2; 26 | double flash_time = 1.0; 27 | 28 | /// Mutexes 29 | pthread_mutex_t exit_lock = PTHREAD_MUTEX_INITIALIZER; 30 | pthread_mutex_t target_lock = PTHREAD_MUTEX_INITIALIZER; 31 | pthread_mutex_t keyboard_lock = PTHREAD_MUTEX_INITIALIZER; 32 | 33 | /// Threads 34 | pthread_t keyboard_thread; 35 | pthread_t capture_thread; 36 | 37 | /// Screen capture 38 | CaptureArgs* capture_args; 39 | 40 | 41 | void mkn_exit() { 42 | pthread_mutex_lock(&exit_lock); 43 | exit_requested = true; 44 | pthread_mutex_unlock(&exit_lock); 45 | pthread_join(keyboard_thread, NULL); 46 | pthread_join(capture_thread, NULL); 47 | libmk_disable_control(NULL); 48 | libmk_exit(); 49 | } 50 | 51 | 52 | void keyboard_updater() { 53 | /** Thread controlling the color of a keyboard 54 | * 55 | * The thread sets the color of the keyboard to a color set by a 56 | * different thread in target_color. target_color is protected by 57 | * target_lock. 58 | * 59 | * Expects that the keyboard to controlled is in the global device 60 | * handle and control is enabled. 61 | */ 62 | unsigned char target[3], previous[3]; 63 | bool exit = false, override = false; 64 | 65 | while (true) { 66 | pthread_mutex_lock(&exit_lock); 67 | exit = exit_requested; 68 | pthread_mutex_unlock(&exit_lock); 69 | if (exit) 70 | break; 71 | 72 | pthread_mutex_lock(&target_lock); 73 | for (int i=0; i<3; i++) 74 | target[i] = target_color[i]; 75 | override = target_override; 76 | pthread_mutex_unlock(&target_lock); 77 | 78 | bool equal = ( 79 | target[0] == previous[0] && 80 | target[1] == previous[1] && 81 | target[2] == previous[2]); 82 | if (equal) { // If equal, sleep to prevent overactiveness 83 | continue; 84 | } 85 | 86 | if (!target_override) 87 | for (int i=0; i<3; i++) { 88 | int diff = (int) target[i] - (int) previous[i]; 89 | target[i] = previous[i] + (unsigned char) (diff / speed); 90 | previous[i] = target[i]; 91 | } 92 | int r = libmk_set_full_color(NULL, target[0], target[1], target[2]); 93 | int* return_code = (int*) malloc(sizeof(int)); 94 | *(return_code) = r; 95 | if (r != LIBMK_SUCCESS) 96 | pthread_exit((void*) return_code); 97 | 98 | usleep(10000); 99 | } 100 | pthread_exit(LIBMK_SUCCESS); 101 | } 102 | 103 | 104 | static PyObject* init(PyObject* self, PyObject* args) { 105 | /** Initialize the library and setup for capture */ 106 | if (!libmk_init()) { 107 | PyErr_SetString(PyExc_RuntimeError, "Failed to init libmk"); 108 | return NULL; 109 | } 110 | 111 | int divider, lower, upper, sat_bias; 112 | int brightness_norm; 113 | if (!PyArg_ParseTuple(args, "iiiiidid", ÷r, &lower, &upper, &sat_bias, 114 | &brightness_norm, &speed, &flash_repeat, &flash_time)) { 115 | PyErr_SetString(PyExc_ValueError, "Failed to parse arguments"); 116 | libmk_exit(); 117 | return NULL; 118 | } 119 | 120 | capture_args = init_capture(divider, sat_bias, lower, upper, 121 | brightness_norm != 0, &target_color, &target_lock, &exit_requested, 122 | &exit_lock, &keyboard_lock); 123 | 124 | if (args == NULL) { 125 | PyErr_SetString(PyExc_RuntimeError, "Failed to build CaptureArgs struct"); 126 | libmk_exit(); 127 | return NULL; 128 | } 129 | 130 | LibMK_Model* models; 131 | int n = libmk_detect_devices(&models); 132 | if (n <= 0) { 133 | libmk_exit(); 134 | return PyInt_FromLong(1); 135 | } 136 | 137 | LibMK_Model model = models[0]; // Take first device found as target 138 | int r = libmk_set_device(model, NULL); // Use global device handle 139 | if (r != LIBMK_SUCCESS) { 140 | libmk_exit(); 141 | return PyInt_FromLong(r); 142 | } 143 | 144 | r = libmk_enable_control(NULL); 145 | if (r != LIBMK_SUCCESS) { 146 | libmk_exit(); 147 | return PyInt_FromLong(r); 148 | } 149 | 150 | Py_AtExit((void*) mkn_exit); 151 | return PyInt_FromLong(LIBMK_SUCCESS); 152 | } 153 | 154 | 155 | static PyObject* start(PyObject* self, PyObject* args) { 156 | /** Start running capture and keyboard threads */ 157 | pthread_create(&capture_thread, NULL, (void*) capturer, (void*) capture_args); 158 | pthread_create(&keyboard_thread, NULL, (void*) keyboard_updater, NULL); 159 | return PyInt_FromLong(0); 160 | } 161 | 162 | 163 | static PyObject* stop(PyObject* self, PyObject* args) { 164 | /** Stop and join capture and keyboard threads */ 165 | pthread_mutex_lock(&exit_lock); 166 | exit_requested = true; 167 | pthread_mutex_unlock(&exit_lock); 168 | int return_kb, return_cp; 169 | pthread_join(keyboard_thread, NULL); 170 | pthread_join(capture_thread, NULL); 171 | 172 | PyObject* tuple = PyTuple_New(2); 173 | int s = PyTuple_SetItem(tuple, 0, PyInt_FromLong(return_kb)); 174 | s += PyTuple_SetItem(tuple, 1, PyInt_FromLong(return_cp)); 175 | if (s != 0) { 176 | PyErr_SetString(PyExc_RuntimeError, "Failed to set tuple item"); 177 | return NULL; 178 | } 179 | return tuple; 180 | } 181 | 182 | 183 | static PyObject* py_calculate_dominant_color(PyObject* self, PyObject* args) { 184 | /** Python interface to fast dominant color calculation function */ 185 | PyObject* list; 186 | int w, h, divider, lower, upper, sat_bias, brightness_norm; 187 | if (!PyArg_ParseTuple(args, "O!iiiiiii", 188 | &PyList_Type, &list, ÷r, &w, &h, &lower, &upper, 189 | &sat_bias, &brightness_norm)) 190 | return NULL; 191 | unsigned char data[w][h][3]; 192 | PyObject* column, *row, *e; 193 | for (int x=0; x-1; i--) { 241 | pthread_mutex_unlock(&target_lock); 242 | for (int j=0; j<3; j++) { 243 | target_color[j] = (unsigned char) ( 244 | (double) color[j] * (double) i / 255.0); 245 | usleep((int) (flash_time / (2*255.0) * 1000000)); 246 | } 247 | pthread_mutex_unlock(&target_lock); 248 | } 249 | pthread_mutex_lock(&target_lock); 250 | target_override = false; 251 | pthread_mutex_unlock(&target_lock); 252 | } 253 | 254 | 255 | void _flash_keyboard(unsigned char* color) { 256 | pthread_mutex_lock(&keyboard_lock); 257 | for (int i=0; i= 3 313 | static struct PyModuleDef mk_notifications_module_def = { 314 | PyModuleDef_HEAD_INIT, 315 | "mk_notifications", 316 | "Library to control MasterKeys keyboard lighting", 317 | -1, 318 | mk_notifications_funcs 319 | }; 320 | PyMODINIT_FUNC PyInit_mk_notifications(void) { 321 | return PyModule_Create(&mk_notifications_module_def); 322 | } 323 | #endif 324 | -------------------------------------------------------------------------------- /masterkeys/masterkeys.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: RedFantom 3 | * License: GNU GPLv3 4 | * Copyright (c) 2018-2019 RedFantom 5 | * 6 | * Python wrapper around libmk 7 | * 8 | * Exposes a Python interface to libmk, allowing the use of lists 9 | * to control MasterKeys RGB keyboards. For python interface 10 | * documentation, please check __init__.py. 11 | */ 12 | #include "../libmk/libmk.h" 13 | #include 14 | #include 15 | 16 | 17 | #if PY_MAJOR_VERSION >= 3 18 | #define PyInt_FromLong PyLong_FromLong 19 | #define PyInt_Check PyLong_Check 20 | #define PyInt_AsLong PyLong_AsLong 21 | #endif 22 | 23 | 24 | static PyObject* masterkeys_init(PyObject* self, PyObject* args) { 25 | /** Initialize the library upon import and register libmk_exit 26 | * 27 | * libmk requires initialization to initialize a libusb session. This 28 | * action is performed on import of the library. Upon (clean) exit 29 | * of the Python interpreter, the libmk_exit function should be 30 | * called to free these resources. This functions is therefore 31 | * registered to be executed at clean interpreter exit. 32 | */ 33 | bool r = libmk_init(); 34 | if (!r) 35 | return NULL; 36 | // Register libmk_exit with cast to void (as Py_AtExit takes only void) 37 | Py_AtExit((void*) libmk_exit); 38 | return PyBool_FromLong((long int) r); 39 | } 40 | 41 | 42 | static PyObject* masterkeys_detect_devices(PyObject* self, PyObject* args) { 43 | /** Return a tuple of connected MasterKeys devices 44 | * 45 | * Python usually runs with simple user permissions, but to access 46 | * (and identify) HID devices and unload kernel drivers, usually 47 | * root privileges are required. 48 | */ 49 | LibMK_Model* models; 50 | int r = libmk_detect_devices(&models); 51 | if (r < 0) 52 | return Py_None; 53 | PyObject * tuple = PyTuple_New(r); 54 | PyObject * elem; 55 | for (short i=0; i < r; i++) { 56 | elem = PyInt_FromLong(models[i]); 57 | int s = PyTuple_SetItem(tuple, i, elem); 58 | if (s != 0) { 59 | // raise RuntimeError("Failed to set tuple item") 60 | PyErr_SetString(PyExc_RuntimeError, "Failed to set tuple item"); 61 | return NULL; 62 | } 63 | } 64 | free(models); // Models list is allocated in libmk_detect_devices 65 | return tuple; 66 | } 67 | 68 | 69 | static PyObject* masterkeys_set_device(PyObject* self, PyObject* args) { 70 | /** Set the device to control with the library 71 | * 72 | * The Python library only supports the control of a single device 73 | * using the global device handle of libmk. 74 | */ 75 | LibMK_Model model; 76 | if (!PyArg_ParseTuple(args, "i", &model)) 77 | return NULL; 78 | int r = libmk_set_device(model, NULL); 79 | return PyInt_FromLong(r); 80 | } 81 | 82 | 83 | static PyObject* masterkeys_enable_control(PyObject* self, PyObject* args) { 84 | /** Enable control of the set control device */ 85 | int r = libmk_enable_control(NULL); // NULL -> global DeviceHandle 86 | return PyInt_FromLong(r); 87 | } 88 | 89 | 90 | static PyObject* masterkeys_disable_control(PyObject* self, PyObject* args) { 91 | /** Disable control of the set control device */ 92 | int r = libmk_disable_control(NULL); // NULL -> global DeviceHandle 93 | return PyInt_FromLong(r); 94 | } 95 | 96 | 97 | static PyObject* masterkeys_set_effect(PyObject* self, PyObject* args) { 98 | /** Set the effect of the keyboard to one of the built-ins */ 99 | LibMK_Effect effect; 100 | if (!PyArg_ParseTuple(args, "i", &effect)) 101 | return NULL; 102 | int r = libmk_set_effect(NULL, effect); 103 | return PyInt_FromLong(r); 104 | } 105 | 106 | 107 | static PyObject* masterkeys_set_full_color(PyObject* self, PyObject* args) { 108 | /** Set the color of all LEDs on the keyboard 109 | * 110 | * Takes three Python integer values as arguments *tuple(r, g, b) 111 | */ 112 | int r, g, b; 113 | if (!PyArg_ParseTuple(args, "iii", &r, &g, &b)) 114 | return NULL; 115 | int result = libmk_set_full_color(NULL, r, g, b); 116 | return PyInt_FromLong(result); 117 | } 118 | 119 | 120 | static PyObject* masterkeys_set_all_led_color(PyObject* self, PyObject* args) { 121 | /** Set the color of all the LEDs on the keyboard individually 122 | * 123 | * Allocates a layout matrix of color values to set the color of all 124 | * the LEDs on the control device. LEDs not supported on a specific 125 | * keyboard are ignored. The argument should be given as a list of 126 | * lists of tuples [row][column][index]. 127 | */ 128 | PyObject* list, *sub, *tuple, *item; 129 | unsigned char value; 130 | // Parse the list of lists of tuples 131 | if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list)) 132 | return NULL; 133 | // Check the size of the list (it must be a full list) 134 | if (PyList_Size(list) != LIBMK_MAX_ROWS) { 135 | // raise ValueError("Invalid number of list elements") 136 | PyErr_SetString(PyExc_ValueError, "Invalid number of list elements"); 137 | return NULL; 138 | } 139 | // Populate layout color buffer 140 | unsigned char layout[LIBMK_MAX_ROWS][LIBMK_MAX_COLS][3]; 141 | for (unsigned char r=0; r < LIBMK_MAX_ROWS; r++) { 142 | // Assert that the item in the list is also a list 143 | sub = PyList_GetItem(list, r); 144 | if (!PyList_Check(sub)) { 145 | // raise TypeError("Invalid sub-type in list") 146 | PyErr_SetString(PyExc_TypeError, "Invalid sub-type in list"); 147 | return NULL; 148 | } else if (PyList_Size(sub) != LIBMK_MAX_COLS) { 149 | // raise ValueError("Invalid number of sub-list elements") 150 | PyErr_SetString( 151 | PyExc_ValueError, "Invalid number of sub-list elements"); 152 | return NULL; 153 | } 154 | for (unsigned char c=0; c < LIBMK_MAX_COLS; c++) { 155 | // Get sub-list item and assert that it is a tuple,3 156 | tuple = PyList_GetItem(sub, c); 157 | if (!PyTuple_Check(tuple)) { 158 | // raise TypeError("Invalid type of sub-list element") 159 | PyErr_SetString( 160 | PyExc_TypeError, "Invalid type of sub-list element"); 161 | return NULL; 162 | } else if (PyTuple_Size(tuple) != 3) { 163 | // raise ValueError("Invalid number of tuple elements") 164 | PyErr_SetString( 165 | PyExc_ValueError, "Invalid number of tuple elements"); 166 | return NULL; 167 | } 168 | for (unsigned char i=0; i < 3; i++) { 169 | // Read a value from the sub-list tuple-element 170 | item = PyTuple_GetItem(tuple, i); 171 | if (!PyInt_Check(item)) { 172 | // raise TypeError("Invalid tuple element type") 173 | PyErr_SetString( 174 | PyExc_TypeError, "Invalid tuple element type"); 175 | return NULL; 176 | } 177 | // Update buffer with specified value 178 | value = (unsigned char) PyInt_AsLong(item); 179 | layout[r][c][i] = value; 180 | } 181 | } 182 | } 183 | // Perform the keyboard LED update 184 | int code = libmk_set_all_led_color(NULL, (unsigned char*) layout); 185 | return PyInt_FromLong(code); 186 | } 187 | 188 | 189 | static PyObject* masterkeys_set_ind_led_color(PyObject* self, PyObject* args) { 190 | /** Set the color of a single LED on the keyboard */ 191 | int row, col, r, g, b; 192 | if (!PyArg_ParseTuple(args, "iiiii", &row, &col, &r, &g, &b)) 193 | return NULL; 194 | int result = libmk_set_single_led(NULL, row, col, r, g, b); 195 | return PyInt_FromLong(result); 196 | } 197 | 198 | 199 | static PyObject* masterkeys_set_effect_details(PyObject* self, PyObject* args) { 200 | /** Set the an effect with additional arguments */ 201 | unsigned char effect, direction, speed, amount; 202 | PyObject* foreground; 203 | PyObject* background; 204 | int r = PyArg_ParseTuple( 205 | args, "iiiiO!O!", 206 | &effect, &direction, &speed, &amount, 207 | &PyTuple_Type, &foreground, &PyTuple_Type, &background); 208 | if (!r) return NULL; 209 | LibMK_Effect_Details* effect_struct = 210 | (LibMK_Effect_Details*) malloc(sizeof(LibMK_Effect_Details)); 211 | effect_struct->effect = (LibMK_Effect) effect; 212 | effect_struct->direction = direction; 213 | effect_struct->speed = speed; 214 | effect_struct->amount = amount; 215 | PyObject* iterim; 216 | for (unsigned char i=0; i < 3; i++) { 217 | iterim = PyTuple_GetItem(foreground, i); 218 | if (iterim == NULL) 219 | return NULL; 220 | effect_struct->foreground[i] = (unsigned char) PyLong_AsLong(iterim); 221 | iterim = PyTuple_GetItem(background, i); 222 | if (iterim == NULL) 223 | return NULL; 224 | effect_struct->background[i] = (unsigned char) PyLong_AsLong(iterim); 225 | } 226 | r = libmk_set_effect_details(NULL, effect_struct); 227 | return PyInt_FromLong(r); 228 | } 229 | 230 | 231 | static PyObject* masterkeys_get_device_ident(PyObject* self, PyObject* args) { 232 | /** Return the bDevice value for the controlled keyboard */ 233 | return PyInt_FromLong(libmk_get_device_ident(NULL)); 234 | } 235 | 236 | 237 | static PyObject* masterkeys_get_active_profile(PyObject* self, PyObject* args) { 238 | /** Return the active profile on the keyboard */ 239 | char profile; 240 | int r = libmk_get_active_profile(NULL, &profile); 241 | if (r != LIBMK_SUCCESS) 242 | return NULL; 243 | return PyInt_FromLong(profile); 244 | } 245 | 246 | 247 | static PyObject* masterkeys_set_active_profile(PyObject* self, PyObject* args) { 248 | /** Set the active profile on the keyboard */ 249 | long profile; 250 | if (!PyArg_ParseTuple(args, "i", &profile)) 251 | return NULL; 252 | int r = libmk_set_active_profile(NULL, profile); 253 | return PyInt_FromLong(r); 254 | } 255 | 256 | 257 | static PyObject* masterkeys_save_profile(PyObject* self, PyObject* args) { 258 | /** Save changes made to the active profile */ 259 | int r = libmk_save_profile(NULL); 260 | return PyInt_FromLong(r); 261 | } 262 | 263 | 264 | static PyObject* masterkeys_set_control_mode(PyObject* self, PyObject* args) { 265 | /** Set the control mode on the keyboard */ 266 | LibMK_ControlMode mode; 267 | if (!PyArg_ParseTuple(args, "i", &mode)) 268 | return NULL; 269 | return PyInt_FromLong(libmk_set_control_mode(NULL, mode)); 270 | } 271 | 272 | 273 | static struct PyMethodDef masterkeys_funcs[] = { 274 | { 275 | "detect_devices", 276 | masterkeys_detect_devices, 277 | METH_NOARGS, 278 | "Return a tuple of connected device models" 279 | }, { 280 | "set_device", 281 | masterkeys_set_device, 282 | METH_VARARGS, 283 | "Set the device to control with the library" 284 | }, { 285 | "enable_control", 286 | masterkeys_enable_control, 287 | METH_NOARGS, 288 | "Enable control of the RGB LEDs on the controlled device" 289 | }, { 290 | "disable_control", 291 | masterkeys_disable_control, 292 | METH_NOARGS, 293 | "Disable control of the RGB LEDs on the controlled device" 294 | }, { 295 | "set_effect", 296 | masterkeys_set_effect, 297 | METH_VARARGS, 298 | "Set the LED lighting effect of the controlled device" 299 | }, { 300 | "set_all_led_color", 301 | masterkeys_set_all_led_color, 302 | METH_VARARGS, 303 | "Set the color of all the LEDs on the controlled device " 304 | "individually", 305 | }, { 306 | "set_full_led_color", 307 | masterkeys_set_full_color, 308 | METH_VARARGS, 309 | "Set the color of all the LEDs on the controlled device to a " 310 | "single color" 311 | }, { 312 | "set_ind_led_color", 313 | masterkeys_set_ind_led_color, 314 | METH_VARARGS, 315 | "Set the color of a single LED on the controlled device" 316 | }, { 317 | "set_effect_details", 318 | masterkeys_set_effect_details, 319 | METH_VARARGS, 320 | "Set the effect on the keyboard with specific arguments" 321 | }, { 322 | "get_device_ident", 323 | masterkeys_get_device_ident, 324 | METH_NOARGS, 325 | "Return the bDevice USB descriptor value" 326 | }, { 327 | "get_active_profile", 328 | masterkeys_get_active_profile, 329 | METH_VARARGS, 330 | "Return the number of the active profile" 331 | }, { 332 | "set_active_profile", 333 | masterkeys_set_active_profile, 334 | METH_VARARGS, 335 | "Set the active profile on the keyboard" 336 | }, { 337 | "save_profile", 338 | masterkeys_save_profile, 339 | METH_VARARGS, 340 | "Save the changes made to the active profile" 341 | }, { 342 | "set_control_mode", 343 | masterkeys_set_control_mode, 344 | METH_VARARGS, 345 | "Set the control mode of the keyboard" 346 | }, {NULL, NULL, 0, NULL} 347 | }; 348 | 349 | 350 | #if PY_MAJOR_VERSION < 3 351 | PyMODINIT_FUNC initmasterkeys(void) { 352 | masterkeys_init(NULL, NULL); 353 | (void) Py_InitModule("masterkeys", masterkeys_funcs); 354 | } 355 | #else // PY_MAJOR_VERSION >= 3 356 | static struct PyModuleDef masterkeys_module_def = { 357 | PyModuleDef_HEAD_INIT, 358 | "masterkeys", 359 | "Library to control MasterKeys keyboard lighting", 360 | -1, 361 | masterkeys_funcs 362 | }; 363 | PyMODINIT_FUNC PyInit_masterkeys(void) { 364 | masterkeys_init(NULL, NULL); 365 | return PyModule_Create(&masterkeys_module_def); 366 | } 367 | #endif 368 | -------------------------------------------------------------------------------- /libmk/libmk.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: RedFantom 3 | * License: GNU GPLv3 4 | * Copyright (c) 2018-2019 RedFantom 5 | * 6 | * @file libmk.h 7 | * @author RedFantom 8 | * @date 2018-2019 9 | * @brief Header file of libmk 10 | * 11 | * Contains all the enums, macro and function definitions for libmk 12 | */ 13 | #include "libusb.h" 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | /** Library settings */ 21 | #define LIBMK_USB_DESCR_LEN 255 22 | #define LIBMK_PACKET_SIZE 64 23 | #define LIBMK_IFACE_NUM 1 // Interface number of the HID device 24 | #define LIBMK_PACKET_TIMEOUT 50 25 | #define LIBMK_EP_IN 0x03 26 | #define LIBMK_EP_OUT 0x04 27 | 28 | /// @brief Maximum number of rows supported on any device 29 | #define LIBMK_MAX_ROWS 7 30 | /// @brief Maximum number of columns supported on any device 31 | #define LIBMK_MAX_COLS 24 32 | #define LIBMK_ALL_LED_PCK_NUM 8 33 | #define LIBMK_ALL_LED_PER_PCK 16 34 | 35 | /// @brief Error codes used within libmk 36 | typedef enum LibMK_Result { 37 | LIBMK_SUCCESS = 0, ///< The one and only success code 38 | LIBMK_ERR_INVALID_DEV = -1, ///< Invalid device specified 39 | LIBMK_ERR_DEV_NOT_CONNECTED = -2, ///< Device specified not connected 40 | LIBMK_ERR_DEV_NOT_SET = -3, ///< Device has not been set 41 | LIBMK_ERR_UNKNOWN_LAYOUT = -14, ///< Device has unknown layout 42 | LIBMK_ERR_DEV_NOT_CLOSED = -15, ///< Device access not closed 43 | LIBMK_ERR_DEV_RESET_FAILED = -16, ///< Device (libusb) reset failed 44 | LIBMK_ERR_IFACE_CLAIM_FAILED = -4, ///< Failed to claim libusb interface 45 | LIBMK_ERR_IFACE_RELEASE_FAILED = -5, ///< Failed to release libusb interface 46 | LIBMK_ERR_DEV_CLOSE_FAILED = -6, ///< Failed to close libusb device 47 | LIBMK_ERR_DEV_OPEN_FAILED = -7, ///< Failed to open libusb device 48 | LIBMK_ERR_KERNEL_DRIVER = -8, ///< Failed to unload kernel driver 49 | LIBMK_ERR_DEV_LIST = -9, ///< Failed to retrieve libusb device list 50 | LIBMK_ERR_TRANSFER = -10, ///< Failed to transfer data to or from device 51 | LIBMK_ERR_DESCR = -11, ///< Failed to get libusb device descriptor 52 | LIBMK_ERR_PROTOCOL = -13, ///< Keyboard interaction protocol error 53 | LIBMK_ERR_INVALID_ARG = -14, ///< Invalid arguments passed by caller 54 | LIBMK_ERR_STILL_ACTIVE = -15, ///< Controller is still active 55 | } LibMK_Result; 56 | 57 | 58 | /// @brief LED Effect Types 59 | typedef enum LibMK_Effect { 60 | LIBMK_EFF_FULL = 0, ///< All LEDs in a single color 61 | LIBMK_EFF_BREATH = 1, ///< All LEDs single color turning slowly on and off 62 | LIBMK_EFF_BREATH_CYCLE = 2, ///< All LEDs cycling through different colors 63 | LIBMK_EFF_SINGLE = 3, ///< Keystrokes highlighted with fading light 64 | LIBMK_EFF_WAVE = 4, ///< Color wave over all keys 65 | LIBMK_EFF_RIPPLE = 5, ///< Rippling effect from keystroke 66 | LIBMK_EFF_CROSS = 6, ///< Fading cross-effect from keystroke 67 | LIBMK_EFF_RAIN = 7, ///< Diagonal streaks of light 68 | LIBMK_EFF_STAR = 8, ///< Fading dots in a random pattern 69 | LIBMK_EFF_SNAKE = 9, ///< Snake game 70 | LIBMK_EFF_CUSTOM = 10, ///< Custom LED layout 71 | LIBMK_EFF_OFF = 0xFE, ///< LEDs off 72 | 73 | // MasterMouse effects 74 | LIBMK_EFF_SPECTRUM = 11, ///< Not used 75 | LIBMK_EFF_RAPID_FIRE = 12 ///< Not used 76 | } LibMK_Effect; 77 | 78 | 79 | /// @brief Supported control modes 80 | typedef enum LibMK_ControlMode { 81 | LIBMK_FIRMWARE_CTRL = 0x00, ///< Default state, no interaction 82 | LIBMK_EFFECT_CTRL = 0x01, ///< Software controls lighting effects 83 | LIBMK_CUSTOM_CTRL = 0x02, ///< Software controls individual LEDs 84 | LIBMK_PROFILE_CTRL = 0x03, ///< Software controls profiles 85 | } LibMK_ControlMode; 86 | 87 | 88 | /// @brief Supported keyboard layouts 89 | typedef enum LibMK_Layout { 90 | LIBMK_LAYOUT_UNKNOWN = 0, 91 | LIBMK_LAYOUT_ANSI = 1, 92 | LIBMK_LAYOUT_ISO = 2, 93 | LIBMK_LAYOUT_JP = 3 ///< Currently not supported 94 | } LibMK_Layout; 95 | 96 | 97 | /// @brief Firmware details (version) and layout (speculative) 98 | typedef struct LibMK_Firmware { 99 | unsigned char major; 100 | unsigned char minor; 101 | unsigned char patch; 102 | unsigned char layout; 103 | char string[6]; 104 | } LibMK_Firmware; 105 | 106 | 107 | /// @brief Supported keyboard sizes 108 | typedef enum LibMK_Size { 109 | LIBMK_L = 0, 110 | LIBMK_M = 1, 111 | LIBMK_S = 2 112 | } LibMK_Size; 113 | 114 | 115 | /// @brief Supported keyboard models 116 | typedef enum LibMK_Model { 117 | DEV_RGB_L = 0, 118 | DEV_RGB_M = 5, 119 | DEV_RGB_S = 1, 120 | 121 | DEV_WHITE_L = 2, 122 | DEV_WHITE_M = 3, 123 | DEV_WHITE_S = 7, 124 | 125 | DEV_NOT_SET = -1, ///< Device not set globally 126 | DEV_ANY = -2, ///< Any supported device 127 | DEV_UNKNOWN = -3, ///< Unrecognized device 128 | } LibMK_Model; 129 | 130 | 131 | /** @brief Struct describing a supported USB device 132 | * 133 | * This struct may be used as a linked list. Holds information required 134 | * for the identification of the keyboard on the machine. 135 | */ 136 | typedef struct LibMK_Device { 137 | char* iManufacturer; ///< Manufacturer string 138 | char* iProduct; ///< Product string 139 | int bVendor; ///< USB Vendor ID number 140 | int bDevice; ///< USB Device ID number 141 | LibMK_Model model; ///< Model number 142 | struct LibMK_Device* next; ///< Linked list attribute 143 | libusb_device* device; ///< libusb_device struct instance 144 | } LibMK_Device; 145 | 146 | 147 | /** @brief Array of strings representing the supported models */ 148 | extern const char* LIBMK_MODEL_STRINGS[]; 149 | 150 | /** @brief Struct describing an opened supported device 151 | * 152 | * Result of libmk_set_device(LibMK_Model, LibMK_Handle**). Contains all 153 | * the required data to control a keyboard device. Contains a 154 | * libusb_device_handle* to allow interaction with the keyboard 155 | * endpoints by the library. Multiple of these may be availble in your 156 | * program, but no multiple handles for a single device are allowed. 157 | */ 158 | typedef struct LibMK_Handle { 159 | LibMK_Model model; ///< Model of the keyboard this handle controls 160 | int bVendor; ///< USB bVendor ID number 161 | int bDevice; ///< USB bDevice ID number 162 | LibMK_Layout layout; ///< Layout of this device 163 | LibMK_Size size; ///< Size of this device 164 | libusb_device_handle* handle; ///< libusb_device_handle required for 165 | ///< reading from and writing to the 166 | ///< device endpoints 167 | bool open; ///< Current state of the handle. If closed, the handle 168 | ///< is no longer valid. Handles may not be re-opened. 169 | } LibMK_Handle; 170 | 171 | 172 | /** @brief Struct describing an effect with custom settings 173 | * 174 | * Apart from the default settings that are applied when an effect is 175 | * applied using libmk_set_effect, custom settings may be applied to 176 | * and effect. Each effect implements these settings differently. 177 | * 178 | * For example: by using a background color of red and a foreground 179 | * color orange with the effect LIBMK_EFF_STAR, a star effect is applied 180 | * of fading orange-lit keys. All keys that are not 'stars' are red in 181 | * color. The amount attribute changes the amount of 'stars' shown and 182 | * the speed attribute the speed with which they fade in and out. 183 | * 184 | * Not all attributes are supported by all effects. Some will have no 185 | * influence at all. 186 | */ 187 | // TODO: Document all the parameters for all the effects 188 | typedef struct LibMK_Effect_Details { 189 | LibMK_Effect effect; 190 | unsigned char speed; ///< Running speed of the effect 191 | unsigned char direction; ///< Direction of the effect 192 | unsigned char amount; ///< Intensity modifier of the effect. Not 193 | ///< supported by all effects in the same way. 194 | unsigned char foreground[3]; ///< Foreground color of the effect 195 | unsigned char background[3]; ///< Background color of the effect 196 | } LibMK_Effect_Details; 197 | 198 | /** @brief Initialize the library and its dependencies to a usable state 199 | * 200 | * Initializes a default libusb context for use throughout the library. 201 | * If a call to this function is omitted, segmentation faults will be 202 | * the result. 203 | */ 204 | bool libmk_init(); 205 | 206 | /** @brief Clean-up the library resources 207 | * 208 | * Frees up the memory used by the libusb context used throughout the 209 | * library. Support for re-initialization after this function is called 210 | * is not guaranteed. Use only at the end of the program. 211 | */ 212 | int libmk_exit(); 213 | 214 | /** @brief Search for devices and put the found models in an array 215 | * 216 | * @param model_list: Pointer to an array of LibMK_Model enums. Required 217 | * memory for storage is allocated by the function and must be freed 218 | * by the caller. 219 | * @returns The number of found devices, or a LibMK_Result error code. 220 | * 221 | * Perform a search for devices using libusb and store all the found 222 | * supported devices in an allocated array of LibMK_Model. 223 | */ 224 | int libmk_detect_devices(LibMK_Model** model_list); 225 | 226 | /** @brief Internal function. Loads the details of a device 227 | * 228 | * @param device: libusb device descriptor to load details for 229 | * @returns pointer to LibMK_Device instance if successful, NULL 230 | * otherwise 231 | * 232 | * Loads the details of a USB device into a LibMK_Device struct instance. 233 | * The details are used by libmk_detect_devices to determine whether a 234 | * device is supported. 235 | */ 236 | LibMK_Device* libmk_open_device(libusb_device* device); 237 | 238 | /** @brief Internal function. Allocate and fill LibMK_Device struct */ 239 | LibMK_Device* libmk_create_device( 240 | LibMK_Model model, libusb_device* device, 241 | char* iManufacturer, char* iProduct, 242 | int bVendor, int bDevice); 243 | 244 | /** @brief Internal function. Free memory of allocated LibMK_Device */ 245 | void libmk_free_device(LibMK_Device* device); 246 | 247 | /** @brief Internal function. Build linked list with LibMK_Device */ 248 | LibMK_Device* libmk_append_device(LibMK_Device* first, LibMK_Device* device); 249 | 250 | /** @brief Identify a model based on its USB descriptor product string */ 251 | LibMK_Model libmk_ident_model(char* product); 252 | 253 | /** @brief Internal function. Allocate and fill LibMK_Handle struct */ 254 | int libmk_create_handle(LibMK_Handle** handle, LibMK_Device* device); 255 | 256 | /** @brief Internal function. Free memory of allocated LibMK_Handle */ 257 | int libmk_free_handle(LibMK_Handle* handle); 258 | 259 | /** @brief Initialize a device within the library 260 | * 261 | * @param model: Model to initialize. The model must be connected, else 262 | * LIBMK_ERR_DEV_NOT_CONNECTED is returned. 263 | * @param handle: Pointer to pointer of struct LibMK_Handle. The funtion 264 | * allocates a LibMK_Handle struct and stores a pointer to it here. 265 | * @returns LibMK_Result code, NULL or valid pointer in *handle. 266 | * 267 | * If NULL is passed for handle the function will set the global 268 | * LibMK_Handle to the device specified. The function chooses the first 269 | * available device of the specified model to assign to the handle. 270 | */ 271 | int libmk_set_device(LibMK_Model model, LibMK_Handle** handle); 272 | 273 | /** @brief Initialize the keyboard for control and send control packet 274 | * 275 | * @param handle: LibMK_Handle* for the device to control. If NULL, the 276 | * global handle is used. 277 | * @returns LibMK_Result result code 278 | * 279 | * Must be called in order to be able to control the keyboard. Claims 280 | * the LED interface on the keyboard USB controller with the appropriate 281 | * endpoints for control. 282 | */ 283 | int libmk_enable_control(LibMK_Handle* handle); 284 | 285 | /** @brief Release the keyboard from control 286 | * 287 | * @param handle: LibMK_Handle* for the device to release. If NULL, the 288 | * global handle is used. 289 | * @returns LibMK_Result result code 290 | * 291 | * Must be called when the user is done controlling the keyboard. 292 | * Support for re-enabling of control on the same LibMK_Handle is not 293 | * guaranteed. 294 | */ 295 | int libmk_disable_control(LibMK_Handle* handle); 296 | 297 | /** @brief Internal function. Claims USB LED interface on device */ 298 | int libmk_claim_interface(LibMK_Handle* handle); 299 | 300 | /** @brief Sends packet to put the keyboard in LIBMK_EFFECT_CTRL 301 | * 302 | * @param handle: LibMK_Handle* for the device to send the packet to. If 303 | * NULL, the global handle is used. 304 | * @returns LibMK_Result result code 305 | */ 306 | int libmk_send_control_packet(LibMK_Handle* handle); 307 | 308 | /** @brief Internal function. Reset the libusb interface when releasing */ 309 | int libmk_reset(LibMK_Handle* handle); 310 | 311 | /** @brief Internal function. Return the bDevice USB descriptor property */ 312 | int libmk_get_device_ident(LibMK_Handle* handle); 313 | 314 | /** @brief Retrieve details on the firmware version of the device 315 | * 316 | * @param handle: Handle to the device to retrieve firmware version of. 317 | * If NULL, the global handle is used. 318 | * @param fw: A LibMK_Firmware* is provided here if the firmware details 319 | * are retrieved successfully. 320 | * @returns LibMK_Result result code, NULL or LibMK_Firmware* in fw 321 | */ 322 | int libmk_get_firmware_version(LibMK_Handle* handle, LibMK_Firmware** fw); 323 | 324 | 325 | int libmk_set_control_mode(LibMK_Handle* handle, LibMK_ControlMode mode); 326 | 327 | /** @brief Send a single packet and verify the response 328 | * 329 | * @param handle: LibMK_Handle for the device to send the packet to 330 | * @param packet: Array of bytes (unsigned char) to send of size 331 | * LIBMK_PACKET_SIZE 332 | * @returns LibMK_Result result code 333 | * 334 | * Sends a single packet of data to the keyboard of size 335 | * LIBMK_PACKET_SIZE (will segfault if not properly sized!) and 336 | * verifies the response of the keyboard by checking the header 337 | * of the response packet. Frees the memory of the provided packet 338 | * pointer. 339 | */ 340 | int libmk_send_packet(LibMK_Handle* handle, unsigned char* packet); 341 | 342 | 343 | /** @brief Exchange a single packet with the keyboard 344 | * 345 | * @param handle: LibMK_Handle for the device to exchange data with 346 | * @param packet: Array of bytes (unsigned char) to send of size 347 | * LIBMK_PACKET_SIZE and to put response in 348 | * @returns LibMK_Result result code, response in packet 349 | * 350 | * Send a single packet to the keyboard and then store the response 351 | * in the packet array. Does not free the packet memory or verify 352 | * the response as an error response. 353 | */ 354 | int libmk_exch_packet(LibMK_Handle* handle, unsigned char* packet); 355 | 356 | /** @brief Set effect to be active on keyboard 357 | * 358 | * @param handle: LibMK_Handle for device to set effect on. If NULL uses 359 | * global device handle 360 | * @param effect: LibMK_Effect specifier of effect to activate 361 | * @returns LibMK_Result result code 362 | */ 363 | int libmk_set_effect(LibMK_Handle* handle, LibMK_Effect effect); 364 | 365 | /** @brief Set effect to be active on keyboard with parameters 366 | * 367 | * @param handle: LibMK_Handle for device to set effect on. If NULL uses 368 | * global device handle. 369 | * @param effect: LibMK_Effect_Details instance with all parameters set 370 | * @returns LibMK_Result result code 371 | */ 372 | int libmk_set_effect_details(LibMK_Handle* handle, LibMK_Effect_Details* effect); 373 | 374 | /** @brief Set color of all the LEDs on the keyboard to a single color 375 | * 376 | * @param handle: LibMK_Handle for device to set color off. If NULL uses 377 | * global device handle. 378 | * @param r: color byte red 379 | * @param g: color byte green 380 | * @param b: color byte blue 381 | * @returns LibMK_Result result code 382 | */ 383 | int libmk_set_full_color( 384 | LibMK_Handle* handle, unsigned char r, unsigned char g, unsigned char b); 385 | 386 | /** @brief Set the color of all the LEDs on the keyboard individually 387 | * 388 | * @param handle: LibMK_Handle for device to set the key colors on. If 389 | * NULL uses the global device handle. 390 | * @param colors: Pointer to array of unsigned char of 391 | * [LIBMK_MAX_ROWS][LIBMK_MAX_COLS][3] size. 392 | * @returns LibMK_Result result code 393 | */ 394 | int libmk_set_all_led_color(LibMK_Handle* handle, unsigned char* colors); 395 | 396 | /** @brief Set the color of a single LED on the keyboard 397 | * 398 | * @param handle: LibMK_Handle for device to set the color of the key 399 | * on. If NULL uses the global device handle. 400 | * @param row: Zero-indexed row index 401 | * @param col: Zero-indexed column index 402 | * @param r: color byte red 403 | * @param g: color byte green 404 | * @param b: color byte blue 405 | * @returns LibMK_Result result code 406 | */ 407 | int libmk_set_single_led( 408 | LibMK_Handle* handle, unsigned char row, unsigned char col, 409 | unsigned char r, unsigned char g, unsigned char b); 410 | 411 | /** @brief Retrieve the addressing offset of a specific key 412 | * 413 | * @param offset: Pointer to unsigned char to store offset in 414 | * @param handle: LibMK_Handle for the device to find the offset for. Is 415 | * required in order to determine the layout of the device. 416 | * @param row: Zero-indexed row index 417 | * @param col: Zero-indexed column index 418 | * @returns LibMK_Result result code 419 | */ 420 | int libmk_get_offset( 421 | unsigned char* offset, LibMK_Handle* handle, 422 | unsigned char row, unsigned char col); 423 | 424 | /** @brief Set the profile active on the device 425 | * 426 | * @param handle: LibMK_Handle for the device to set the profile on. If 427 | * NULL the global device handle is used. 428 | * @param profile: Number of the profile to activate. 429 | * @returns LibMK_Result result code 430 | * 431 | * The MasterKeys series of devices supports four individual lighting 432 | * profiles to which settings can be saved. A profile is activated by 433 | * changing the control mode and then activating the new profile. Any 434 | * changes applied to the lighting of the keyboard are lost when 435 | * changing the control mode to profile control. 436 | */ 437 | int libmk_set_active_profile(LibMK_Handle* handle, char profile); 438 | 439 | /** @brief Retrieve the number of the active profile on the device 440 | * 441 | * @param handle: LibMK_Handle for the device to get the number of the 442 | * active profile from. If NULL the global device handle is used. 443 | * @param profile: Pointer to the unsigned char to store the number of 444 | * the profile in. 445 | * @returns LibMK_Result result code 446 | */ 447 | int libmk_get_active_profile(LibMK_Handle* handle, char* profile); 448 | 449 | /** @brief Save the current lighting settings to the active profile 450 | * 451 | * @param handle: LibMK_Handle for the device to save the changes to. If 452 | * NULL the global device handle is used. 453 | * @returns LibMK_Result result code 454 | * 455 | * Saves the lighting settings to the profile that is returned by 456 | * libmk_get_active_profile. The changes persist after releasing control 457 | * of the keyboard, and even after power-cycling the keyboard. The 458 | * previous lighting configuration in the profile is deleted and 459 | * non-recoverable. 460 | */ 461 | int libmk_save_profile(LibMK_Handle* handle); 462 | 463 | /** @brief Send a packet specifying whether to expect a response 464 | * 465 | * @param handle: LibMK_Handle of the device to send the packet to. If 466 | * NULL the global device handle is used. 467 | * @param packet: Pointer to array of packet to send. 468 | * @param r: Whether to expect a response. If ``false``, the function 469 | * still attempts to read a response to make sure that the buffer is 470 | * empty. If ``true``, performs protocol error checks and yields an 471 | * error if no response was received. 472 | * @returns LibMK_Result result code 473 | */ 474 | int libmk_send_recv_packet(LibMK_Handle* handle, unsigned char* packet, bool r); 475 | 476 | /** @brief Build a new packet of data that can be sent to keyboard 477 | * 478 | * @param predef: Amount of bytes given in the variable arguments 479 | * @param ...: Bytes to from index zero of the packet. The amount of 480 | * bytes given must be equal to the amount specified by ``predef``, 481 | * otherwise this function will segfault. 482 | * @returns Pointer to the allocated packet with the set bytes. NULL if 483 | * no memory could be allocated. 484 | */ 485 | unsigned char* libmk_build_packet(unsigned char predef, ...); 486 | 487 | /** Debugging purposes */ 488 | void libmk_print_packet(unsigned char* packet, char* label); 489 | -------------------------------------------------------------------------------- /libmk/libmk.c: -------------------------------------------------------------------------------- 1 | /** Author: RedFantom 2 | * License: GNU GPLv3 3 | * Copyright (c) 2018-2019 RedFantom 4 | */ 5 | #include "libmk.h" 6 | #include "libusb.h" 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | // #define LIBMK_DEBUG 14 | // #define LIBMK_USB_DEBUG 15 | 16 | #ifndef LIBMK_DEBUG 17 | #define printf(fmt, ...) (0) 18 | #endif 19 | 20 | #define MANUFACTURER "Cooler Master Technology Inc." 21 | #define PRODUCT "MasterKeys" 22 | #define WHITE "White" 23 | #define LARGE "L" 24 | #define MEDIUM "M" 25 | #define SMALL "S" 26 | 27 | 28 | /** Global Variables 29 | * 30 | * Each instance of the library gets its own copy of these variables. 31 | * The variables are required so that if the library is loaded into a 32 | * different language (like Python), interaction is easier. 33 | */ 34 | static libusb_context* Context; 35 | static LibMK_Handle* DeviceHandle; 36 | 37 | typedef enum LibMK_Model LibMK_Model; 38 | typedef enum LibMK_Result LibMK_Result; 39 | typedef enum LibMK_Effect LibMK_Effect; 40 | typedef struct LibMK_Device LibMK_Device; 41 | 42 | /** Constants */ 43 | const unsigned char HEADER_SET = 0x51; // 1001 0001 44 | const unsigned char HEADER_GET = 0x52; // 1001 0010 45 | 46 | const unsigned char HEADER_FULL_COLOR = 0xc0; // 1100 0000 47 | const unsigned char HEADER_ERROR = 0xFF; // 1111 1111 48 | const unsigned char OPCODE_EFFECT = 0x28; // 0010 1000 49 | const unsigned char OPCODE_ALL_LED = 0xA8; // 1010 1000 50 | const unsigned char OPCODE_EFFECT_ARGS = 0x2c; // 0010 1100 51 | 52 | const unsigned int ANSI[] = 53 | {0x003b, 0x0000}; 54 | const unsigned int ISO[] = 55 | {0x0047, 0x0000}; 56 | 57 | const unsigned char LAYOUT_ANSI = 0; 58 | const unsigned char LAYOUT_ISO = 1; 59 | 60 | const char* LIBMK_MODEL_STRINGS[] = { 61 | "MasterKeys Pro L RGB", 62 | "MasterKeys Pro S RGB", 63 | "MasterKeys Pro L White", 64 | "MasterKeys Pro M White", 65 | "Unknown Model", 66 | "MasterKeys Pro M RGB", 67 | "Unknown Model", 68 | "MasterKeys Pro S White", 69 | }; 70 | 71 | /** Layout matrices 72 | * 73 | * These matrices describe the internal addresses of keys within the 74 | * keyboard. The matrix is in [row][column] format. A value of 0xFF 75 | * indicates an unknown value. 76 | */ 77 | const unsigned char LIBMK_LAYOUT[2][3][LIBMK_MAX_ROWS][LIBMK_MAX_COLS] = { 78 | { // ANSI Layouts 79 | // Layout size L 80 | {{0x0b, 0x16, 0x1e, 0x19, 0x1b, 0xff, 0x07, 0x33, 0x39, 0x3e, 0xff, 0x56, 81 | 0x57, 0x53, 0x55, 0x4f, 0x48, 0x00, 0x65, 0x6d, 0x75, 0x77, 0xff, 0xff}, 82 | {0x0e, 0x0f, 0x17, 0x1f, 0x27, 0x26, 0x2e, 0x2f, 0x37, 0x3f, 0x47, 0x46, 83 | 0x36, 0xff, 0x51, 0x03, 0x01, 0x02, 0x64, 0x6c, 0x74, 0x76, 0xff, 0xff}, 84 | {0x09, 0x08, 0x10, 0x18, 0x20, 0x21, 0x29, 0x28, 0x30, 0x38, 0x40, 0x41, 85 | 0x31, 0xff, 0x52, 0x5e, 0x5c, 0x58, 0x60, 0x68, 0x70, 0x6e, 0xff, 0xff}, 86 | {0x11, 0x0a, 0x12, 0x1a, 0x22, 0x23, 0x2b, 0x2a, 0x32, 0x3a, 0x42, 0x43, 87 | 0xff, 0xff, 0x54, 0xff, 0xff, 0xff, 0x61, 0x69, 0x71, 0xff, 0xff, 0xff}, 88 | {0x49, 0xff, 0x0c, 0x14, 0x1c, 0x24, 0x25, 0x2d, 0x2c, 0x34, 0x3c, 0x45, 89 | 0xff, 0xff, 0x4a, 0xff, 0x50, 0xff, 0x62, 0x6a, 0x72, 0x6f, 0xff, 0xff}, 90 | {0x06, 0x5a, 0x4b, 0xff, 0xff, 0xff, 0x5b, 0xff, 0xff, 0xff, 0x4d, 0x4e, 91 | 0x3d, 0xff, 0x04, 0x5f, 0x5d, 0x05, 0x6b, 0xff, 0x73, 0xff, 0xff, 0xff}, 92 | {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 93 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, 94 | // Layout size M 95 | // TODO: Find the key layout matrix of an ANSI M keyboard 96 | {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 97 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 98 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 99 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 100 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 101 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 102 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 103 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 104 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 105 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 106 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 107 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 108 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 109 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, 110 | // Layout size S 111 | {{0x60, 0x61, 0x62, 0x63, 0x68, 0xFF, 0x69, 0x6A, 0x70, 0x71, 0xFF, 0x72, 112 | 0x43, 0x44, 0x45, 0x66, 0x67, 0x6B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 113 | {0x00, 0x01, 0x08, 0x09, 0x10, 0x11, 0x18, 0x19, 0x20, 0x21, 0x28, 0x29, 114 | 0x30, 0xFF, 0x31, 0x38, 0x39, 0x40, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 115 | {0x02, 0x03, 0x0A, 0x0B, 0x12, 0x13, 0x1A, 0x1B, 0x22, 0x23, 0x2A, 0x2B, 116 | 0x32, 0xFF, 0x33, 0x3A, 0x3B, 0x42, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 117 | {0x04, 0x05, 0x0C, 0x0D, 0x14, 0x15, 0x1C, 0x1D, 0x24, 0x25, 0x2C, 0x2D, 118 | 0xFF, 0xFF, 0x34, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 119 | {0x06, 0xFF, 0x07, 0x0E, 0x0F, 0x16, 0x17, 0x1E, 0x1F, 0x26, 0x27, 0x2E, 120 | 0x01, 0xFF, 0x2F, 0xFF, 0x3D, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 121 | {0x5B, 0x5A, 0x5C, 0xFF, 0xFF, 0xFF, 0x5D, 0xFF, 0xFF, 0xFF, 0x5E, 0x3C, 122 | 0x5F, 0xFF, 0x36, 0x3F, 0x3E, 0x46, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 123 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 124 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, 125 | }, { // ISO Layouts 126 | // Layout size L 127 | // This key layout matrix was copied from libcmmk, GNU GPLv3 128 | {{0x0B, 0x16, 0x1E, 0x19, 0x1B, 0xFF, 0x07, 0x33, 0x39, 0x3E, 0xFF, 0x56, 129 | 0x57, 0x53, 0x55, 0x4F, 0x48, 0x00, 0x65, 0x6D, 0x75, 0x77, 0xFF, 0xFF}, 130 | {0x0E, 0x0F, 0x17, 0x1F, 0x27, 0x26, 0x2E, 0x2F, 0x37, 0x3F, 0x47, 0x46, 131 | 0x36, 0xFF, 0x51, 0x03, 0x01, 0x02, 0x64, 0x6C, 0x74, 0x76, 0xFF, 0xFF}, 132 | {0x09, 0x08, 0x10, 0x18, 0x20, 0x21, 0x29, 0x28, 0x30, 0x38, 0x40, 0x41, 133 | 0x31, 0xFF, 0x54, 0x5E, 0x5C, 0x58, 0x60, 0x68, 0x70, 0x6E, 0xFF, 0xFF}, 134 | {0x11, 0x0A, 0x12, 0x1A, 0x22, 0x23, 0x2B, 0x2A, 0x32, 0x3A, 0x42, 0x43, 135 | 0x44, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x61, 0x69, 0x71, 0xFF, 0xFF, 0xFF}, 136 | {0x49, 0x13, 0x0C, 0x14, 0x1C, 0x24, 0x25, 0x2D, 0x2C, 0x34, 0x3C, 0x45, 137 | 0xFF, 0xFF, 0x4A, 0xFF, 0x50, 0xFF, 0x62, 0x6A, 0x72, 0x6F, 0xFF, 0xFF}, 138 | {0x06, 0x5A, 0x4B, 0xFF, 0xFF, 0xFF, 0x5B, 0xFF, 0xFF, 0xFF, 0x4D, 0x4E, 139 | 0x3D, 0xFF, 0x04, 0x5F, 0x5D, 0x05, 0x6B, 0xFF, 0x73, 0xFF, 0xFF, 0xFF}, 140 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 141 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, 142 | // Layout size M 143 | // TODO: Find the key layout matrix of an ISO M keyboard 144 | {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 145 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 146 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 147 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 148 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 149 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 150 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 151 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 152 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 153 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 154 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 155 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 156 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 157 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, 158 | // Layout size S 159 | // TODO: Find the key layout matrix of an ISO S keyboard 160 | {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 161 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 162 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 163 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 164 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 165 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 166 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 167 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 168 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 169 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 170 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 171 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 172 | {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 173 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}} 174 | }, 175 | // TODO: If required, Japanese layouts may be added at index 2 of this array 176 | // TODO: so that it remains compatible with the LibMK_Layout enum and the 177 | // TODO: firmware defined layout 178 | }; 179 | 180 | 181 | bool libmk_init(void) { 182 | int result = libusb_init(&Context); 183 | #ifdef LIBMK_USB_DEBUG 184 | libusb_set_debug(Context, LIBUSB_LOG_LEVEL_DEBUG); 185 | #endif 186 | return (result == LIBUSB_SUCCESS); 187 | } 188 | 189 | 190 | int libmk_exit(void) { 191 | if (DeviceHandle != NULL) { 192 | int r = libmk_free_handle(DeviceHandle); 193 | if (r != LIBMK_SUCCESS) 194 | return r; 195 | } 196 | libusb_exit(Context); 197 | return LIBMK_SUCCESS; 198 | } 199 | 200 | 201 | int libmk_detect_devices(LibMK_Model** model_list) { 202 | libusb_device** devices = NULL; 203 | ssize_t amount = libusb_get_device_list(Context, &devices); 204 | if (amount < 0) 205 | return LIBMK_ERR_DEV_LIST; 206 | 207 | int n = 0; 208 | libusb_device* current = NULL; 209 | LibMK_Device* list = NULL; 210 | LibMK_Device* temp = NULL; 211 | 212 | // Build a linked list of Device structs of supported devices 213 | for (ssize_t i = 0; i < amount; i++) { 214 | current = devices[i]; 215 | if (current == NULL) 216 | break; 217 | temp = libmk_open_device(current); 218 | if (temp == NULL) // Not a MasterKeys device 219 | continue; 220 | 221 | list = libmk_append_device(list, temp); 222 | n = n + 1; 223 | } 224 | 225 | // Now build an array of Model numbers 226 | LibMK_Model* models = (LibMK_Model*) malloc(sizeof(LibMK_Model) * n); 227 | *model_list = models; 228 | temp = list; 229 | LibMK_Device* to_free; 230 | for (int j = 0; j < n; j++) { 231 | models[j] = temp->model; 232 | to_free = temp; 233 | if (temp->next != NULL) 234 | temp = temp->next; 235 | libmk_free_device(to_free); 236 | } 237 | return n; 238 | } 239 | 240 | 241 | LibMK_Device* libmk_open_device(libusb_device* device) { 242 | int r; 243 | struct libusb_device_descriptor descriptor; 244 | libusb_device_handle* handle = NULL; 245 | unsigned char* manufacturer = 246 | (unsigned char*) malloc(LIBMK_USB_DESCR_LEN * sizeof(unsigned char)); 247 | unsigned char* product = 248 | (unsigned char*) malloc(LIBMK_USB_DESCR_LEN * sizeof(unsigned char)); 249 | 250 | // Get the device descriptor of the next device 251 | r = libusb_get_device_descriptor(device, &descriptor); 252 | if (r < 0) 253 | return NULL; 254 | 255 | // Open the device and decode the descriptor strings 256 | r = libusb_open(device, &handle); 257 | if (r < 0) 258 | return NULL; 259 | 260 | libusb_get_string_descriptor_ascii( 261 | handle, descriptor.iManufacturer, 262 | manufacturer, LIBMK_USB_DESCR_LEN); 263 | libusb_get_string_descriptor_ascii( 264 | handle, descriptor.iProduct, 265 | product, LIBMK_USB_DESCR_LEN); 266 | 267 | if (strcmp((char*) manufacturer, MANUFACTURER) != 0) 268 | return NULL; 269 | 270 | // Build a Device descriptor 271 | LibMK_Model model = libmk_ident_model((char*) product); 272 | if (model == DEV_UNKNOWN) 273 | return NULL; 274 | 275 | LibMK_Device* device_struct = libmk_create_device( 276 | model, device, (char*) manufacturer, (char*) product, 277 | descriptor.idVendor, descriptor.idProduct); 278 | libusb_close(handle); 279 | return device_struct; 280 | } 281 | 282 | 283 | LibMK_Device* libmk_create_device(LibMK_Model model, libusb_device* dev, 284 | char* iManufacturer, char* iProduct, 285 | int bVendor, int bDevice) { 286 | char* m_str = (char*) malloc((strlen(iManufacturer) + 1) * sizeof(char)); 287 | char* p_str = (char*) malloc((strlen(iProduct) + 1) * sizeof(char)); 288 | strcpy(m_str, iManufacturer); 289 | strcpy(p_str, iProduct); 290 | LibMK_Device* device = (LibMK_Device*) malloc(sizeof(LibMK_Device)); 291 | device->iManufacturer = m_str; 292 | device->iProduct = p_str; 293 | device->bVendor = bVendor; 294 | device->bDevice = bDevice; 295 | device->device = dev; 296 | device->model = model; 297 | return device; 298 | } 299 | 300 | 301 | void libmk_free_device(LibMK_Device* device) { 302 | free(device->iManufacturer); 303 | free(device->iProduct); 304 | free(device); 305 | } 306 | 307 | 308 | LibMK_Device* libmk_append_device(LibMK_Device* first_device, 309 | LibMK_Device* device) { 310 | if (first_device == NULL) 311 | return device; 312 | LibMK_Device* current = first_device; 313 | while (current->next != NULL) 314 | current = current->next; 315 | current->next = device; 316 | return first_device; 317 | } 318 | 319 | 320 | int libmk_create_handle(LibMK_Handle** handle, LibMK_Device* device) { 321 | *handle = (LibMK_Handle*) malloc(sizeof(LibMK_Handle)); 322 | if (*handle == NULL) 323 | return LIBMK_ERR_DEV_OPEN_FAILED; 324 | int r = libusb_open(device->device, &(*handle)->handle); 325 | if (r != 0) 326 | return LIBMK_ERR_DEV_OPEN_FAILED; 327 | (*handle)->open = true; 328 | (*handle)->model = device->model; 329 | (*handle)->bDevice = device->bDevice; 330 | (*handle)->bVendor = device->bVendor; 331 | LibMK_Model model = device->model; 332 | if (model == DEV_RGB_L || model == DEV_WHITE_L) 333 | (*handle)->size = LIBMK_L; 334 | else if (model == DEV_RGB_M || model == DEV_WHITE_M) 335 | (*handle)->size = LIBMK_M; 336 | else if (model == DEV_RGB_S || model == DEV_WHITE_S) 337 | (*handle)->size = LIBMK_S; 338 | else { 339 | libusb_close((*handle)->handle); 340 | return LIBMK_ERR_UNKNOWN_LAYOUT; 341 | } 342 | return LIBMK_SUCCESS; 343 | } 344 | 345 | 346 | int libmk_free_handle(LibMK_Handle* handle) { 347 | if (handle->open) 348 | return LIBMK_ERR_DEV_NOT_CLOSED; 349 | free(handle); 350 | return LIBMK_SUCCESS; 351 | } 352 | 353 | 354 | int libmk_set_device(LibMK_Model model, LibMK_Handle** handle) { 355 | libusb_device** devices; 356 | ssize_t amount = libusb_get_device_list(NULL, &devices); 357 | if (amount < 0) 358 | return LIBMK_ERR_DEV_LIST; 359 | 360 | // Variables required for looping over the device list 361 | int r; // libusb requires error handling with return values 362 | libusb_device* current = NULL; 363 | libusb_device* device = NULL; 364 | struct libusb_device_descriptor descriptor; 365 | libusb_device_handle* usb_handle; 366 | 367 | // Strings to store decoded device descriptors in 368 | unsigned char manufacturer[LIBMK_USB_DESCR_LEN]; 369 | unsigned char product[LIBMK_USB_DESCR_LEN]; 370 | 371 | for (ssize_t i = 0; i < amount; i++) { 372 | 373 | // Get the device descriptor of the next device 374 | current = devices[i]; 375 | r = libusb_get_device_descriptor(current, &descriptor); 376 | if (r < 0) 377 | return LIBMK_ERR_DESCR; 378 | 379 | // Open the device and decode the descriptor strings 380 | r = libusb_open(current, &usb_handle); 381 | if (r < 0) 382 | return LIBMK_ERR_DEV_OPEN_FAILED; 383 | libusb_get_string_descriptor_ascii( 384 | usb_handle, descriptor.iManufacturer, 385 | manufacturer, LIBMK_USB_DESCR_LEN); 386 | libusb_get_string_descriptor_ascii( 387 | usb_handle, descriptor.iProduct, 388 | product, LIBMK_USB_DESCR_LEN); 389 | 390 | // Determine whether this is a valid MasterKeys keyboard device 391 | if (strcmp((char*) manufacturer, MANUFACTURER) == 0) { 392 | if (model == DEV_ANY 393 | || libmk_ident_model((char*) product) == model) { 394 | 395 | device = current; 396 | libusb_close(usb_handle); 397 | break; 398 | } 399 | } 400 | libusb_close(usb_handle); 401 | } 402 | 403 | if (device == NULL) 404 | // No devices detected 405 | return LIBMK_ERR_DEV_NOT_CONNECTED; 406 | 407 | // Open the device into the handle 408 | LibMK_Device* dev = libmk_open_device(device); 409 | if (handle == NULL) 410 | handle = &DeviceHandle; 411 | r = libmk_create_handle(handle, dev); 412 | libusb_free_device_list(devices, true); 413 | return r; 414 | } 415 | 416 | 417 | LibMK_Model libmk_ident_model(char* product) { 418 | if (strstr(product, PRODUCT) == NULL) 419 | return DEV_UNKNOWN; 420 | if (strstr(product, WHITE) != NULL) { 421 | if (strstr(product, LARGE) != NULL) 422 | return DEV_WHITE_L; 423 | else if (strstr(product, SMALL) != NULL) 424 | return DEV_WHITE_S; 425 | return DEV_WHITE_M; 426 | } 427 | if (strstr(product, LARGE) != NULL) 428 | return DEV_RGB_L; 429 | else if (strstr(product, SMALL) != NULL) 430 | return DEV_RGB_S; 431 | return DEV_RGB_M; 432 | } 433 | 434 | 435 | int libmk_get_device_ident(LibMK_Handle* handle) { 436 | if (handle == NULL) 437 | handle = DeviceHandle; 438 | if (handle == NULL) 439 | return 0x0000; 440 | return DeviceHandle->bDevice; 441 | } 442 | 443 | 444 | int libmk_enable_control(LibMK_Handle* handle) { 445 | int r; // Stores libusb return values 446 | 447 | if (handle == NULL) 448 | handle = DeviceHandle; 449 | if (handle == NULL) 450 | return LIBMK_ERR_DEV_NOT_SET; 451 | 452 | // Claim the interface on the device 453 | r = libmk_claim_interface(handle); 454 | if (r != LIBMK_SUCCESS) 455 | return LIBMK_ERR_IFACE_CLAIM_FAILED; 456 | 457 | // Send the enable control packet to the keyboard 458 | return libmk_send_control_packet(handle); 459 | } 460 | 461 | 462 | int libmk_send_control_packet(LibMK_Handle* handle) { 463 | int r = libmk_set_control_mode(handle, LIBMK_CUSTOM_CTRL); 464 | if (r != LIBMK_SUCCESS) 465 | return r; 466 | LibMK_Firmware* fw; 467 | r = libmk_get_firmware_version(handle, &fw); 468 | if (r != LIBMK_SUCCESS) { 469 | libusb_close(handle->handle); 470 | return r; 471 | } 472 | handle->layout = fw->layout; 473 | return LIBMK_SUCCESS; 474 | } 475 | 476 | 477 | int libmk_disable_control(LibMK_Handle* handle) { 478 | if (handle == NULL) 479 | handle = DeviceHandle; 480 | if (handle == NULL) 481 | return LIBMK_ERR_DEV_NOT_SET; 482 | 483 | int r = libmk_set_control_mode(handle, LIBMK_FIRMWARE_CTRL); 484 | if (r != LIBMK_SUCCESS) 485 | return r; 486 | 487 | r = libusb_release_interface(handle->handle, LIBMK_IFACE_NUM); 488 | if (r < 0) 489 | return LIBMK_ERR_IFACE_RELEASE_FAILED; 490 | 491 | libusb_close(handle->handle); 492 | handle->open = false; 493 | if (handle == DeviceHandle) { 494 | libmk_free_handle(handle); 495 | DeviceHandle = NULL; 496 | } 497 | libusb_reset_device(handle->handle); 498 | return LIBMK_SUCCESS; 499 | } 500 | 501 | 502 | int libmk_claim_interface(LibMK_Handle* handle) { 503 | int r; 504 | if (handle == NULL) 505 | handle = DeviceHandle; 506 | if (handle == NULL) 507 | return LIBMK_ERR_DEV_NOT_SET; 508 | 509 | // Unload the kernel driver for the device if it is active 510 | if (libusb_kernel_driver_active(handle->handle, LIBMK_IFACE_NUM)) { 511 | r = libusb_detach_kernel_driver(handle->handle, LIBMK_IFACE_NUM); 512 | if (r < 0) 513 | return LIBMK_ERR_KERNEL_DRIVER; 514 | } 515 | 516 | // Claim the interface on the device 517 | r = libusb_claim_interface(handle->handle, LIBMK_IFACE_NUM); 518 | if (r < 0) 519 | return LIBMK_ERR_IFACE_CLAIM_FAILED; 520 | return LIBMK_SUCCESS; 521 | } 522 | 523 | 524 | int libmk_set_effect(LibMK_Handle* handle, LibMK_Effect effect) { 525 | if (handle == NULL) 526 | handle = DeviceHandle; 527 | if (handle == NULL) 528 | return LIBMK_ERR_DEV_NOT_SET; 529 | 530 | unsigned char* packet = libmk_build_packet( 531 | 2, 0x41, 0x01); 532 | int r = libmk_send_packet(handle, packet); 533 | if (r != LIBMK_SUCCESS) 534 | return r; 535 | packet = libmk_build_packet( 536 | 5, HEADER_SET, OPCODE_EFFECT, 0x00, 0x00, (unsigned char) effect); 537 | return libmk_send_packet(handle, packet); 538 | } 539 | 540 | 541 | int libmk_set_full_color(LibMK_Handle* handle, 542 | unsigned char r, 543 | unsigned char g, 544 | unsigned char b) { 545 | if (handle == NULL) 546 | handle = DeviceHandle; 547 | if (handle == NULL) 548 | return LIBMK_ERR_DEV_NOT_SET; 549 | unsigned char* packet = libmk_build_packet( 550 | 7, HEADER_FULL_COLOR, 0x00, 0x00, 0x00, r, g, b); 551 | return libmk_send_packet(handle, packet); 552 | } 553 | 554 | 555 | int libmk_send_packet(LibMK_Handle* handle, unsigned char* packet) { 556 | return libmk_send_recv_packet(handle, packet, true); 557 | } 558 | 559 | 560 | int libmk_send_recv_packet( 561 | LibMK_Handle* handle, unsigned char* packet, bool response_required) { 562 | if (handle == NULL) 563 | handle = DeviceHandle; 564 | if (handle == NULL) 565 | return LIBMK_ERR_DEV_NOT_SET; 566 | int t, result; 567 | int r = libusb_interrupt_transfer( 568 | handle->handle, LIBMK_EP_OUT | LIBUSB_ENDPOINT_OUT, 569 | packet, LIBMK_PACKET_SIZE, &t, 570 | LIBMK_PACKET_TIMEOUT); 571 | #ifdef LIBMK_DEBUG 572 | libmk_print_packet(packet, "Sent"); 573 | #endif // LIBMK_DEBUG 574 | free(packet); 575 | if (r != 0 || t != LIBMK_PACKET_SIZE) 576 | return LIBMK_ERR_TRANSFER; 577 | packet = libmk_build_packet(0); 578 | r = libusb_interrupt_transfer( 579 | handle->handle, LIBMK_EP_IN | LIBUSB_ENDPOINT_IN, 580 | packet, LIBMK_PACKET_SIZE, &t, LIBMK_PACKET_TIMEOUT); 581 | #ifdef LIBMK_DEBUG 582 | libmk_print_packet(packet, "Response"); 583 | #endif // LIBMK_DEBUG 584 | if (r != LIBUSB_SUCCESS && response_required) { 585 | result = LIBMK_ERR_TRANSFER; 586 | } else if (t != LIBMK_PACKET_SIZE && response_required) { 587 | result = LIBMK_ERR_TRANSFER; 588 | } else if (packet[0] == HEADER_ERROR) { 589 | libmk_print_packet(packet, "Error response"); 590 | result = LIBMK_ERR_PROTOCOL; 591 | } else 592 | result = LIBMK_SUCCESS; 593 | free(packet); 594 | return result; 595 | } 596 | 597 | 598 | int libmk_exch_packet(LibMK_Handle* handle, unsigned char* packet) { 599 | int t; 600 | int r = libusb_interrupt_transfer( 601 | handle->handle, LIBMK_EP_OUT | LIBUSB_ENDPOINT_OUT, 602 | packet, LIBMK_PACKET_SIZE, &t, LIBMK_PACKET_TIMEOUT); 603 | #ifdef LIBMK_DEBUG 604 | libmk_print_packet(packet, "Sent"); 605 | #endif // LIBMK_DEBUG 606 | if (r != LIBUSB_SUCCESS || t != LIBMK_PACKET_SIZE) { 607 | free(packet); 608 | return LIBMK_ERR_TRANSFER; 609 | } 610 | r = libusb_interrupt_transfer( 611 | handle->handle, LIBMK_EP_IN | LIBUSB_ENDPOINT_IN, 612 | packet, LIBMK_PACKET_SIZE, &t, LIBMK_PACKET_TIMEOUT); 613 | #ifdef LIBMK_DEBUG 614 | libmk_print_packet(packet, "Received"); 615 | #endif // LIBMK_DEBUG 616 | if (r != LIBUSB_SUCCESS || t != LIBMK_PACKET_SIZE) 617 | return LIBMK_ERR_TRANSFER; 618 | return LIBMK_SUCCESS; 619 | } 620 | 621 | 622 | unsigned char* libmk_build_packet(unsigned char predef, ...) { 623 | unsigned char* packet = (unsigned char*) 624 | malloc(LIBMK_PACKET_SIZE * sizeof(unsigned char)); 625 | if (packet == NULL) 626 | return NULL; 627 | for (int i = 0; i < LIBMK_PACKET_SIZE; i++) 628 | packet[i] = 0x00; 629 | va_list elements; 630 | va_start(elements, predef); 631 | int elem; 632 | for (unsigned char i = 0; i < predef; i++) { 633 | elem = va_arg(elements, int); 634 | packet[i] = (unsigned char) elem; 635 | } 636 | va_end(elements); 637 | return packet; 638 | } 639 | 640 | 641 | int libmk_reset(LibMK_Handle* handle) { 642 | if (handle == NULL) 643 | handle = DeviceHandle; 644 | if (handle == NULL) 645 | return LIBMK_ERR_DEV_NOT_SET; 646 | int r = libusb_reset_device(handle->handle); 647 | if (r != LIBUSB_SUCCESS) 648 | return LIBMK_ERR_DEV_RESET_FAILED; 649 | return LIBMK_SUCCESS; 650 | } 651 | 652 | 653 | int libmk_set_all_led_color(LibMK_Handle* handle, unsigned char* colors) { 654 | if (handle == NULL) 655 | handle = DeviceHandle; 656 | if (handle == NULL) 657 | return LIBMK_ERR_DEV_NOT_SET; 658 | libmk_set_effect(handle, LIBMK_EFF_CUSTOM); 659 | unsigned char* packets[LIBMK_ALL_LED_PCK_NUM]; 660 | 661 | for (short i = 0; i < LIBMK_ALL_LED_PCK_NUM; i++) 662 | packets[i] = libmk_build_packet(3, HEADER_SET, 0xA8, (unsigned char) i * 2); 663 | 664 | unsigned char offset; 665 | int packet, index, result; 666 | 667 | for (unsigned char r = 0; r < LIBMK_MAX_ROWS; r++) 668 | for (unsigned char c = 0; c < LIBMK_MAX_COLS; c++) { 669 | result = libmk_get_offset(&offset, handle, r, c); 670 | if (result != LIBMK_SUCCESS) 671 | return result; 672 | if (offset == 0xFF) 673 | continue; 674 | packet = offset / LIBMK_ALL_LED_PER_PCK; 675 | index = offset % LIBMK_ALL_LED_PER_PCK; 676 | for (short o = 0; o < 3; o++) { 677 | packets[packet][4 + (index * 3) + o] = colors[ 678 | (r * LIBMK_MAX_COLS + c) * 3 + o]; 679 | } 680 | } 681 | 682 | for (short k = 0; k < LIBMK_ALL_LED_PCK_NUM; k++) { 683 | int r = libmk_send_packet(handle, packets[k]); 684 | if (r != LIBMK_SUCCESS) 685 | return r; 686 | } 687 | return LIBMK_SUCCESS; 688 | } 689 | 690 | 691 | inline void libmk_print_packet(unsigned char* packet, char* label) { 692 | #ifdef LIBMK_DEBUG 693 | printf("Packet: %s\n", label); 694 | for (unsigned char j = 0; j < LIBMK_PACKET_SIZE; j++) { 695 | printf("%02x ", packet[j]); 696 | if ((j + 1) % 16 == 0) { 697 | printf("\n"); 698 | } else if ((j + 1) % 8 == 0) 699 | printf(" "); 700 | } 701 | #endif 702 | } 703 | 704 | 705 | int libmk_get_offset( 706 | unsigned char* offset, LibMK_Handle* handle, 707 | unsigned char row, unsigned char col) { 708 | if (handle->layout != LAYOUT_ISO && handle->layout != LAYOUT_ANSI) 709 | return LIBMK_ERR_UNKNOWN_LAYOUT; 710 | *offset = LIBMK_LAYOUT[handle->layout - 1][handle->size][row][col]; 711 | return LIBMK_SUCCESS; 712 | } 713 | 714 | 715 | int libmk_set_single_led( 716 | LibMK_Handle* handle, unsigned char row, unsigned char col, 717 | unsigned char r, unsigned char g, unsigned char b) { 718 | if (handle == NULL) 719 | handle = DeviceHandle; 720 | if (handle == NULL) 721 | return LIBMK_ERR_DEV_NOT_SET; 722 | int result = libmk_set_control_mode(handle, LIBMK_CUSTOM_CTRL); 723 | if (result != LIBMK_SUCCESS) 724 | return result; 725 | unsigned char offset; 726 | result = libmk_get_offset(&offset, handle, row, col); 727 | if (result != LIBMK_SUCCESS) 728 | return result; 729 | unsigned char* packet = libmk_build_packet( 730 | 8, 0xC0, 0x01, 0x01, 0x00, offset, r, g, b); 731 | return libmk_send_packet(handle, packet); 732 | } 733 | 734 | 735 | int libmk_set_effect_details( 736 | LibMK_Handle* handle, LibMK_Effect_Details* effect) { 737 | if (handle == NULL) 738 | handle = DeviceHandle; 739 | if (handle == NULL) 740 | return LIBMK_ERR_DEV_NOT_SET; 741 | unsigned char* packet = libmk_build_packet( 742 | 10, HEADER_SET, OPCODE_EFFECT_ARGS, 0x00, 0x00, 743 | (unsigned char) effect->effect, effect->speed, effect->direction, 744 | effect->amount, 0xFF, 0xFF); 745 | unsigned char i; 746 | for (i=0; i < 3; i++) 747 | packet[10 + i] = effect->foreground[i]; 748 | for (i=0; i < 3; i++) 749 | packet[13 + i] = effect->background[i]; 750 | for (i=16; i < 64; i++) 751 | packet[i] = 0xFF; 752 | int r = libmk_set_effect(handle, effect->effect); 753 | if (r != LIBMK_SUCCESS) 754 | return r; 755 | return libmk_send_packet(handle, packet); 756 | } 757 | 758 | 759 | int libmk_get_firmware_version(LibMK_Handle* handle, LibMK_Firmware** fw) { 760 | if (handle == NULL) 761 | handle = DeviceHandle; 762 | if (handle == NULL) 763 | return LIBMK_ERR_DEV_NOT_SET; 764 | unsigned char* p = libmk_build_packet(2, 0x01, 0x02); 765 | int r = libmk_exch_packet(handle, p); 766 | if (r != LIBMK_SUCCESS) 767 | return r; 768 | (*fw) = (LibMK_Firmware*) malloc(sizeof(LibMK_Firmware)); 769 | for (unsigned char i=0; i<5; i++) 770 | (*fw)->string[i] = p[0x04 + i]; 771 | (*fw)->string[5] = 0x00; 772 | (*fw)->major = p[0x04] & 0x0F; 773 | (*fw)->minor = p[0x06] & 0x0F; 774 | (*fw)->patch = p[0x08] & 0x0F; 775 | (*fw)->layout = p[0x04] & 0x0F; 776 | return LIBMK_SUCCESS; 777 | } 778 | 779 | 780 | int libmk_save_profile(LibMK_Handle* handle) { 781 | if (handle == NULL) 782 | handle = DeviceHandle; 783 | if (handle == NULL) 784 | return LIBMK_ERR_DEV_NOT_SET; 785 | int r = libmk_set_control_mode(handle, LIBMK_PROFILE_CTRL); 786 | if (r != LIBMK_SUCCESS) 787 | return r; 788 | unsigned char* p = libmk_build_packet(2, 0x50, 0x55); 789 | r = libmk_send_recv_packet(handle, p, false); 790 | if (r != LIBMK_SUCCESS) 791 | return r; 792 | return libmk_set_control_mode(handle, LIBMK_CUSTOM_CTRL); 793 | } 794 | 795 | 796 | int libmk_set_active_profile(LibMK_Handle* handle, char profile) { 797 | if (handle == NULL) 798 | handle = DeviceHandle; 799 | if (handle == NULL) 800 | return LIBMK_ERR_DEV_NOT_SET; 801 | int r = libmk_set_control_mode(handle, LIBMK_PROFILE_CTRL); 802 | if (r != LIBMK_SUCCESS) 803 | return r; 804 | if (!(1 <= profile <= 4)) 805 | return LIBMK_ERR_INVALID_ARG; 806 | unsigned char* p = libmk_build_packet(5, HEADER_SET, 0x00, 0x00, 0x00, profile); 807 | r = libmk_send_packet(handle, p); 808 | if (r != LIBMK_SUCCESS) 809 | return r; 810 | return libmk_set_control_mode(handle, LIBMK_CUSTOM_CTRL); 811 | } 812 | 813 | 814 | int libmk_get_active_profile(LibMK_Handle* handle, char* profile) { 815 | if (handle == NULL) 816 | handle = DeviceHandle; 817 | if (handle == NULL) 818 | return LIBMK_ERR_DEV_NOT_SET; 819 | unsigned char* p = libmk_build_packet(1, 0x52); 820 | int r = libmk_exch_packet(handle, p); 821 | if (r != LIBMK_SUCCESS) 822 | return r; 823 | *profile = p[4]; 824 | free(p); 825 | return LIBMK_SUCCESS; 826 | } 827 | 828 | 829 | int libmk_set_control_mode(LibMK_Handle* handle, LibMK_ControlMode mode) { 830 | if (handle == NULL) 831 | handle = DeviceHandle; 832 | if (handle == NULL) 833 | return LIBMK_ERR_DEV_NOT_SET; 834 | char* p = libmk_build_packet(2, 0x41, mode); 835 | return libmk_send_recv_packet(handle, p, false); 836 | } 837 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ### GNU GENERAL PUBLIC LICENSE 2 | 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | 7 | 8 | Everyone is permitted to copy and distribute verbatim copies of this 9 | license document, but changing it is not allowed. 10 | 11 | ### Preamble 12 | 13 | The GNU General Public License is a free, copyleft license for 14 | software and other kinds of works. 15 | 16 | The licenses for most software and other practical works are designed 17 | to take away your freedom to share and change the works. By contrast, 18 | the GNU General Public License is intended to guarantee your freedom 19 | to share and change all versions of a program--to make sure it remains 20 | free software for all its users. We, the Free Software Foundation, use 21 | the GNU General Public License for most of our software; it applies 22 | also to any other work released this way by its authors. You can apply 23 | it to your programs, too. 24 | 25 | When we speak of free software, we are referring to freedom, not 26 | price. Our General Public Licenses are designed to make sure that you 27 | have the freedom to distribute copies of free software (and charge for 28 | them if you wish), that you receive source code or can get it if you 29 | want it, that you can change the software or use pieces of it in new 30 | free programs, and that you know you can do these things. 31 | 32 | To protect your rights, we need to prevent others from denying you 33 | these rights or asking you to surrender the rights. Therefore, you 34 | have certain responsibilities if you distribute copies of the 35 | software, or if you modify it: responsibilities to respect the freedom 36 | of others. 37 | 38 | For example, if you distribute copies of such a program, whether 39 | gratis or for a fee, you must pass on to the recipients the same 40 | freedoms that you received. You must make sure that they, too, receive 41 | or can get the source code. And you must show them these terms so they 42 | know their rights. 43 | 44 | Developers that use the GNU GPL protect your rights with two steps: 45 | (1) assert copyright on the software, and (2) offer you this License 46 | giving you legal permission to copy, distribute and/or modify it. 47 | 48 | For the developers' and authors' protection, the GPL clearly explains 49 | that there is no warranty for this free software. For both users' and 50 | authors' sake, the GPL requires that modified versions be marked as 51 | changed, so that their problems will not be attributed erroneously to 52 | authors of previous versions. 53 | 54 | Some devices are designed to deny users access to install or run 55 | modified versions of the software inside them, although the 56 | manufacturer can do so. This is fundamentally incompatible with the 57 | aim of protecting users' freedom to change the software. The 58 | systematic pattern of such abuse occurs in the area of products for 59 | individuals to use, which is precisely where it is most unacceptable. 60 | Therefore, we have designed this version of the GPL to prohibit the 61 | practice for those products. If such problems arise substantially in 62 | other domains, we stand ready to extend this provision to those 63 | domains in future versions of the GPL, as needed to protect the 64 | freedom of users. 65 | 66 | Finally, every program is threatened constantly by software patents. 67 | States should not allow patents to restrict development and use of 68 | software on general-purpose computers, but in those that do, we wish 69 | to avoid the special danger that patents applied to a free program 70 | could make it effectively proprietary. To prevent this, the GPL 71 | assures that patents cannot be used to render the program non-free. 72 | 73 | The precise terms and conditions for copying, distribution and 74 | modification follow. 75 | 76 | ### TERMS AND CONDITIONS 77 | 78 | #### 0. Definitions. 79 | 80 | "This License" refers to version 3 of the GNU General Public License. 81 | 82 | "Copyright" also means copyright-like laws that apply to other kinds 83 | of works, such as semiconductor masks. 84 | 85 | "The Program" refers to any copyrightable work licensed under this 86 | License. Each licensee is addressed as "you". "Licensees" and 87 | "recipients" may be individuals or organizations. 88 | 89 | To "modify" a work means to copy from or adapt all or part of the work 90 | in a fashion requiring copyright permission, other than the making of 91 | an exact copy. The resulting work is called a "modified version" of 92 | the earlier work or a work "based on" the earlier work. 93 | 94 | A "covered work" means either the unmodified Program or a work based 95 | on the Program. 96 | 97 | To "propagate" a work means to do anything with it that, without 98 | permission, would make you directly or secondarily liable for 99 | infringement under applicable copyright law, except executing it on a 100 | computer or modifying a private copy. Propagation includes copying, 101 | distribution (with or without modification), making available to the 102 | public, and in some countries other activities as well. 103 | 104 | To "convey" a work means any kind of propagation that enables other 105 | parties to make or receive copies. Mere interaction with a user 106 | through a computer network, with no transfer of a copy, is not 107 | conveying. 108 | 109 | An interactive user interface displays "Appropriate Legal Notices" to 110 | the extent that it includes a convenient and prominently visible 111 | feature that (1) displays an appropriate copyright notice, and (2) 112 | tells the user that there is no warranty for the work (except to the 113 | extent that warranties are provided), that licensees may convey the 114 | work under this License, and how to view a copy of this License. If 115 | the interface presents a list of user commands or options, such as a 116 | menu, a prominent item in the list meets this criterion. 117 | 118 | #### 1. Source Code. 119 | 120 | The "source code" for a work means the preferred form of the work for 121 | making modifications to it. "Object code" means any non-source form of 122 | a work. 123 | 124 | A "Standard Interface" means an interface that either is an official 125 | standard defined by a recognized standards body, or, in the case of 126 | interfaces specified for a particular programming language, one that 127 | is widely used among developers working in that language. 128 | 129 | The "System Libraries" of an executable work include anything, other 130 | than the work as a whole, that (a) is included in the normal form of 131 | packaging a Major Component, but which is not part of that Major 132 | Component, and (b) serves only to enable use of the work with that 133 | Major Component, or to implement a Standard Interface for which an 134 | implementation is available to the public in source code form. A 135 | "Major Component", in this context, means a major essential component 136 | (kernel, window system, and so on) of the specific operating system 137 | (if any) on which the executable work runs, or a compiler used to 138 | produce the work, or an object code interpreter used to run it. 139 | 140 | The "Corresponding Source" for a work in object code form means all 141 | the source code needed to generate, install, and (for an executable 142 | work) run the object code and to modify the work, including scripts to 143 | control those activities. However, it does not include the work's 144 | System Libraries, or general-purpose tools or generally available free 145 | programs which are used unmodified in performing those activities but 146 | which are not part of the work. For example, Corresponding Source 147 | includes interface definition files associated with source files for 148 | the work, and the source code for shared libraries and dynamically 149 | linked subprograms that the work is specifically designed to require, 150 | such as by intimate data communication or control flow between those 151 | subprograms and other parts of the work. 152 | 153 | The Corresponding Source need not include anything that users can 154 | regenerate automatically from other parts of the Corresponding Source. 155 | 156 | The Corresponding Source for a work in source code form is that same 157 | work. 158 | 159 | #### 2. Basic Permissions. 160 | 161 | All rights granted under this License are granted for the term of 162 | copyright on the Program, and are irrevocable provided the stated 163 | conditions are met. This License explicitly affirms your unlimited 164 | permission to run the unmodified Program. The output from running a 165 | covered work is covered by this License only if the output, given its 166 | content, constitutes a covered work. This License acknowledges your 167 | rights of fair use or other equivalent, as provided by copyright law. 168 | 169 | You may make, run and propagate covered works that you do not convey, 170 | without conditions so long as your license otherwise remains in force. 171 | You may convey covered works to others for the sole purpose of having 172 | them make modifications exclusively for you, or provide you with 173 | facilities for running those works, provided that you comply with the 174 | terms of this License in conveying all material for which you do not 175 | control copyright. Those thus making or running the covered works for 176 | you must do so exclusively on your behalf, under your direction and 177 | control, on terms that prohibit them from making any copies of your 178 | copyrighted material outside their relationship with you. 179 | 180 | Conveying under any other circumstances is permitted solely under the 181 | conditions stated below. Sublicensing is not allowed; section 10 makes 182 | it unnecessary. 183 | 184 | #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 185 | 186 | No covered work shall be deemed part of an effective technological 187 | measure under any applicable law fulfilling obligations under article 188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 189 | similar laws prohibiting or restricting circumvention of such 190 | measures. 191 | 192 | When you convey a covered work, you waive any legal power to forbid 193 | circumvention of technological measures to the extent such 194 | circumvention is effected by exercising rights under this License with 195 | respect to the covered work, and you disclaim any intention to limit 196 | operation or modification of the work as a means of enforcing, against 197 | the work's users, your or third parties' legal rights to forbid 198 | circumvention of technological measures. 199 | 200 | #### 4. Conveying Verbatim Copies. 201 | 202 | You may convey verbatim copies of the Program's source code as you 203 | receive it, in any medium, provided that you conspicuously and 204 | appropriately publish on each copy an appropriate copyright notice; 205 | keep intact all notices stating that this License and any 206 | non-permissive terms added in accord with section 7 apply to the code; 207 | keep intact all notices of the absence of any warranty; and give all 208 | recipients a copy of this License along with the Program. 209 | 210 | You may charge any price or no price for each copy that you convey, 211 | and you may offer support or warranty protection for a fee. 212 | 213 | #### 5. Conveying Modified Source Versions. 214 | 215 | You may convey a work based on the Program, or the modifications to 216 | produce it from the Program, in the form of source code under the 217 | terms of section 4, provided that you also meet all of these 218 | conditions: 219 | 220 | - a) The work must carry prominent notices stating that you modified 221 | it, and giving a relevant date. 222 | - b) The work must carry prominent notices stating that it is 223 | released under this License and any conditions added under 224 | section 7. This requirement modifies the requirement in section 4 225 | to "keep intact all notices". 226 | - c) You must license the entire work, as a whole, under this 227 | License to anyone who comes into possession of a copy. This 228 | License will therefore apply, along with any applicable section 7 229 | additional terms, to the whole of the work, and all its parts, 230 | regardless of how they are packaged. This License gives no 231 | permission to license the work in any other way, but it does not 232 | invalidate such permission if you have separately received it. 233 | - d) If the work has interactive user interfaces, each must display 234 | Appropriate Legal Notices; however, if the Program has interactive 235 | interfaces that do not display Appropriate Legal Notices, your 236 | work need not make them do so. 237 | 238 | A compilation of a covered work with other separate and independent 239 | works, which are not by their nature extensions of the covered work, 240 | and which are not combined with it such as to form a larger program, 241 | in or on a volume of a storage or distribution medium, is called an 242 | "aggregate" if the compilation and its resulting copyright are not 243 | used to limit the access or legal rights of the compilation's users 244 | beyond what the individual works permit. Inclusion of a covered work 245 | in an aggregate does not cause this License to apply to the other 246 | parts of the aggregate. 247 | 248 | #### 6. Conveying Non-Source Forms. 249 | 250 | You may convey a covered work in object code form under the terms of 251 | sections 4 and 5, provided that you also convey the machine-readable 252 | Corresponding Source under the terms of this License, in one of these 253 | ways: 254 | 255 | - a) Convey the object code in, or embodied in, a physical product 256 | (including a physical distribution medium), accompanied by the 257 | Corresponding Source fixed on a durable physical medium 258 | customarily used for software interchange. 259 | - b) Convey the object code in, or embodied in, a physical product 260 | (including a physical distribution medium), accompanied by a 261 | written offer, valid for at least three years and valid for as 262 | long as you offer spare parts or customer support for that product 263 | model, to give anyone who possesses the object code either (1) a 264 | copy of the Corresponding Source for all the software in the 265 | product that is covered by this License, on a durable physical 266 | medium customarily used for software interchange, for a price no 267 | more than your reasonable cost of physically performing this 268 | conveying of source, or (2) access to copy the Corresponding 269 | Source from a network server at no charge. 270 | - c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | - d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | - e) Convey the object code using peer-to-peer transmission, 288 | provided you inform other peers where the object code and 289 | Corresponding Source of the work are being offered to the general 290 | public at no charge under subsection 6d. 291 | 292 | A separable portion of the object code, whose source code is excluded 293 | from the Corresponding Source as a System Library, need not be 294 | included in conveying the object code work. 295 | 296 | A "User Product" is either (1) a "consumer product", which means any 297 | tangible personal property which is normally used for personal, 298 | family, or household purposes, or (2) anything designed or sold for 299 | incorporation into a dwelling. In determining whether a product is a 300 | consumer product, doubtful cases shall be resolved in favor of 301 | coverage. For a particular product received by a particular user, 302 | "normally used" refers to a typical or common use of that class of 303 | product, regardless of the status of the particular user or of the way 304 | in which the particular user actually uses, or expects or is expected 305 | to use, the product. A product is a consumer product regardless of 306 | whether the product has substantial commercial, industrial or 307 | non-consumer uses, unless such uses represent the only significant 308 | mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to 312 | install and execute modified versions of a covered work in that User 313 | Product from a modified version of its Corresponding Source. The 314 | information must suffice to ensure that the continued functioning of 315 | the modified object code is in no case prevented or interfered with 316 | solely because modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or 331 | updates for a work that has been modified or installed by the 332 | recipient, or for the User Product in which it has been modified or 333 | installed. Access to a network may be denied when the modification 334 | itself materially and adversely affects the operation of the network 335 | or violates the rules and protocols for communication across the 336 | network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | #### 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders 364 | of that material) supplement the terms of this License with terms: 365 | 366 | - a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | - b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | - c) Prohibiting misrepresentation of the origin of that material, 372 | or requiring that modified versions of such material be marked in 373 | reasonable ways as different from the original version; or 374 | - d) Limiting the use for publicity purposes of names of licensors 375 | or authors of the material; or 376 | - e) Declining to grant rights under trademark law for use of some 377 | trade names, trademarks, or service marks; or 378 | - f) Requiring indemnification of licensors and authors of that 379 | material by anyone who conveys the material (or modified versions 380 | of it) with contractual assumptions of liability to the recipient, 381 | for any liability that these contractual assumptions directly 382 | impose on those licensors and authors. 383 | 384 | All other non-permissive additional terms are considered "further 385 | restrictions" within the meaning of section 10. If the Program as you 386 | received it, or any part of it, contains a notice stating that it is 387 | governed by this License along with a term that is a further 388 | restriction, you may remove that term. If a license document contains 389 | a further restriction but permits relicensing or conveying under this 390 | License, you may add to a covered work material governed by the terms 391 | of that license document, provided that the further restriction does 392 | not survive such relicensing or conveying. 393 | 394 | If you add terms to a covered work in accord with this section, you 395 | must place, in the relevant source files, a statement of the 396 | additional terms that apply to those files, or a notice indicating 397 | where to find the applicable terms. 398 | 399 | Additional terms, permissive or non-permissive, may be stated in the 400 | form of a separately written license, or stated as exceptions; the 401 | above requirements apply either way. 402 | 403 | #### 8. Termination. 404 | 405 | You may not propagate or modify a covered work except as expressly 406 | provided under this License. Any attempt otherwise to propagate or 407 | modify it is void, and will automatically terminate your rights under 408 | this License (including any patent licenses granted under the third 409 | paragraph of section 11). 410 | 411 | However, if you cease all violation of this License, then your license 412 | from a particular copyright holder is reinstated (a) provisionally, 413 | unless and until the copyright holder explicitly and finally 414 | terminates your license, and (b) permanently, if the copyright holder 415 | fails to notify you of the violation by some reasonable means prior to 416 | 60 days after the cessation. 417 | 418 | Moreover, your license from a particular copyright holder is 419 | reinstated permanently if the copyright holder notifies you of the 420 | violation by some reasonable means, this is the first time you have 421 | received notice of violation of this License (for any work) from that 422 | copyright holder, and you cure the violation prior to 30 days after 423 | your receipt of the notice. 424 | 425 | Termination of your rights under this section does not terminate the 426 | licenses of parties who have received copies or rights from you under 427 | this License. If your rights have been terminated and not permanently 428 | reinstated, you do not qualify to receive new licenses for the same 429 | material under section 10. 430 | 431 | #### 9. Acceptance Not Required for Having Copies. 432 | 433 | You are not required to accept this License in order to receive or run 434 | a copy of the Program. Ancillary propagation of a covered work 435 | occurring solely as a consequence of using peer-to-peer transmission 436 | to receive a copy likewise does not require acceptance. However, 437 | nothing other than this License grants you permission to propagate or 438 | modify any covered work. These actions infringe copyright if you do 439 | not accept this License. Therefore, by modifying or propagating a 440 | covered work, you indicate your acceptance of this License to do so. 441 | 442 | #### 10. Automatic Licensing of Downstream Recipients. 443 | 444 | Each time you convey a covered work, the recipient automatically 445 | receives a license from the original licensors, to run, modify and 446 | propagate that work, subject to this License. You are not responsible 447 | for enforcing compliance by third parties with this License. 448 | 449 | An "entity transaction" is a transaction transferring control of an 450 | organization, or substantially all assets of one, or subdividing an 451 | organization, or merging organizations. If propagation of a covered 452 | work results from an entity transaction, each party to that 453 | transaction who receives a copy of the work also receives whatever 454 | licenses to the work the party's predecessor in interest had or could 455 | give under the previous paragraph, plus a right to possession of the 456 | Corresponding Source of the work from the predecessor in interest, if 457 | the predecessor has it or can get it with reasonable efforts. 458 | 459 | You may not impose any further restrictions on the exercise of the 460 | rights granted or affirmed under this License. For example, you may 461 | not impose a license fee, royalty, or other charge for exercise of 462 | rights granted under this License, and you may not initiate litigation 463 | (including a cross-claim or counterclaim in a lawsuit) alleging that 464 | any patent claim is infringed by making, using, selling, offering for 465 | sale, or importing the Program or any portion of it. 466 | 467 | #### 11. Patents. 468 | 469 | A "contributor" is a copyright holder who authorizes use under this 470 | License of the Program or a work on which the Program is based. The 471 | work thus licensed is called the contributor's "contributor version". 472 | 473 | A contributor's "essential patent claims" are all patent claims owned 474 | or controlled by the contributor, whether already acquired or 475 | hereafter acquired, that would be infringed by some manner, permitted 476 | by this License, of making, using, or selling its contributor version, 477 | but do not include claims that would be infringed only as a 478 | consequence of further modification of the contributor version. For 479 | purposes of this definition, "control" includes the right to grant 480 | patent sublicenses in a manner consistent with the requirements of 481 | this License. 482 | 483 | Each contributor grants you a non-exclusive, worldwide, royalty-free 484 | patent license under the contributor's essential patent claims, to 485 | make, use, sell, offer for sale, import and otherwise run, modify and 486 | propagate the contents of its contributor version. 487 | 488 | In the following three paragraphs, a "patent license" is any express 489 | agreement or commitment, however denominated, not to enforce a patent 490 | (such as an express permission to practice a patent or covenant not to 491 | sue for patent infringement). To "grant" such a patent license to a 492 | party means to make such an agreement or commitment not to enforce a 493 | patent against the party. 494 | 495 | If you convey a covered work, knowingly relying on a patent license, 496 | and the Corresponding Source of the work is not available for anyone 497 | to copy, free of charge and under the terms of this License, through a 498 | publicly available network server or other readily accessible means, 499 | then you must either (1) cause the Corresponding Source to be so 500 | available, or (2) arrange to deprive yourself of the benefit of the 501 | patent license for this particular work, or (3) arrange, in a manner 502 | consistent with the requirements of this License, to extend the patent 503 | license to downstream recipients. "Knowingly relying" means you have 504 | actual knowledge that, but for the patent license, your conveying the 505 | covered work in a country, or your recipient's use of the covered work 506 | in a country, would infringe one or more identifiable patents in that 507 | country that you have reason to believe are valid. 508 | 509 | If, pursuant to or in connection with a single transaction or 510 | arrangement, you convey, or propagate by procuring conveyance of, a 511 | covered work, and grant a patent license to some of the parties 512 | receiving the covered work authorizing them to use, propagate, modify 513 | or convey a specific copy of the covered work, then the patent license 514 | you grant is automatically extended to all recipients of the covered 515 | work and works based on it. 516 | 517 | A patent license is "discriminatory" if it does not include within the 518 | scope of its coverage, prohibits the exercise of, or is conditioned on 519 | the non-exercise of one or more of the rights that are specifically 520 | granted under this License. You may not convey a covered work if you 521 | are a party to an arrangement with a third party that is in the 522 | business of distributing software, under which you make payment to the 523 | third party based on the extent of your activity of conveying the 524 | work, and under which the third party grants, to any of the parties 525 | who would receive the covered work from you, a discriminatory patent 526 | license (a) in connection with copies of the covered work conveyed by 527 | you (or copies made from those copies), or (b) primarily for and in 528 | connection with specific products or compilations that contain the 529 | covered work, unless you entered into that arrangement, or that patent 530 | license was granted, prior to 28 March 2007. 531 | 532 | Nothing in this License shall be construed as excluding or limiting 533 | any implied license or other defenses to infringement that may 534 | otherwise be available to you under applicable patent law. 535 | 536 | #### 12. No Surrender of Others' Freedom. 537 | 538 | If conditions are imposed on you (whether by court order, agreement or 539 | otherwise) that contradict the conditions of this License, they do not 540 | excuse you from the conditions of this License. If you cannot convey a 541 | covered work so as to satisfy simultaneously your obligations under 542 | this License and any other pertinent obligations, then as a 543 | consequence you may not convey it at all. For example, if you agree to 544 | terms that obligate you to collect a royalty for further conveying 545 | from those to whom you convey the Program, the only way you could 546 | satisfy both those terms and this License would be to refrain entirely 547 | from conveying the Program. 548 | 549 | #### 13. Use with the GNU Affero General Public License. 550 | 551 | Notwithstanding any other provision of this License, you have 552 | permission to link or combine any covered work with a work licensed 553 | under version 3 of the GNU Affero General Public License into a single 554 | combined work, and to convey the resulting work. The terms of this 555 | License will continue to apply to the part which is the covered work, 556 | but the special requirements of the GNU Affero General Public License, 557 | section 13, concerning interaction through a network will apply to the 558 | combination as such. 559 | 560 | #### 14. Revised Versions of this License. 561 | 562 | The Free Software Foundation may publish revised and/or new versions 563 | of the GNU General Public License from time to time. Such new versions 564 | will be similar in spirit to the present version, but may differ in 565 | detail to address new problems or concerns. 566 | 567 | Each version is given a distinguishing version number. If the Program 568 | specifies that a certain numbered version of the GNU General Public 569 | License "or any later version" applies to it, you have the option of 570 | following the terms and conditions either of that numbered version or 571 | of any later version published by the Free Software Foundation. If the 572 | Program does not specify a version number of the GNU General Public 573 | License, you may choose any version ever published by the Free 574 | Software Foundation. 575 | 576 | If the Program specifies that a proxy can decide which future versions 577 | of the GNU General Public License can be used, that proxy's public 578 | statement of acceptance of a version permanently authorizes you to 579 | choose that version for the Program. 580 | 581 | Later license versions may give you additional or different 582 | permissions. However, no additional obligations are imposed on any 583 | author or copyright holder as a result of your choosing to follow a 584 | later version. 585 | 586 | #### 15. Disclaimer of Warranty. 587 | 588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT 592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 596 | CORRECTION. 597 | 598 | #### 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR 602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES 604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT 605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR 606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM 607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER 608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 609 | 610 | #### 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | --------------------------------------------------------------------------------