Compare commits

...

10 commits

Author SHA1 Message Date
Moises Martinez
a908c0be7a restart docker container 2024-02-28 19:35:04 +00:00
Moises Martinez
93a71b6273 update README 2024-02-27 19:05:54 +00:00
Moises Martinez
4cd056f09e updated LICENSE 2024-02-27 18:57:28 +00:00
Moises Martinez
d6c2d580e3 more typos 2024-02-27 18:38:58 +00:00
Moises Martinez
9f14b18c67 another typo 2024-02-27 18:36:33 +00:00
Moises Martinez
6e520aaf18 fix more typos 2024-02-27 18:34:35 +00:00
Moises Martinez
4ca704e970 fix typo 2024-02-27 18:33:10 +00:00
Moises Martinez
caa16c27d5 Updated README and improved multimonitor support 2024-02-27 18:30:45 +00:00
Moises Martinez
bc4bc9afdb Dockerfile and docker-compose work 2024-02-27 06:33:04 +00:00
Moises Martinez
5c58be3aa8 First working implementation 2024-02-26 19:40:40 +00:00
14 changed files with 303 additions and 45 deletions

30
Dockerfile Normal file
View file

@ -0,0 +1,30 @@
# Use an official Python runtime as a parent image
FROM python:3.11
# Install system dependencies
RUN apt-get update && apt-get install -y \
libddcutil-dev \
libddcutil4 \
&& rm -rf /var/lib/apt/lists/*
# Set the working directory in the container
WORKDIR /usr/src/app
# Copy the current directory contents into the container at /usr/src/app
COPY . .
# Build the extension module
RUN (cd simpleddc-extension && python setup.py install)
# Install Python dependencies for the ddc-mqtt project
RUN pip install --no-cache-dir -r ./ddc-mqtt/requirements.txt
# Ensure the built module is available to the project
ENV PYTHONPATH "${PYTHONPATH}:/usr/src/app/simpleddc"
# Change the working directory to run the ddc-mqtt project
WORKDIR /usr/src/app/ddc-mqtt
# Run start.py when the container launches
CMD ["python", "start.py"]

7
LICENSE.md Normal file
View file

@ -0,0 +1,7 @@
Copyright (c) 2024 Moises Martinez
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

142
README.md Normal file
View file

@ -0,0 +1,142 @@
# ddc-mqtt - A simple software Display Input switch for DDC-supporting monitors
[!["Buy Me A Coffee"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/moimartb)
- Do you have a display with multiple inputs?
- Would you like to be able to switch inputs without the need of meddling with clunky OSD menus and akwardly-positioned control 'nipples'?
- Does this happen to you even with fancy, expensive displays like the Neo G9 line from Samsung?
- Can you imagine KVM scenarios based on home assistant automations?
Then this software is for you!!!
You only need a Linux machine connected to the display, a bit of knowledge on your display's support of DDC capabilities and this will
create a device for your Home Assistance (or your MQTT setup) so you can control the display
## Display's DDC capabilities
First of all, you'd need some info about your display and its DDC capabilities wrt display inputs. You'd need the *ddcutil* tool to figure
things out. For example: this is what my G95NC Samsung Neo G9 Reports:
```
$ ddcutil capabilities
Model: FALCON
MCCS version: 2.0
Commands:
Op Code: 01 (VCP Request)
Op Code: 02 (VCP Response)
Op Code: 03 (VCP Set)
Op Code: 07 (Timing Request)
Op Code: 0C (Save Settings)
Op Code: E3 (Capabilities Reply)
Op Code: F3 (Capabilities Request)
VCP Features:
Feature: 02 (New control value)
Feature: 04 (Restore factory defaults)
Feature: 05 (Restore factory brightness/contrast defaults)
Feature: 08 (Restore color defaults)
Feature: 10 (Brightness)
Feature: 12 (Contrast)
Feature: 14 (Select color preset)
Values:
05: 6500 K
08: 9300 K
0b: User 1
0c: User 2
Feature: 16 (Video gain: Red)
Feature: 18 (Video gain: Green)
Feature: 1A (Video gain: Blue)
Feature: 52 (Active control)
Feature: 60 (Input Source)
Values:
01: VGA-1
03: DVI-1
04: DVI-2
11: HDMI-1
12: HDMI-2
0f: DisplayPort-1
10: DisplayPort-2
Feature: 62 (Audio speaker volume)
Feature: 8D (Audio Mute)
Feature: FF (Manufacturer specific feature)
```
We'll focus on the **Feature: 60 (Input Source)** ... I have good news and bad news:
1. Good news: The display supports changing inputs with DDC!
2. Bad news: **The inputs and the values are, for the most part, bullsh\*t!!**
Because of this, we will need to figure out the actual input values for each actual input of the monitor.
You can use **ddcutil** again to figure them out like so:
```
# change the last number to figure the actual values that change the input.
# Have in mind these are hexadecimal values you'll need to convert to integers
$ sudo ddcutil setvcp 0x60 0x01
```
## Configuration
Once you have the values for the inputs you want to control, you can fill out the config.yml inside the folder ddc-mqtt that you'd need for the software to run. For my display this would be:
```
mqtt:
username: #your mqtt server's username
password: #your mqtt server's password
host: 1.2.3.4 #your mqtt server's host
port: 1883
display:
- id: 1 #display to control. if only a single monitor, this must be 1
inputs:
HDMI1: 5 # key: value — you can change the name of the input.
HDMI2: 6 # The codes here are input as integers, not hexadecimal
HDMI3: 7
DP: 15
interval: 20
```
## Setup
You might want to use the docker container that comes with the code. If you use a Raspberry Pi you just do:
```
$ docker-compose up -d
```
And if your config is well formed, that should be it!
If you don't use a Raspberry Pi, you might need to pay attention to the *docker-compose.yml* in the root folder as we are
forwarding the i2c devices for the ddcutil library to access.
```
devices:
- "/dev/i2c-20:/dev/i2c-20"
- "/dev/i2c-21:/dev/i2c-21" #these might be different in your machine
```
## Usage
If your MQTT server is shared or is part of a *Home Assistant* setup, the usage is simple. You'll get a device with switches to change inputs and that's all!
![Display KVM](https://raw.githubusercontent.com/moimart/ddc-mqtt/main/hass_display_kvm.jpg)'
If you want to use it MQTT RAW!!! you'd have access to the entities in the following paths:
```
Subscribe to kikkei/display-kvm/{number_of_display}/{input_name_in_the_config}/state
-> with values 'true' or 'false' to check the state
Publish 'ON' to kikkei/display-kvm/{number_of_display}/{input_name_in_the_config}/command for activation
-> no need to send 'OFF'; switching is taken care of
Example: kikkei/display-kvm/1/HDMI1/state
```
## Observations
This software is polling at an interval to re-check of the state of the active input— just in case you switch it manually...
This interval can be configured in the config.yml with the key interval. It is optional and by default is 20 seconds...
I coded this to support multiple monitors but I have not tested it at all... contributions are very welcome! :)
**Hope it works for you as well as it works for me!**

View file

@ -1,14 +1,14 @@
device = {
"identifiers": ["Kikkei Labs Display KVM"],
"name": "Display KVM",
"name": "Display KVM #?",
"model": "Kikkei-display-kvm-0",
"manufacturer": "Kikkei Labs",
}
display_device = {
"identifiers": ["Kid"],
"name": "Display # KVM",
"identifiers": ["Input"],
"name": "Display Input KVM #?",
"model": "Kikkei-display-kvm",
"manufacturer": "Kikkei Labs",
}
@ -16,13 +16,13 @@ display_device = {
display_input_entity = {
"generic_switch": 'homeassistant/switch/display-kvm-#/?-switch/config',
"generic_switch_config": {
"availability_topic": "kikkei/display-kvm/garbage",
"state_topic": "kikkei/display-kvm/kids/#/?/state",
"availability_topic": "kikkei/display-kvm/availability",
"state_topic": "kikkei/display-kvm/#/?/state",
"name": "",
"unique_id": "",
"object_id": "",
"payload_available": "ON",
"payload_not_available": "OFF",
"payload_available": "online",
"payload_not_available": "offline",
#"json_attributes_topic": "kikkei/household/#/%/attributes",
"state_on": "true",
"state_off": "false",

View file

@ -1,4 +1,3 @@
from devices import garbage_config
import paho.mqtt.client as mqtt
import json
from timer import Timer

View file

@ -4,10 +4,10 @@ mqtt:
host:
port: 1883
display:
id: 1
inputs:
hdmi1: 5
hdmi2: 6
hdmi3: 7
dp: 15
- id: 1
inputs:
HDMI1: 5
HDMI2: 6
HDMI3: 7
DP: 15
interval: 20

View file

@ -0,0 +1,2 @@
pyyaml>=6.0
paho-mqtt==1.6.1

View file

@ -4,17 +4,18 @@ from timeit import default_timer as timer
import yaml
import os
import json
from devices import display_device, display_input_entity, hass_display_sensor
from devices import display_device, display_input_entity
import simpleddc
class Service:
def __init__(self):
self.dt = 0
try:
with open("config.yaml","r") as config:
with open("config.yml","r") as config:
config = yaml.safe_load(config)
except Exception as e:
with open("rename_to_config.yaml","r") as config:
with open("rename_to_config.yml","r") as config:
config = yaml.safe_load(config)
self.mqtt = MQTTClient(config["mqtt"]["username"],
@ -22,38 +23,65 @@ class Service:
config["mqtt"]["host"],
config["mqtt"]["port"])
poll_interval = 20 if "interval" not in config else config["interval"]
self.mqtt.delegate = self
self.inputs = {}
display_data = config['display']
self.inputs[display_data['id']]['switches'] = []
print(display_data)
for input_name, input_code in display_data['inputs'].items():
self.create_display_switch(display_data['id'],input_name,input_code)
self.inputs = {}
for display in display_data:
self.inputs[display['id']] = { "switches": [] }
for input_name, input_code in display['inputs'].items():
self.create_display_switch(display['id'],input_name,input_code)
self.timer = Timer(poll_interval, self)
self.update_inputs_states()
self.timer = Timer(120, self)
def update_inputs_states(self):
#check what input is on by getting the code from simpleddc
#change the state of only that input
pass
for display_id in self.inputs.keys():
input_code = simpleddc.show_input(int(display_id))
print(f"Input code is {input_code}")
for entry in self.inputs[display_id]["switches"]:
if entry["code"] == input_code:
self.mqtt.client.publish(entry["topic"], "true")
entry["state"] = True
else:
self.mqtt.client.publish(entry["topic"], "false")
entry["state"] = False
def on_message(self, topic, payload):
if payload =='OFF':
return #do nothing
if "command" in topic:
self.activate_input_deactivate_rest(self.inputs[topic.split("/")[2]],topic.split("/")[3])
self.activate_input_deactivate_rest(int(topic.split("/")[2]),topic.split("/")[3])
def activate_input_deactivate_rest(display_id,display_name):
#check if this input is already on. if so, return
#if not, switch display to this input, set rest of inputs to off
pass
def activate_input_deactivate_rest(self, display_id,display_input):
print(f"Display {display_id} name {display_input}")
for entry in self.inputs[display_id]["switches"]:
if entry["id"] == display_input:
entry["state"] = True
self.mqtt.client.publish(entry["topic"], "true")
print(f'switching to {entry["code"]}')
simpleddc.switch_to_input(display_id, int(entry["code"]))
else:
entry["state"] = False
self.mqtt.client.publish(entry["topic"], "false")
def on_timer(self, timer, elapsed):
#check input states
self.timer.reset()
self.timer.active = True
self.update_inputs_states()
def step(self, dt):
self.timer.step(dt)
@ -61,30 +89,31 @@ class Service:
def create_display_switch(self, display_id, input_name, input_code):
topic = display_input_entity["generic_switch"]
topic = topic.replace("#", display_id)
topic = topic.replace("#", str(display_id))
topic = topic.replace("?", input_name)
config = display_input_entity["generic_switch_config"].copy()
config["unique_id"] = "{}_{}_switch".format(display_id,input_name)
config["object_id"] = "{}_{}_switch".format(display_id,input_name)
config["name"] = input_name
config["state_topic"] = config["state_topic"].replace("#", id)
config["state_topic"] = config["state_topic"].replace("#", str(display_id))
config["state_topic"] = config["state_topic"].replace("?", input_name)
device = display_device.copy()
device["name"] = device["name"].replace("#", input_name)
device["model"] = "{}-{}".format(device["model"],id)
device["name"] = device["name"].replace("?", input_name)
device["model"] = "{}-{}".format(device["model"],display_id)
config["device"] = device
config["command_topic"] = config["command_topic"].replace("#", id)
config["command_topic"] = config["command_topic"].replace("#", str(display_id))
config["command_topic"] = config["command_topic"].replace("?", input_name)
self.mqtt.client.publish(config["availability_topic"],"online", retain=True)
self.mqtt.client.publish(config["state_topic"], "off")
self.mqtt.client.publish(topic, json.dumps(config), retain=True)
self.mqtt.client.subscribe(config["command_topic"])
self.inputs[display_id]["switches"].append({"id": input_name, "topic": topic, "config": config, "code": input_code})
self.inputs[display_id]["switches"].append({"id": input_name, "topic": config["state_topic"], "config": config, "code": input_code, "state": False})
def start(self):
while True:
@ -93,4 +122,5 @@ class Service:
t1 = timer()
self.dt = t1 - t0
service = Service()
service.start()

13
docker-compose.yml Normal file
View file

@ -0,0 +1,13 @@
version: '3.8'
services:
app:
restart: unless-stopped
build: .
network_mode: "host"
volumes:
- .:/usr/src/app
devices:
- "/dev/i2c-20:/dev/i2c-20"
- "/dev/i2c-21:/dev/i2c-21"
environment:
- PYTHONUNBUFFERED=1

BIN
hass_display_kvm.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

View file

@ -6,6 +6,6 @@ module = Extension('simpleddc',
library_dirs=['/usr/lib/aarch64-linux-gnu/libddcutil.so.4'],
include_dirs=['/usr/include'])
setup(name='example',
setup(name='simpleddc',
version='1.0',
ext_modules=[module])

View file

@ -7,6 +7,7 @@
#include <ddcutil_status_codes.h>
DDCA_Display_Handle * open_first_display_by_dlist();
DDCA_Display_Handle * open_display_by_dlist(unsigned int display);
DDCA_Status switch_input(DDCA_Display_Handle* handle, uint8_t input);
uint8_t show_any_value(
DDCA_Display_Handle dh,

View file

@ -19,9 +19,16 @@ static PyObject* switch_to_input(PyObject* self, PyObject* args) {
}
static PyObject* show_input(PyObject* self, PyObject* args) {
DDCA_Display_Handle* handle = open_first_display_by_dlist();
uint8_t* display = malloc(sizeof(uint8_t));
if (!PyArg_ParseTuple(args, "i", display))
*display = 0;
DDCA_Display_Handle* handle = open_display_by_dlist(*display);
int result = show_any_value(handle,DDCA_NON_TABLE_VCP_VALUE, 0x60);
ddca_close_display(handle);
free(display);
return PyLong_FromLong(result);
}

View file

@ -8,7 +8,8 @@
ddca_rc_desc(status_code)); \
} while(0)
DDCA_Display_Handle * open_first_display_by_dlist() {
DDCA_Display_Handle * open_first_display_by_dlist()
{
printf("Check for monitors using ddca_get_displays()...\n");
DDCA_Display_Handle dh = NULL;
@ -20,13 +21,39 @@ DDCA_Display_Handle * open_first_display_by_dlist() {
if (dlist->ct == 0) {
printf(" No DDC capable displays found\n");
}
else {
} else {
DDCA_Display_Info * dinf = &dlist->info[0];
DDCA_Display_Ref * dref = dinf->dref;
printf("Opening display %s\n", dinf->model_name);
printf("Model: %s\n", dinf->model_name);
//printf("Model: %s\n", dinf->mmid.model_name);
DDCA_Status rc = ddca_open_display2(dref, false, &dh);
if (rc != 0) {
DDC_ERRMSG("ddca_open_display2", rc);
}
}
ddca_free_display_info_list(dlist);
return dh;
}
DDCA_Display_Handle * open_display_by_dlist(unsigned int display)
{
DDCA_Display_Handle dh = NULL;
// Inquire about detected monitors.
DDCA_Display_Info_List* dlist = NULL;
ddca_get_display_info_list2(
false, // don't include invalid displays
&dlist);
if (dlist->ct == 0 || dlist->ct < display) {
printf(" No DDC capable displays found\n");
} else {
DDCA_Display_Info * dinf = &dlist->info[display - 1];
DDCA_Display_Ref * dref = dinf->dref;
printf("Opening display %s\n", dinf->model_name);
printf("Model: %s\n", dinf->model_name);
DDCA_Status rc = ddca_open_display2(dref, false, &dh);
if (rc != 0) {
DDC_ERRMSG("ddca_open_display2", rc);