Seeed-Solution/reterminal_skill / skill
reterminal-skill
VerifiedUse when creating, uploading, sending, deleting, or managing SenseCraft HMI playlists and pages through the HMI API.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 3.1 KB |
| references/api.md | markdown | 2.5 KB |
| scripts/reterminal-skill.mjsexecutable | script | 15.3 KB |
scripts/reterminal-skill.mjs
View on GitHub#!/usr/bin/env node
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const JSON_HEADERS = { 'Content-Type': 'application/json' };
export async function runCommand({ argv = process.argv.slice(2), env = process.env, fetch = globalThis.fetch } = {}) {
const [command, ...rest] = argv;
const options = parseArgs(rest);
const client = new HmiClient({ env, fetch });
switch (command) {
case 'list-devices':
return client.listDevices();
case 'create-playlist':
return client.createPlaylist({
name: requireOption(options, 'name'),
macAddress: options.macAddress,
});
case 'upload-image-base64':
return client.uploadImageBase64({
imageBase64: requireOption(options, 'imageBase64'),
filename: options.filename,
macAddress: options.macAddress,
});
case 'upload-file':
return client.uploadFile({
file: requireOption(options, 'file'),
filename: options.filename,
macAddress: options.macAddress,
});
case 'create-image-page':
return client.createImagePage({
name: requireOption(options, 'name'),
imageUrl: requireOption(options, 'imageUrl'),
macAddress: options.macAddress,
});
case 'upsert-pages':
return client.upsertPages({
playlistId: requireNumericOption(options, 'playlistId'),
pageId: requireNumericOption(options, 'pageId'),
sort: Number(options.sort ?? 0),
});
case 'send-playlist':
return client.sendPlaylist({
playlistId: requireNumericOption(options, 'playlistId'),
macAddress: options.macAddress,
deviceId: options.deviceId,
deviceName: options.deviceName,
});
case 'set-refresh-interval':
return client.setRefreshInterval({
seconds: options.seconds,
minutes: options.minutes,
macAddress: options.macAddress,
deviceId: options.deviceId,
deviceName: options.deviceName,
});
case 'delete-playlist':
return client.deletePlaylist({
playlistId: requireNumericOption(options, 'playlistId'),
macAddress: options.macAddress,
deviceId: options.deviceId,
deviceName: options.deviceName,
});
case 'delete-page':
return client.deletePage({
pageId: requireNumericOption(options, 'pageId'),
macAddress: options.macAddress,
deviceId: options.deviceId,
deviceName: options.deviceName,
});
case 'create-upload-send':
return client.createUploadSend({
name: requireOption(options, 'name'),
imageBase64: options.imageBase64,
file: options.file,
filename: options.filename,
pageName: options.pageName,
macAddress: options.macAddress,
deviceId: options.deviceId,
deviceName: options.deviceName,
});
case '--help':
case '-h':
case undefined:
return { usage: usage() };
default:
throw new Error(`Unknown command: ${command}`);
}
}
class HmiClient {
constructor({ env, fetch }) {
if (!fetch) {
throw new Error('fetch is not available. Use Node.js 20+ or provide a fetch implementation.');
}
this.fetch = fetch;
this.base = requireEnv(env, 'HMI_API_BASE').replace(/\/+$/, '');
this.apiKey = requireEnv(env, 'HMI_API_KEY');
this.defaultMac = env.HMI_DEVICE_MAC;
this.envDeviceId = env.HMI_DEVICE_ID;
this.envDeviceName = env.HMI_DEVICE_NAME;
}
async listDevices() {
const response = await this.request('GET', '/api/v2/user/device/list');
return { devices: normalizeDevices(response.result) };
}
async createPlaylist({ name, macAddress }) {
const body = withMac({ name }, this.mac(macAddress));
const response = await this.request('POST', '/api/v2/user/playlist', body);
return { playlist_id: pickId(response.result, ['id', 'playlist_id']) };
}
async uploadImageBase64({ imageBase64, filename }) {
const body = { image_data: imageBase64 };
if (filename) {
body.file_name = filename;
}
const response = await this.request('POST', '/api/v1/oss/upload', body);
return { image_url: pickUrl(response.result) };
}
async uploadFile({ file, filename, macAddress }) {
const buffer = await readFile(file);
const form = new FormData();
const name = filename || path.basename(file);
form.set('file', new Blob([buffer]), name);
if (name) form.set('filename', name);
const mac = this.mac(macAddress);
if (mac) form.set('mac_address', mac);
const response = await this.request('POST', '/api/v1/oss/file/upload', form);
return { image_url: pickUrl(response.result) };
}
async createImagePage({ name, imageUrl, macAddress }) {
const body = withMac(
{
pages: [
{
type: 'img',
name,
data: imageUrl,
dither: 0,
thumbnail: imageUrl,
},
],
},
this.mac(macAddress),
);
const response = await this.request('POST', '/api/v2/user/page', body);
return { page_id: pickId(response.result, ['ids.0', 'id', 'page_id']) };
}
async upsertPages({ playlistId, pageId, sort = 0 }) {
const response = await this.request('POST', '/api/v2/user/playlist/upsert_pages', {
playlist_id: playlistId,
pages: [{ id: pageId, sort }],
});
return { result: response.result ?? true };
}
async sendPlaylist({ playlistId, macAddress, deviceId, deviceName }) {
const mac = await this.requireMac({ macAddress, deviceId, deviceName });
const response = await this.request('POST', '/api/v2/user/device/down_link', {
mac_address: mac,
type: 1,
playlist_id: playlistId,
});
return { mac_address: mac, downlink: response.result ?? true };
}
async setRefreshInterval({ seconds, minutes, macAddress, deviceId, deviceName }) {
const refreshInterval = parseRefreshInterval({ seconds, minutes });
const mac = await this.requireMac({ macAddress, deviceId, deviceName });
const response = await this.request('POST', '/api/v2/user/device/down_link', {
mac_address: mac,
type: 2,
refresh_interval: refreshInterval,
});
return {
mac_address: mac,
refresh_interval: refreshInterval,
downlink: response.result ?? true,
};
}
async deletePlaylist({ playlistId, macAddress, deviceId, deviceName }) {
assertPositiveInteger(playlistId, 'playlist-id');
const mac = await this.requireMac({ macAddress, deviceId, deviceName });
const response = await this.request('DELETE', '/api/v2/user/playlist', {
id: playlistId,
mac_address: mac,
});
return { deleted_playlist_id: playlistId, mac_address: mac, result: response.result ?? true };
}
async deletePage({ pageId, macAddress, deviceId, deviceName }) {
assertPositiveInteger(pageId, 'page-id');
const mac = await this.requireMac({ macAddress, deviceId, deviceName });
const response = await this.request('DELETE', '/api/v2/user/page', {
id: pageId,
mac_address: mac,
});
return { deleted_page_id: pageId, mac_address: mac, result: response.result ?? true };
}
async createUploadSend({ name, imageBase64, file, filename, pageName, macAddress, deviceId, deviceName }) {
if (!imageBase64 && !file) {
throw new Error('Missing required option: --image-base64 or --file');
}
const resolvedMac = await this.requireMac({ macAddress, deviceId, deviceName });
const created = { mac_address: resolvedMac };
const playlist = await this.createPlaylist({ name, macAddress: resolvedMac });
created.playlist_id = playlist.playlist_id;
const upload = imageBase64
? await this.uploadImageBase64({ imageBase64, filename, macAddress: resolvedMac })
: await this.uploadFile({ file, filename, macAddress: resolvedMac });
created.image_url = upload.image_url;
const page = await this.createImagePage({
name: pageName || filename || name,
imageUrl: upload.image_url,
macAddress: resolvedMac,
});
created.page_id = page.page_id;
await this.upsertPages({ playlistId: playlist.playlist_id, pageId: page.page_id, sort: 0 });
try {
const sent = await this.sendPlaylist({ playlistId: playlist.playlist_id, macAddress: resolvedMac });
return { ...created, ...sent };
} catch (error) {
error.partial = { ...created };
throw error;
}
}
mac(macAddress) {
return macAddress || this.defaultMac;
}
async requireMac({ macAddress, deviceId, deviceName } = {}) {
const mac = this.mac(macAddress);
if (!mac) {
return this.resolveDeviceMac({
deviceId: deviceId || this.envDeviceId,
deviceName: deviceName || this.envDeviceName,
});
}
return mac;
}
async resolveDeviceMac({ deviceId, deviceName } = {}) {
const { devices } = await this.listDevices();
const selectedDevice = selectDevice(devices, { deviceId, deviceName });
return selectedDevice.mac_address;
}
async request(method, endpoint, body) {
const headers = { 'api-key': this.apiKey };
const init = { method, headers };
if (body instanceof FormData) {
init.body = body;
} else if (body !== undefined) {
Object.assign(headers, JSON_HEADERS);
init.body = JSON.stringify(body);
}
const httpResponse = await this.fetch(`${this.base}${endpoint}`, init);
const payload = await readJsonResponse(httpResponse);
if (!httpResponse.ok || (payload && payload.code !== undefined && !isSuccessCode(payload.code))) {
throw apiError(payload, httpResponse.status);
}
return payload ?? {};
}
}
function parseArgs(argv) {
const options = {};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (!arg.startsWith('--')) {
throw new Error(`Unexpected argument: ${arg}`);
}
const key = toCamel(arg.slice(2));
const value = argv[index + 1];
if (!value || value.startsWith('--')) {
throw new Error(`Missing value for ${arg}`);
}
options[key] = value;
index += 1;
}
return options;
}
function toCamel(value) {
return value.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
}
function requireOption(options, name) {
const value = options[name];
if (!value) {
throw new Error(`Missing required option: --${name.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)}`);
}
return value;
}
function requireNumericOption(options, name) {
const value = Number(requireOption(options, name));
assertPositiveInteger(value, name);
return value;
}
function parseRefreshInterval({ seconds, minutes }) {
if (seconds && minutes) {
throw new Error('Use only one of --seconds or --minutes');
}
if (minutes) {
const value = Number(minutes);
assertPositiveInteger(value, 'minutes');
return value * 60;
}
if (seconds) {
const value = Number(seconds);
assertPositiveInteger(value, 'seconds');
return value;
}
throw new Error('Missing required option: --seconds or --minutes');
}
function assertPositiveInteger(value, label) {
if (!Number.isInteger(value) || value <= 0) {
throw new Error(`${label} must be a positive integer`);
}
}
function requireEnv(env, name) {
const value = env[name];
if (!value) {
throw new Error(`Missing required environment variable: ${name}`);
}
return value;
}
function withMac(body, macAddress) {
return macAddress ? { ...body, mac_address: macAddress } : body;
}
function normalizeDevices(result) {
const source = Array.isArray(result) ? result : result?.list || result?.devices || result?.items || [];
return source.map((device) => ({
id: device.id,
name: device.device_name || device.name,
mac_address: device.mac_address || device.macAddress,
online_status: device.online_status,
}));
}
function selectDevice(devices, { deviceId, deviceName } = {}) {
const usableDevices = devices.filter((device) => device.mac_address);
if (usableDevices.length === 0) {
throw new Error('No HMI devices with mac_address were found for this API key.');
}
if (deviceId) {
const selected = usableDevices.find((device) => String(device.id) === String(deviceId));
if (!selected) {
const error = new Error(`No HMI device found for device id: ${deviceId}`);
error.devices = usableDevices;
throw error;
}
return selected;
}
if (deviceName) {
const matches = usableDevices.filter((device) => device.name === deviceName);
if (matches.length === 1) {
return matches[0];
}
const error =
matches.length === 0
? new Error(`No HMI device found for device name: ${deviceName}`)
: new Error(`Multiple HMI devices found for device name: ${deviceName}. Use --device-id or --mac-address.`);
error.devices = usableDevices;
throw error;
}
if (usableDevices.length === 1) {
return usableDevices[0];
}
const error = new Error('Multiple devices found. Use --device-id, --device-name, --mac-address, HMI_DEVICE_ID, HMI_DEVICE_NAME, or HMI_DEVICE_MAC.');
error.devices = usableDevices;
throw error;
}
function pickId(result, fields) {
for (const field of fields) {
const value = getPath(result, field);
if (value !== undefined && value !== null) {
return value;
}
}
throw new Error(`API response did not include an expected ID field: ${fields.join(', ')}`);
}
function pickUrl(result) {
const value = pickFirst(result, [
'url',
'image_url',
'file_url',
'path',
'object_url',
'data.url',
'data.image_url',
'data.file_url',
]);
if (!value) {
throw new Error('API response did not include an uploaded file URL');
}
return value;
}
function pickFirst(source, fields) {
for (const field of fields) {
const value = getPath(source, field);
if (value !== undefined && value !== null && value !== '') {
return value;
}
}
return undefined;
}
function getPath(source, field) {
return field.split('.').reduce((current, part) => {
if (current === undefined || current === null) return undefined;
return current[part];
}, source);
}
async function readJsonResponse(response) {
try {
return await response.json();
} catch {
const text = await response.text();
return text ? { message: text } : {};
}
}
function apiError(payload, status) {
const code = payload?.code ?? status;
const message = payload?.message || payload?.msg || `HMI API request failed with code ${code}`;
const error = new Error(message);
error.code = code;
error.response = payload;
return error;
}
function isSuccessCode(code) {
return code === 0 || code === 200;
}
function usage() {
return {
commands: [
'create-playlist',
'list-devices',
'upload-image-base64',
'upload-file',
'create-image-page',
'upsert-pages',
'send-playlist',
'set-refresh-interval',
'delete-playlist',
'delete-page',
'create-upload-send',
],
};
}
if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
runCommand()
.then((result) => {
console.log(JSON.stringify(result, null, 2));
})
.catch((error) => {
const output = {
error: error.message,
code: error.code,
partial: error.partial,
devices: error.devices,
};
console.error(JSON.stringify(output, null, 2));
process.exitCode = 1;
});
}
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |