为 Skydimo 开发插件:REST API 完整参考 Developing Skydimo Plugins: Complete REST API Reference Разработка плагинов для Skydimo: полный справочник REST API Skydimo Eklentisi Geliştirme: Eksiksiz REST API Referansı
Skydimo REST API 接口文档、插件开发入门、WebSocket 实时推送与自定义效果开发指南。 Skydimo REST API documentation, plugin development basics, WebSocket real-time push, and custom effect development guide. Документация REST API Skydimo, основы разработки плагинов, WebSocket real-time push и руководство по созданию пользовательских эффектов. Skydimo REST API dokümantasyonu, eklenti geliştirmenin temelleri, WebSocket gerçek zamanlı push ve özel efekt geliştirme rehberi.
REST API 概述
Skydimo 提供完整的 REST API,允许外部应用程序控制所有 RGB 设备。
基础 URL:http://localhost:9527/api/v1
认证:API Token(在设置中生成)
内容类型:application/json
启用 API
设置 → 开发者 → 启用 REST API
端口:9527(可修改)
生成 API Token → 复制并保存
API 端点参考
获取所有设备
GET /api/v1/devices
Authorization: Bearer YOUR_TOKEN
响应示例:
{
"devices": [
{
"id": "usb:1234:5678",
"name": "Corsair K70 RGB",
"type": "keyboard",
"leds": 110,
"vendor": "Corsair",
"connected": true
},
{
"id": "smbus:1",
"name": "主板 ARGB 控制器",
"type": "motherboard",
"leds": 60,
"vendor": "Gigabyte",
"connected": true
}
]
}
设置设备颜色
PUT /api/v1/devices/{device_id}/color
Authorization: Bearer YOUR_TOKEN
Content-Type: application/json
{
"mode": "static",
"color": {"r": 255, "g": 0, "b": 128}
}
设置单个 LED
PUT /api/v1/devices/{device_id}/leds
Authorization: Bearer YOUR_TOKEN
{
"leds": [
{"index": 0, "r": 255, "g": 0, "b": 0},
{"index": 1, "r": 0, "g": 255, "b": 0},
{"index": 2, "r": 0, "g": 0, "b": 255}
]
}
应用配置方案
POST /api/v1/profiles/{profile_id}/apply
Authorization: Bearer YOUR_TOKEN
音乐同步控制
POST /api/v1/music-sync/start
POST /api/v1/music-sync/stop
GET /api/v1/music-sync/status
# 响应:{"active": true, "mode": "ai", "latency_ms": 18}
WebSocket 实时推送
Skydimo 支持 WebSocket 连接,实时接收设备状态和音频数据:
const ws = new WebSocket('ws://localhost:9527/ws');
ws.onopen = () => {
// 订阅音频频谱数据
ws.send(JSON.stringify({
type: 'subscribe',
topics: ['spectrum', 'device_state']
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'spectrum') {
// 实时频谱数据
const { bass, mid, high, raw } = data.payload;
// raw: Float32Array,257 个频率分量的能量值
updateVisualization(raw);
}
if (data.type === 'device_state') {
// 设备状态变化
console.log('Device updated:', data.payload);
}
};
频谱数据格式
interface SpectrumMessage {
type: 'spectrum';
timestamp: number;
payload: {
bass: number; // 0-1,低频能量
mid: number; // 0-1,中频能量
high: number; // 0-1,高频能量
bpm: number; // 当前检测到的 BPM
is_beat: boolean; // 当前帧是否为节拍点
raw: number[]; // 257 个频率分量
};
}
插件开发入门
Python 示例:音乐可视化插件
import requests
import websocket
import json
import colorsys
import threading
BASE_URL = "http://localhost:9527/api/v1"
TOKEN = "your_api_token_here"
headers = {"Authorization": f"Bearer {TOKEN}"}
def get_devices():
resp = requests.get(f"{BASE_URL}/devices", headers=headers)
return resp.json()["devices"]
def set_all_devices_color(r, g, b):
devices = get_devices()
for device in devices:
requests.put(
f"{BASE_URL}/devices/{device['id']}/color",
headers=headers,
json={"mode": "static", "color": {"r": r, "g": g, "b": b}}
)
def on_spectrum(ws, message):
data = json.loads(message)
if data["type"] != "spectrum":
return
payload = data["payload"]
bass = payload["bass"]
high = payload["high"]
# 将频谱映射为颜色
# Bass → 色调(低频=紫色,高频=青色)
hue = 0.75 - bass * 0.5 # 0.75=紫色, 0.5=蓝色
saturation = 1.0
value = 0.3 + bass * 0.7 # 响应 Bass 亮度
r, g, b = colorsys.hsv_to_rgb(hue, saturation, value)
set_all_devices_color(int(r*255), int(g*255), int(b*255))
def on_open(ws):
ws.send(json.dumps({
"type": "subscribe",
"topics": ["spectrum"]
}))
print("已连接到 Skydimo,开始音乐同步...")
ws = websocket.WebSocketApp(
"ws://localhost:9527/ws",
on_message=on_spectrum,
on_open=on_open
)
ws.run_forever()
JavaScript/Node.js 示例
const WebSocket = require('ws');
const fetch = require('node-fetch');
const BASE_URL = 'http://localhost:9527/api/v1';
const TOKEN = 'your_token';
async function setDeviceColor(deviceId, r, g, b) {
await fetch(`${BASE_URL}/devices/${deviceId}/color`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ mode: 'static', color: { r, g, b } }),
});
}
const ws = new WebSocket('ws://localhost:9527/ws');
ws.on('open', () => {
ws.send(JSON.stringify({ type: 'subscribe', topics: ['spectrum'] }));
});
ws.on('message', async (raw) => {
const msg = JSON.parse(raw);
if (msg.type !== 'spectrum') return;
const { bass, mid, high } = msg.payload;
// 低频→红色,中频→绿色,高频→蓝色的简单映射
const r = Math.round(bass * 255);
const g = Math.round(mid * 255);
const b = Math.round(high * 255);
// 获取所有设备并更新(实际应缓存设备列表)
const resp = await fetch(`${BASE_URL}/devices`, {
headers: { 'Authorization': `Bearer ${TOKEN}` }
});
const { devices } = await resp.json();
for (const device of devices) {
await setDeviceColor(device.id, r, g, b);
}
});
插件发布
完成开发后,可以将插件提交到 Skydimo 插件市场:
- 准备
plugin.json描述文件:
{
"name": "我的音乐插件",
"version": "1.0.0",
"description": "自定义音乐可视化效果",
"author": "你的名字",
"license": "MIT",
"entry": "main.py",
"requirements": ["requests", "websocket-client"]
}
- 将代码上传到 GitHub
- 提交到 Skydimo 插件市场:plugins.skydimo.com
API 速率限制
| 端点类型 | 限制 |
|---|---|
| 设备控制(PUT/POST) | 100 次/秒 |
| 设备查询(GET) | 无限制 |
| WebSocket 推送 | 无限制(服务端推送) |
| Batch 批量操作 | 20 次批次/秒 |
💡 最佳实践:使用 WebSocket 接收实时数据,仅在需要时通过 REST 发送控制命令,避免频繁轮询。
REST API Overview
Skydimo provides a complete REST API allowing external applications to control all RGB devices.
Base URL: http://localhost:9527/api/v1
Authentication: API Token (generate in Settings)
Content-Type: application/json
Enabling the API
Settings → Developer → Enable REST API
Port: 9527 (configurable)
Generate API Token → copy and save
API Endpoint Reference
Get All Devices
GET /api/v1/devices
Authorization: Bearer YOUR_TOKEN
Response example:
{
"devices": [
{
"id": "usb:1234:5678",
"name": "Corsair K70 RGB",
"type": "keyboard",
"leds": 110,
"vendor": "Corsair",
"connected": true
},
{
"id": "smbus:1",
"name": "Motherboard ARGB Controller",
"type": "motherboard",
"leds": 60,
"vendor": "Gigabyte",
"connected": true
}
]
}
Set Device Color
PUT /api/v1/devices/{device_id}/color
Authorization: Bearer YOUR_TOKEN
Content-Type: application/json
{
"mode": "static",
"color": {"r": 255, "g": 0, "b": 128}
}
Set Individual LEDs
PUT /api/v1/devices/{device_id}/leds
Authorization: Bearer YOUR_TOKEN
{
"leds": [
{"index": 0, "r": 255, "g": 0, "b": 0},
{"index": 1, "r": 0, "g": 255, "b": 0},
{"index": 2, "r": 0, "g": 0, "b": 255}
]
}
Apply Profile
POST /api/v1/profiles/{profile_id}/apply
Authorization: Bearer YOUR_TOKEN
Music Sync Control
POST /api/v1/music-sync/start
POST /api/v1/music-sync/stop
GET /api/v1/music-sync/status
# Response: {"active": true, "mode": "ai", "latency_ms": 18}
WebSocket Real-Time Push
Skydimo supports WebSocket connections for real-time reception of device state and audio data:
const ws = new WebSocket('ws://localhost:9527/ws');
ws.onopen = () => {
// Subscribe to audio spectrum data
ws.send(JSON.stringify({
type: 'subscribe',
topics: ['spectrum', 'device_state']
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'spectrum') {
// Real-time spectrum data
const { bass, mid, high, raw } = data.payload;
// raw: Float32Array, energy values for 257 frequency components
updateVisualization(raw);
}
if (data.type === 'device_state') {
// Device state change
console.log('Device updated:', data.payload);
}
};
Spectrum Data Format
interface SpectrumMessage {
type: 'spectrum';
timestamp: number;
payload: {
bass: number; // 0-1, low frequency energy
mid: number; // 0-1, mid frequency energy
high: number; // 0-1, high frequency energy
bpm: number; // currently detected BPM
is_beat: boolean; // whether the current frame is a beat point
raw: number[]; // 257 frequency components
};
}
Plugin Development Basics
Python Example: Music Visualization Plugin
import requests
import websocket
import json
import colorsys
import threading
BASE_URL = "http://localhost:9527/api/v1"
TOKEN = "your_api_token_here"
headers = {"Authorization": f"Bearer {TOKEN}"}
def get_devices():
resp = requests.get(f"{BASE_URL}/devices", headers=headers)
return resp.json()["devices"]
def set_all_devices_color(r, g, b):
devices = get_devices()
for device in devices:
requests.put(
f"{BASE_URL}/devices/{device['id']}/color",
headers=headers,
json={"mode": "static", "color": {"r": r, "g": g, "b": b}}
)
def on_spectrum(ws, message):
data = json.loads(message)
if data["type"] != "spectrum":
return
payload = data["payload"]
bass = payload["bass"]
high = payload["high"]
# Map spectrum to color
# Bass → hue (low freq = purple, high freq = cyan)
hue = 0.75 - bass * 0.5 # 0.75=purple, 0.5=blue
saturation = 1.0
value = 0.3 + bass * 0.7 # brightness responds to bass
r, g, b = colorsys.hsv_to_rgb(hue, saturation, value)
set_all_devices_color(int(r*255), int(g*255), int(b*255))
def on_open(ws):
ws.send(json.dumps({
"type": "subscribe",
"topics": ["spectrum"]
}))
print("Connected to Skydimo, starting music sync...")
ws = websocket.WebSocketApp(
"ws://localhost:9527/ws",
on_message=on_spectrum,
on_open=on_open
)
ws.run_forever()
JavaScript/Node.js Example
const WebSocket = require('ws');
const fetch = require('node-fetch');
const BASE_URL = 'http://localhost:9527/api/v1';
const TOKEN = 'your_token';
async function setDeviceColor(deviceId, r, g, b) {
await fetch(`${BASE_URL}/devices/${deviceId}/color`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ mode: 'static', color: { r, g, b } }),
});
}
const ws = new WebSocket('ws://localhost:9527/ws');
ws.on('open', () => {
ws.send(JSON.stringify({ type: 'subscribe', topics: ['spectrum'] }));
});
ws.on('message', async (raw) => {
const msg = JSON.parse(raw);
if (msg.type !== 'spectrum') return;
const { bass, mid, high } = msg.payload;
// Simple mapping: bass → red, mid → green, high → blue
const r = Math.round(bass * 255);
const g = Math.round(mid * 255);
const b = Math.round(high * 255);
// Get all devices and update (cache the device list in production)
const resp = await fetch(`${BASE_URL}/devices`, {
headers: { 'Authorization': `Bearer ${TOKEN}` }
});
const { devices } = await resp.json();
for (const device of devices) {
await setDeviceColor(device.id, r, g, b);
}
});
Publishing Plugins
Once development is complete, submit your plugin to the Skydimo Plugin Marketplace:
- Prepare a
plugin.jsonmanifest file:
{
"name": "My Music Plugin",
"version": "1.0.0",
"description": "Custom music visualization effect",
"author": "Your Name",
"license": "MIT",
"entry": "main.py",
"requirements": ["requests", "websocket-client"]
}
- Upload your code to GitHub
- Submit to the Skydimo Plugin Marketplace: plugins.skydimo.com
API Rate Limits
| Endpoint Type | Limit |
|---|---|
| Device control (PUT/POST) | 100 requests/second |
| Device query (GET) | Unlimited |
| WebSocket push | Unlimited (server-side push) |
| Batch operations | 20 batches/second |
💡 Best practice: Use WebSocket to receive real-time data and only send control commands via REST when needed — avoid frequent polling.
Обзор REST API
Skydimo предоставляет полноценный REST API, позволяющий внешним приложениям управлять всеми RGB-устройствами.
Базовый URL: http://localhost:9527/api/v1
Аутентификация: API Token (генерируется в настройках)
Content-Type: application/json
Включение API
Настройки → Разработчик → Включить REST API
Порт: 9527 (можно изменить)
Сгенерировать API Token → скопировать и сохранить
Справочник эндпоинтов API
Получить все устройства
GET /api/v1/devices
Authorization: Bearer YOUR_TOKEN
Пример ответа:
{
"devices": [
{
"id": "usb:1234:5678",
"name": "Corsair K70 RGB",
"type": "keyboard",
"leds": 110,
"vendor": "Corsair",
"connected": true
},
{
"id": "smbus:1",
"name": "ARGB-контроллер материнской платы",
"type": "motherboard",
"leds": 60,
"vendor": "Gigabyte",
"connected": true
}
]
}
Установить цвет устройства
PUT /api/v1/devices/{device_id}/color
Authorization: Bearer YOUR_TOKEN
Content-Type: application/json
{
"mode": "static",
"color": {"r": 255, "g": 0, "b": 128}
}
Установить отдельные LED
PUT /api/v1/devices/{device_id}/leds
Authorization: Bearer YOUR_TOKEN
{
"leds": [
{"index": 0, "r": 255, "g": 0, "b": 0},
{"index": 1, "r": 0, "g": 255, "b": 0},
{"index": 2, "r": 0, "g": 0, "b": 255}
]
}
Применить профиль
POST /api/v1/profiles/{profile_id}/apply
Authorization: Bearer YOUR_TOKEN
Управление синхронизацией с музыкой
POST /api/v1/music-sync/start
POST /api/v1/music-sync/stop
GET /api/v1/music-sync/status
# Ответ: {"active": true, "mode": "ai", "latency_ms": 18}
WebSocket real-time push
Skydimo поддерживает WebSocket-соединения для получения в реальном времени данных о состоянии устройств и аудио:
const ws = new WebSocket('ws://localhost:9527/ws');
ws.onopen = () => {
// Подписываемся на данные аудиоспектра
ws.send(JSON.stringify({
type: 'subscribe',
topics: ['spectrum', 'device_state']
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'spectrum') {
// Данные спектра в реальном времени
const { bass, mid, high, raw } = data.payload;
// raw: Float32Array, значения энергии 257 частотных компонентов
updateVisualization(raw);
}
if (data.type === 'device_state') {
// Изменение состояния устройства
console.log('Device updated:', data.payload);
}
};
Формат данных спектра
interface SpectrumMessage {
type: 'spectrum';
timestamp: number;
payload: {
bass: number; // 0-1, энергия низких частот
mid: number; // 0-1, энергия средних частот
high: number; // 0-1, энергия высоких частот
bpm: number; // текущее определённое BPM
is_beat: boolean; // является ли текущий кадр точкой бита
raw: number[]; // 257 частотных компонентов
};
}
Основы разработки плагинов
Пример на Python: плагин музыкальной визуализации
import requests
import websocket
import json
import colorsys
import threading
BASE_URL = "http://localhost:9527/api/v1"
TOKEN = "your_api_token_here"
headers = {"Authorization": f"Bearer {TOKEN}"}
def get_devices():
resp = requests.get(f"{BASE_URL}/devices", headers=headers)
return resp.json()["devices"]
def set_all_devices_color(r, g, b):
devices = get_devices()
for device in devices:
requests.put(
f"{BASE_URL}/devices/{device['id']}/color",
headers=headers,
json={"mode": "static", "color": {"r": r, "g": g, "b": b}}
)
def on_spectrum(ws, message):
data = json.loads(message)
if data["type"] != "spectrum":
return
payload = data["payload"]
bass = payload["bass"]
high = payload["high"]
# Бас → оттенок (низкие частоты = фиолетовый, высокие = голубой)
hue = 0.75 - bass * 0.5 # 0.75=фиолетовый, 0.5=синий
saturation = 1.0
value = 0.3 + bass * 0.7 # яркость реагирует на бас
r, g, b = colorsys.hsv_to_rgb(hue, saturation, value)
set_all_devices_color(int(r*255), int(g*255), int(b*255))
def on_open(ws):
ws.send(json.dumps({
"type": "subscribe",
"topics": ["spectrum"]
}))
print("Подключено к Skydimo, запуск синхронизации с музыкой...")
ws = websocket.WebSocketApp(
"ws://localhost:9527/ws",
on_message=on_spectrum,
on_open=on_open
)
ws.run_forever()
Пример на JavaScript/Node.js
const WebSocket = require('ws');
const fetch = require('node-fetch');
const BASE_URL = 'http://localhost:9527/api/v1';
const TOKEN = 'your_token';
async function setDeviceColor(deviceId, r, g, b) {
await fetch(`${BASE_URL}/devices/${deviceId}/color`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ mode: 'static', color: { r, g, b } }),
});
}
const ws = new WebSocket('ws://localhost:9527/ws');
ws.on('open', () => {
ws.send(JSON.stringify({ type: 'subscribe', topics: ['spectrum'] }));
});
ws.on('message', async (raw) => {
const msg = JSON.parse(raw);
if (msg.type !== 'spectrum') return;
const { bass, mid, high } = msg.payload;
// Простое отображение: бас → красный, средние → зелёный, высокие → синий
const r = Math.round(bass * 255);
const g = Math.round(mid * 255);
const b = Math.round(high * 255);
// Получаем все устройства и обновляем (в продакшне кэшируйте список)
const resp = await fetch(`${BASE_URL}/devices`, {
headers: { 'Authorization': `Bearer ${TOKEN}` }
});
const { devices } = await resp.json();
for (const device of devices) {
await setDeviceColor(device.id, r, g, b);
}
});
Публикация плагинов
После завершения разработки отправьте плагин на маркетплейс плагинов Skydimo:
- Подготовьте файл манифеста
plugin.json:
{
"name": "Мой музыкальный плагин",
"version": "1.0.0",
"description": "Пользовательский эффект музыкальной визуализации",
"author": "Ваше имя",
"license": "MIT",
"entry": "main.py",
"requirements": ["requests", "websocket-client"]
}
- Загрузите код на GitHub
- Отправьте на маркетплейс плагинов Skydimo: plugins.skydimo.com
Ограничения скорости API
| Тип эндпоинта | Лимит |
|---|---|
| Управление устройством (PUT/POST) | 100 запросов/сек |
| Запрос устройства (GET) | Без ограничений |
| WebSocket push | Без ограничений (push от сервера) |
| Пакетные операции | 20 пакетов/сек |
💡 Лучшая практика: используйте WebSocket для получения данных в реальном времени и отправляйте управляющие команды через REST только при необходимости — избегайте частого опроса (polling).
REST API’ye Genel Bakış
Skydimo, harici uygulamaların tüm RGB cihazlarını kontrol etmesine olanak tanıyan eksiksiz bir REST API sağlar.
Temel URL: http://localhost:9527/api/v1
Kimlik Doğrulama: API Token (Ayarlar’da üretin)
İçerik Türü: application/json
API’yi Etkinleştirme
Ayarlar → Geliştirici → REST API'yi etkinleştir
Port: 9527 (yapılandırılabilir)
API Token oluştur → kopyalayın ve kaydedin
API Endpoint Referansı
Tüm Cihazları Al
GET /api/v1/devices
Authorization: Bearer YOUR_TOKEN
Yanıt örneği:
{
"devices": [
{
"id": "usb:1234:5678",
"name": "Corsair K70 RGB",
"type": "keyboard",
"leds": 110,
"vendor": "Corsair",
"connected": true
},
{
"id": "smbus:1",
"name": "Anakart ARGB Denetleyici",
"type": "motherboard",
"leds": 60,
"vendor": "Gigabyte",
"connected": true
}
]
}
Cihaz Rengi Ayarla
PUT /api/v1/devices/{device_id}/color
Authorization: Bearer YOUR_TOKEN
Content-Type: application/json
{
"mode": "static",
"color": {"r": 255, "g": 0, "b": 128}
}
Tek Tek LED Ayarla
PUT /api/v1/devices/{device_id}/leds
Authorization: Bearer YOUR_TOKEN
{
"leds": [
{"index": 0, "r": 255, "g": 0, "b": 0},
{"index": 1, "r": 0, "g": 255, "b": 0},
{"index": 2, "r": 0, "g": 0, "b": 255}
]
}
Profil Uygula
POST /api/v1/profiles/{profile_id}/apply
Authorization: Bearer YOUR_TOKEN
Müzik Senkronizasyonu Kontrolü
POST /api/v1/music-sync/start
POST /api/v1/music-sync/stop
GET /api/v1/music-sync/status
# Yanıt: {"active": true, "mode": "ai", "latency_ms": 18}
WebSocket Gerçek Zamanlı Push
Skydimo, cihaz durumu ve ses verilerini gerçek zamanlı olarak almak için WebSocket bağlantılarını destekler:
const ws = new WebSocket('ws://localhost:9527/ws');
ws.onopen = () => {
// Ses spektrum verilerine abone ol
ws.send(JSON.stringify({
type: 'subscribe',
topics: ['spectrum', 'device_state']
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'spectrum') {
// Gerçek zamanlı spektrum verisi
const { bass, mid, high, raw } = data.payload;
// raw: Float32Array, 257 frekans bileşeni için enerji değerleri
updateVisualization(raw);
}
if (data.type === 'device_state') {
// Cihaz durumu değişikliği
console.log('Device updated:', data.payload);
}
};
Spektrum Veri Formatı
interface SpectrumMessage {
type: 'spectrum';
timestamp: number;
payload: {
bass: number; // 0-1, düşük frekans enerjisi
mid: number; // 0-1, orta frekans enerjisi
high: number; // 0-1, yüksek frekans enerjisi
bpm: number; // şu anda algılanan BPM
is_beat: boolean; // mevcut karenin bir ritim noktası olup olmadığı
raw: number[]; // 257 frekans bileşeni
};
}
Eklenti Geliştirmenin Temelleri
Python Örneği: Müzik Görselleştirme Eklentisi
import requests
import websocket
import json
import colorsys
import threading
BASE_URL = "http://localhost:9527/api/v1"
TOKEN = "your_api_token_here"
headers = {"Authorization": f"Bearer {TOKEN}"}
def get_devices():
resp = requests.get(f"{BASE_URL}/devices", headers=headers)
return resp.json()["devices"]
def set_all_devices_color(r, g, b):
devices = get_devices()
for device in devices:
requests.put(
f"{BASE_URL}/devices/{device['id']}/color",
headers=headers,
json={"mode": "static", "color": {"r": r, "g": g, "b": b}}
)
def on_spectrum(ws, message):
data = json.loads(message)
if data["type"] != "spectrum":
return
payload = data["payload"]
bass = payload["bass"]
high = payload["high"]
# Spektrumu renge eşle
# Bas → ton (düşük frekans = mor, yüksek frekans = turkuaz)
hue = 0.75 - bass * 0.5 # 0.75=mor, 0.5=mavi
saturation = 1.0
value = 0.3 + bass * 0.7 # parlaklık basa yanıt verir
r, g, b = colorsys.hsv_to_rgb(hue, saturation, value)
set_all_devices_color(int(r*255), int(g*255), int(b*255))
def on_open(ws):
ws.send(json.dumps({
"type": "subscribe",
"topics": ["spectrum"]
}))
print("Skydimo'ya bağlandı, müzik senkronizasyonu başlıyor...")
ws = websocket.WebSocketApp(
"ws://localhost:9527/ws",
on_message=on_spectrum,
on_open=on_open
)
ws.run_forever()
JavaScript/Node.js Örneği
const WebSocket = require('ws');
const fetch = require('node-fetch');
const BASE_URL = 'http://localhost:9527/api/v1';
const TOKEN = 'your_token';
async function setDeviceColor(deviceId, r, g, b) {
await fetch(`${BASE_URL}/devices/${deviceId}/color`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ mode: 'static', color: { r, g, b } }),
});
}
const ws = new WebSocket('ws://localhost:9527/ws');
ws.on('open', () => {
ws.send(JSON.stringify({ type: 'subscribe', topics: ['spectrum'] }));
});
ws.on('message', async (raw) => {
const msg = JSON.parse(raw);
if (msg.type !== 'spectrum') return;
const { bass, mid, high } = msg.payload;
// Basit eşleme: bas → kırmızı, orta → yeşil, yüksek → mavi
const r = Math.round(bass * 255);
const g = Math.round(mid * 255);
const b = Math.round(high * 255);
// Tüm cihazları al ve güncelle (üretimde cihaz listesini önbelleğe alın)
const resp = await fetch(`${BASE_URL}/devices`, {
headers: { 'Authorization': `Bearer ${TOKEN}` }
});
const { devices } = await resp.json();
for (const device of devices) {
await setDeviceColor(device.id, r, g, b);
}
});
Eklenti Yayınlama
Geliştirme tamamlandıktan sonra eklentinizi Skydimo Eklenti Pazaryerine gönderin:
plugin.jsonmanifest dosyası hazırlayın:
{
"name": "Müzik Eklentim",
"version": "1.0.0",
"description": "Özel müzik görselleştirme efekti",
"author": "Adınız",
"license": "MIT",
"entry": "main.py",
"requirements": ["requests", "websocket-client"]
}
- Kodunuzu GitHub’a yükleyin
- Skydimo Eklenti Pazaryerine gönderin: plugins.skydimo.com
API Hız Sınırları
| Endpoint Türü | Sınır |
|---|---|
| Cihaz kontrolü (PUT/POST) | 100 istek/saniye |
| Cihaz sorgusu (GET) | Sınırsız |
| WebSocket push | Sınırsız (sunucu tarafı push) |
| Toplu işlemler | 20 toplu işlem/saniye |
💡 En iyi uygulama: Gerçek zamanlı veri almak için WebSocket kullanın ve yalnızca gerektiğinde REST aracılığıyla kontrol komutları gönderin — sık sık yoklama (polling) yapmaktan kaçının.