fix(relays): {value} is the relay's label, not a per-relay value
It was built the other way round on a misreading of two screenshots: the pattern
held {value} and the per-relay boxes held numbers to drop into it. The ask was
simpler and better — {value} is the name typed in Relay labels, so a switch
addressed by antenna name is one pattern instead of eight URLs:
http://10.10.10.100/relay?on={value} relay 1 named Ant1 → ?on=Ant1
Renaming the antenna re-addresses it, and the name on the button and the name on
the wire cannot drift apart because they are the same string. It works in the
per-relay URLs and in the patterns alike, so the per-relay boxes go back to
holding URLs and nothing about them changes meaning any more.
The label is percent-encoded with %20 rather than "+" for a space: "+" is a
space only in a query string and a literal plus in a path, and this can land in
either half of a URL.
{value} on a relay with no label would send "?on=", an empty parameter that most
boards answer with a cheerful 200 and no movement. The driver refuses it and
names the label as what is missing; the editor warns while it is being typed,
beside the empty box rather than after an antenna fails to switch. The labels
also join the driver's cache key — they are part of the wire format now.
This commit is contained in:
@@ -14763,7 +14763,7 @@ func buildDeviceDriver(d StationDevice) relaydev.Device {
|
||||
// generic board fall through to the WebSwitch driver below: it answered
|
||||
// the WebSwitch's own address, never sent one configured URL, and
|
||||
// reported itself offline so every relay button stayed greyed out.
|
||||
return relaydev.NewHTTPGeneric(d.OnURLs, d.OffURLs, d.OnPat, d.OffPat, d.User, d.Pass, deviceRelayCount(d))
|
||||
return relaydev.NewHTTPGeneric(d.OnURLs, d.OffURLs, d.OnPat, d.OffPat, d.User, d.Pass, deviceRelayCount(d), d.Labels)
|
||||
default:
|
||||
return relaydev.NewWebswitch(d.Host)
|
||||
}
|
||||
@@ -14779,7 +14779,11 @@ func deviceKey(d StationDevice) string {
|
||||
// handed back the cached driver still holding the wrong address, so the
|
||||
// fix appeared to do nothing until OpsLog was restarted.
|
||||
k += "|" + d.OnPat + "|" + d.OffPat +
|
||||
"|" + strings.Join(d.OnURLs, "\x1f") + "|" + strings.Join(d.OffURLs, "\x1f")
|
||||
"|" + strings.Join(d.OnURLs, "\x1f") + "|" + strings.Join(d.OffURLs, "\x1f") +
|
||||
// The labels are part of the wire format here: {value} sends them.
|
||||
// Renaming a relay re-addresses it, and the cached driver would keep
|
||||
// commanding the old name.
|
||||
"|" + strings.Join(d.Labels, "\x1f")
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
+2
-2
@@ -6,13 +6,13 @@
|
||||
"WinKeyer: the opening probe goes out as one write, matching a capture of a client that talks to the same K3NG keyer, and the handshake bytes are always logged so a keyer that stays silent can be diagnosed.",
|
||||
"DX cluster: when spots arrive and every one is filtered out, the panel says so, names the filters doing it and offers to clear them — it used to say “waiting for spots” beside a counter reading 76 live.",
|
||||
"DX cluster: the log times the connection and the first spot, so a slow first launch can be told apart from a quiet node.",
|
||||
"Generic HTTP relay: its URLs were never actually sent — fixed. Adds {value} and {relay-1}, https, and no host or test needed."
|
||||
"Generic HTTP relay: its URLs were never actually sent — fixed. {value} sends the relay's label, {relay-1} counts from zero, no host needed."
|
||||
],
|
||||
"fr": [
|
||||
"WinKeyer : la sonde d’ouverture part en un seul envoi, calquée sur la capture d’un client qui dialogue avec le même manipulateur K3NG, et les octets de la poignée de main sont toujours journalisés pour diagnostiquer un manipulateur muet.",
|
||||
"Cluster DX : quand des spots arrivent et que tout est filtré, le panneau le dit, nomme les filtres responsables et propose de les effacer — il affichait « en attente de spots » à côté d’un compteur à 76 en direct.",
|
||||
"Cluster DX : le journal chronomètre la connexion et le premier spot, pour distinguer un premier lancement lent d’un nœud silencieux.",
|
||||
"Relais HTTP générique : ses URL n’étaient jamais envoyées — corrigé. Ajoute {value} et {relay-1}, https, sans hôte ni test."
|
||||
"Relais HTTP générique : ses URL n’étaient jamais envoyées — corrigé. {value} envoie le libellé du relais, {relay-1} compte de zéro, hôte inutile."
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -696,11 +696,13 @@ function DeviceEditor({ device, onChange, onSave, onCancel, t }: {
|
||||
const isDenkovi = device.type === 'denkovi';
|
||||
const isUsbRelay = device.type === 'usbrelay';
|
||||
const isHTTPGen = device.type === 'httpgen';
|
||||
// {value} in a pattern changes what the boxes below hold — a value to drop
|
||||
// into it instead of a whole URL. The grid says which as soon as it is typed,
|
||||
// because the two are indistinguishable once entered and getting it wrong
|
||||
// switches an antenna somewhere unexpected.
|
||||
const usesValue = `${device.on_pattern ?? ''}${device.off_pattern ?? ''}`.includes('{value}');
|
||||
// {value} sends a relay's label, so a URL using it on an unnamed relay would
|
||||
// go out with an empty parameter. Warn while it is being typed rather than at
|
||||
// the moment an antenna fails to switch.
|
||||
const valueNeedsLabels = isHTTPGen
|
||||
&& [...(device.on_urls ?? []), ...(device.off_urls ?? []), device.on_pattern ?? '', device.off_pattern ?? '']
|
||||
.some((s) => (s ?? '').includes('{value}'))
|
||||
&& device.labels.some((l) => !l.trim());
|
||||
// COM ports for the generic USB-serial relay picker.
|
||||
const [serialPorts, setSerialPorts] = useState<string[]>([]);
|
||||
useEffect(() => {
|
||||
@@ -874,12 +876,12 @@ function DeviceEditor({ device, onChange, onSave, onCancel, t }: {
|
||||
</div>
|
||||
<div className="text-[10px] text-muted-foreground">{t('station.patternHint')}</div>
|
||||
<div className="space-y-1">
|
||||
<Label>{usesValue ? t('station.perRelayValues') : t('station.perRelayUrls')}</Label>
|
||||
<Label>{t('station.perRelayUrls')}</Label>
|
||||
<div className="space-y-1">
|
||||
{device.labels.map((_, i) => (
|
||||
<div key={i} className="grid grid-cols-[2.5rem_1fr_1fr] items-center gap-2">
|
||||
<span className="text-[11px] text-muted-foreground">{i + 1}</span>
|
||||
<Input className="h-8 font-mono text-[11px]" placeholder={usesValue ? t('station.onValuePh') : t('station.onUrlPh')}
|
||||
<Input className="h-8 font-mono text-[11px]" placeholder={t('station.onUrlPh')}
|
||||
value={device.on_urls?.[i] ?? ''}
|
||||
onChange={(e) => {
|
||||
const on_urls = [...(device.on_urls ?? [])];
|
||||
@@ -887,7 +889,7 @@ function DeviceEditor({ device, onChange, onSave, onCancel, t }: {
|
||||
on_urls[i] = e.target.value;
|
||||
onChange({ ...device, on_urls });
|
||||
}} />
|
||||
<Input className="h-8 font-mono text-[11px]" placeholder={usesValue ? t('station.offValuePh') : t('station.offUrlPh')}
|
||||
<Input className="h-8 font-mono text-[11px]" placeholder={t('station.offUrlPh')}
|
||||
value={device.off_urls?.[i] ?? ''}
|
||||
onChange={(e) => {
|
||||
const off_urls = [...(device.off_urls ?? [])];
|
||||
@@ -898,13 +900,17 @@ function DeviceEditor({ device, onChange, onSave, onCancel, t }: {
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="text-[10px] text-muted-foreground">{usesValue ? t('station.perValueHint') : t('station.perRelayHint')}</div>
|
||||
<div className="text-[10px] text-muted-foreground">{t('station.perRelayHint')}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label>{t('station.labels')}</Label>
|
||||
{/* {value} sends the label, so an unnamed relay would go out as "?on=".
|
||||
Said here, beside the empty box, rather than when the antenna fails
|
||||
to switch and the log is the only place that explains why. */}
|
||||
{valueNeedsLabels && <p className="text-[10px] text-warning">{t('station.valueNeedsLabels')}</p>}
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{device.labels.map((lab, i) => (
|
||||
<Input key={i} value={lab} placeholder={`${t('station.relay')} ${i + 1}`} className="h-8 text-xs"
|
||||
|
||||
@@ -156,8 +156,8 @@ const en: Dict = {
|
||||
'uscty.backfillIntro': 'Resolve county (and grid) for US QSOs already in your log that are missing them. Existing values are kept — only blanks are filled.',
|
||||
'uscty.backfillRun': 'Fill missing counties',
|
||||
'uscty.backfillDone': '{s} US QSOs scanned · {c} counties, {g} grids filled.',
|
||||
'station.typeHttpGen': 'HTTP relay (home-made / generic)', 'station.onPattern': 'ON URL pattern', 'station.offPattern': 'OFF URL pattern', 'station.patternHint': 'Optional, http or https. {relay} is replaced by the relay number — {relay-1} if the board counts from zero. Put {value} where the boards differ only by a number, and type that number per relay below. Leave both blank if every relay has its own full URL.', 'station.perRelayUrls': 'Per-relay URLs (optional)', 'station.perRelayHint': 'Filled in here, these win over the patterns — for a switch whose channels have nothing in common. State is remembered, not read back: after a restart every relay is re-commanded once.', 'station.onUrlPh': 'ON URL', 'station.offUrlPh': 'OFF URL',
|
||||
'station.perRelayValues': 'Per-relay values (for {value})', 'station.perValueHint': 'The pattern above contains {value}: these are the values dropped into it, not URLs — e.g. 1, 2, 4, 8 to switch on and 0 to switch off. State is remembered, not read back: after a restart every relay is re-commanded once.', 'station.onValuePh': 'ON value', 'station.offValuePh': 'OFF value',
|
||||
'station.typeHttpGen': 'HTTP relay (home-made / generic)', 'station.onPattern': 'ON URL pattern', 'station.offPattern': 'OFF URL pattern', 'station.patternHint': 'Optional, http or https. {relay} is the relay number — {relay-1} if the board counts from zero. {value} is that relay\'s label below, so …/relay?on={value} with relay 1 named Ant1 sends …/relay?on=Ant1. Leave both blank if every relay has its own full URL.', 'station.perRelayUrls': 'Per-relay URLs (optional)', 'station.perRelayHint': 'Filled in here, these win over the patterns — for a switch whose channels have nothing in common. {relay} and {value} work here too. State is remembered, not read back: after a restart every relay is re-commanded once.', 'station.onUrlPh': 'ON URL', 'station.offUrlPh': 'OFF URL',
|
||||
'station.valueNeedsLabels': 'A URL above uses {value}, which sends the relay’s label — name every relay you switch that way, or its URL goes out with an empty value.',
|
||||
'station.title': 'Station Control', 'station.rotator': 'Rotator', 'station.rotateTo': 'Rotate to {az}°', 'station.rotatorNoRead': 'No heading read', 'station.bands': 'Bands', 'station.nudgeUp': 'Up {n} kHz', 'station.nudgeDown': 'Down {n} kHz', 'station.trackOn': 'Tracking on', 'station.trackOff': 'Tracking off', 'station.trackStepTip': 'Re-tune only when the rig has moved this far', 'station.trackModeTip': 'When the antenna is allowed to re-tune', 'station.trackAlways': 'Every frequency change', 'station.trackStep': 'Past a step', 'station.trackBand': 'Band change only', 'station.trackAlwaysTip': 'Follow every frequency change. Best resonance, but the motors run constantly — and on a SteppIR every move blocks transmit while the elements travel.', 'station.trackStepTipMode': 'Re-tune only once the rig has moved further than the step. Follows a QSY, ignores tuning around.', 'station.trackBandTip': 'Re-tune only when the band changes. The motors move a few times a day and are left alone within a band.', 'station.pattern': 'Pattern', 'station.bi': 'Bi', 'station.retract': 'Retract elements', 'station.moving': 'MOVING', 'station.elements': 'Elements (mm)', 'station.read': 'Read', 'station.readLengths': 'Read current element lengths from the controller', 'station.noLengths': 'Lengths unknown — click Read to fetch them from the controller.', 'station.element': 'Element', 'station.reflector': 'Reflector', 'station.driven': 'Driven', 'station.director': 'Dir', 'station.set': 'Set', 'station.elementsHint': 'Each press lengthens/shortens the element by 2 mm (like the physical console). Verify which element responds on your antenna.', 'station.setExactLen': 'Click to type the exact current length (fixes the baseline if the auto-read is off).', 'station.atMax': 'Controller refused — the element is likely at its maximum length for this band, so it can\'t extend further.', 'station.go': 'Go', 'station.stop': 'Stop', 'station.dragHint': 'Drag the grip handle on the left of a panel to move it. Pick a column count to lay them out in a grid.', 'station.dragMove': 'Drag to move this panel', 'station.colsAuto': 'Auto', 'station.addDevice': 'Add device', 'station.editDevice': 'Edit device', 'station.empty': 'No relay boards yet. Add a WebSwitch 1216H or a KMTronic 8-relay board to control your station power and accessories.', 'station.online': 'Online', 'station.offline': 'Offline', 'station.edit': 'Edit', 'station.delete': 'Delete', 'station.relay': 'Relay', 'station.on': 'ON', 'station.off': 'OFF', 'station.type': 'Device type', 'station.name': 'Name', 'station.host': 'Host / IP', 'station.hostHint': 'LAN IP for local use. To reach the board from OUTSIDE, put a full URL here — e.g. https://relay.yourdomain.com — pointing at a reverse proxy (Nginx Proxy Manager…) that fronts the board’s HTTP port.', 'station.user': 'Username', 'station.pass': 'Password', 'station.optional': 'optional', 'station.ftdiSerial': 'FTDI serial number', 'station.detect': 'Detect', 'station.ftdiHint': 'The Denkovi board is driven via FTDI bit-bang (not the COM port). Pick its serial (e.g. DAE0006K). Needs the FTDI D2XX driver installed.', 'station.channels': 'Relays', 'station.comPort': 'COM port', 'station.noPorts': 'No ports found', 'station.usbRelayHint': 'Cheap USB-serial relay boards (CH340/LCUS) using the A0 command protocol. If yours does not switch, tell me its model / command set.', 'station.labels': 'Relay labels', 'station.cancel': 'Cancel', 'station.save': 'Save', 'station.test': 'Test connection', 'station.testOk': 'Connected — {n} relays', 'station.testFail': 'Not connected', 'station.detectNone': 'No FTDI board found — check the cable and that the D2XX driver is installed.', 'station.detectFound': '{n} board(s) detected.',
|
||||
'awards.followHint': 'Awards shown in the Awards tab. Leave the right side empty to show them all.', 'awards.available': 'All awards', 'awards.followed': 'Followed', 'awards.search': 'Filter…', 'awards.addAll': 'Add all', 'awards.clear': 'Clear', 'awards.allTracked': 'All awards are followed.', 'awards.noneFollowed': 'Nothing followed yet — the Awards tab shows all.',
|
||||
'sec.awards': 'Awards', 'sec.cat': 'CAT interface', 'sec.rotator': 'Rotator', 'sec.winkeyer': 'CW Keyer',
|
||||
@@ -591,8 +591,8 @@ const fr: Dict = {
|
||||
'uscty.backfillIntro': "Résout le comté (et le locator) pour les QSO US déjà dans ton log qui n'en ont pas. Les valeurs existantes sont conservées — seuls les vides sont remplis.",
|
||||
'uscty.backfillRun': 'Remplir les comtés manquants',
|
||||
'uscty.backfillDone': '{s} QSO US analysés · {c} comtés, {g} locators remplis.',
|
||||
'station.typeHttpGen': 'Relais HTTP (fait main / générique)', 'station.onPattern': 'Modèle d’URL ON', 'station.offPattern': 'Modèle d’URL OFF', 'station.patternHint': 'Optionnel, http ou https. {relay} est remplacé par le numéro du relais — {relay-1} si la carte compte à partir de zéro. Mets {value} là où les URL ne diffèrent que par un nombre, et saisis ce nombre par relais ci-dessous. Laisse les deux vides si chaque relais a sa propre URL complète.', 'station.perRelayUrls': 'URL par relais (optionnel)', 'station.perRelayHint': 'Renseignées ici, elles l’emportent sur les modèles — pour un commutateur dont les voies n’ont rien en commun. L’état est mémorisé, pas relu : après un redémarrage chaque relais est recommandé une fois.', 'station.onUrlPh': 'URL ON', 'station.offUrlPh': 'URL OFF',
|
||||
'station.perRelayValues': 'Valeurs par relais (pour {value})', 'station.perValueHint': 'Le modèle ci-dessus contient {value} : ce sont les valeurs qui y seront insérées, pas des URL — ex. 1, 2, 4, 8 pour activer et 0 pour couper. L’état est mémorisé, pas relu : après un redémarrage chaque relais est recommandé une fois.', 'station.onValuePh': 'Valeur ON', 'station.offValuePh': 'Valeur OFF',
|
||||
'station.typeHttpGen': 'Relais HTTP (fait main / générique)', 'station.onPattern': 'Modèle d’URL ON', 'station.offPattern': 'Modèle d’URL OFF', 'station.patternHint': 'Optionnel, http ou https. {relay} est le numéro du relais — {relay-1} si la carte compte à partir de zéro. {value} est le libellé de ce relais ci-dessous : …/relay?on={value} avec le relais 1 nommé Ant1 envoie …/relay?on=Ant1. Laisse les deux vides si chaque relais a sa propre URL complète.', 'station.perRelayUrls': 'URL par relais (optionnel)', 'station.perRelayHint': 'Renseignées ici, elles l’emportent sur les modèles — pour un commutateur dont les voies n’ont rien en commun. {relay} et {value} fonctionnent aussi ici. L’état est mémorisé, pas relu : après un redémarrage chaque relais est recommandé une fois.', 'station.onUrlPh': 'URL ON', 'station.offUrlPh': 'URL OFF',
|
||||
'station.valueNeedsLabels': 'Une URL ci-dessus utilise {value}, qui envoie le libellé du relais — nomme chaque relais commuté ainsi, sinon son URL part avec une valeur vide.',
|
||||
'station.title': 'Contrôle station', 'station.rotator': 'Rotator', 'station.rotateTo': 'Tourner vers {az}°', 'station.rotatorNoRead': 'Azimut non lu', 'station.bands': 'Bandes', 'station.nudgeUp': 'Monter de {n} kHz', 'station.nudgeDown': 'Descendre de {n} kHz', 'station.trackOn': 'Suivi actif', 'station.trackOff': 'Suivi inactif', 'station.trackStepTip': 'Ne réaccorder que si le rig a bougé d au moins ça', 'station.trackModeTip': "Quand l'antenne a le droit de se réaccorder", 'station.trackAlways': 'À chaque changement', 'station.trackStep': 'Au-delà d un pas', 'station.trackBand': 'Changement de bande', 'station.trackAlwaysTip': "Suivre chaque changement de fréquence. Résonance idéale, mais les moteurs tournent en permanence — et sur une SteppIR chaque déplacement bloque l'émission le temps du mouvement.", 'station.trackStepTipMode': "Ne réaccorder qu'une fois le rig sorti du pas. Suit un QSY, ignore la recherche autour.", 'station.trackBandTip': "Ne réaccorder qu'au changement de bande. Les moteurs bougent quelques fois par jour et restent tranquilles dans une bande.", 'station.pattern': 'Diagramme', 'station.bi': 'Bi', 'station.retract': 'Rétracter les éléments', 'station.moving': 'EN MOUVEMENT', 'station.elements': 'Éléments (mm)', 'station.read': 'Lire', 'station.readLengths': 'Lire les longueurs actuelles depuis le contrôleur', 'station.noLengths': 'Longueurs inconnues — clique sur Lire pour les récupérer depuis le contrôleur.', 'station.element': 'Élément', 'station.reflector': 'Réflecteur', 'station.driven': 'Radiateur', 'station.director': 'Dir', 'station.set': 'Régler', 'station.elementsHint': "Chaque appui allonge/raccourcit l'élément de 2 mm (comme le pupitre). Vérifie quel élément répond sur ton antenne.", 'station.setExactLen': "Clique pour taper la longueur actuelle exacte (recale la base si la lecture auto est fausse).", 'station.atMax': "Refusé par le contrôleur — l'élément est probablement en butée (longueur max pour cette bande), il ne peut plus s'allonger.", 'station.go': 'Aller', 'station.stop': 'Stop', 'station.dragHint': 'Glisse la poignée à gauche d un panneau pour le déplacer. Choisis un nombre de colonnes pour la disposition.', 'station.dragMove': 'Glisser pour déplacer ce panneau', 'station.colsAuto': 'Auto', 'station.addDevice': 'Ajouter un appareil', 'station.editDevice': "Modifier l'appareil", 'station.empty': "Aucune carte relais. Ajoute un WebSwitch 1216H ou une carte KMTronic 8 relais pour piloter l'alimentation et les accessoires de ta station.", 'station.online': 'En ligne', 'station.offline': 'Hors ligne', 'station.edit': 'Modifier', 'station.delete': 'Supprimer', 'station.relay': 'Relais', 'station.on': 'ON', 'station.off': 'OFF', 'station.type': "Type d'appareil", 'station.name': 'Nom', 'station.host': 'Hôte / IP', 'station.hostHint': "IP du LAN en local. Pour joindre la carte depuis L'EXTÉRIEUR, saisis une URL complète ici — ex. https://relais.tondomaine.com — pointant vers un reverse proxy (Nginx Proxy Manager…) qui expose le port HTTP de la carte.", 'station.user': "Nom d'utilisateur", 'station.pass': 'Mot de passe', 'station.optional': 'optionnel', 'station.ftdiSerial': 'Numéro de série FTDI', 'station.detect': 'Détecter', 'station.ftdiHint': "La carte Denkovi se pilote en FTDI bit-bang (pas via le port COM). Choisis son numéro de série (ex. DAE0006K). Nécessite le driver FTDI D2XX installé.", 'station.channels': 'Relais', 'station.comPort': 'Port COM', 'station.noPorts': 'Aucun port', 'station.usbRelayHint': "Cartes USB-série bon marché (CH340/LCUS) protocole A0. Si la tienne ne commute pas, donne-moi le modèle / jeu de commandes.", 'station.labels': 'Libellés des relais', 'station.cancel': 'Annuler', 'station.save': 'Enregistrer', 'station.test': 'Tester la connexion', 'station.testOk': 'Connecté — {n} relais', 'station.testFail': 'Non connecté', 'station.detectNone': 'Aucune carte FTDI trouvée — vérifie le câble et que le driver D2XX est installé.', 'station.detectFound': '{n} carte(s) détectée(s).',
|
||||
'awards.followHint': 'Diplômes affichés dans l’onglet Awards. Laisse la colonne de droite vide pour tous les afficher.', 'awards.available': 'Tous les diplômes', 'awards.followed': 'Suivis', 'awards.search': 'Filtrer…', 'awards.addAll': 'Tout ajouter', 'awards.clear': 'Vider', 'awards.allTracked': 'Tous les diplômes sont suivis.', 'awards.noneFollowed': 'Aucun pour l’instant — l’onglet Awards les montre tous.',
|
||||
'sec.awards': 'Diplômes', 'sec.cat': 'Interface CAT', 'sec.rotator': 'Rotator', 'sec.winkeyer': 'Manipulateur CW',
|
||||
|
||||
@@ -3,6 +3,7 @@ package relaydev
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -17,25 +18,31 @@ import (
|
||||
// their boards need something specific; this one exists because most of them
|
||||
// need nothing at all.
|
||||
//
|
||||
// THREE WAYS TO CONFIGURE IT, and the differences matter:
|
||||
// TWO WAYS TO CONFIGURE IT, and the difference matters:
|
||||
//
|
||||
// - one URL pair with {relay} in it, used for every relay:
|
||||
// http://192.168.1.9/relay?n={relay}&state=on
|
||||
// - one pair per relay, when the box has no pattern to speak of:
|
||||
// relay 1 → http://192.168.1.9/FF0101 , relay 2 → .../FF0201
|
||||
// - one pair with {value} in it, and a VALUE per relay:
|
||||
// pattern http://192.168.1.9:59/Set0/{value}, relay 1 ON "1", relay 2 ON "2",
|
||||
// relay 3 ON "4", relay 4 ON "8", every OFF "0".
|
||||
//
|
||||
// The last two are the reason this driver exists. A hand-made switch often has
|
||||
// URLs with nothing in common between channels, which no pattern can express;
|
||||
// and a bit-mask board (qro.cz and its kin) repeats a long URL whose only
|
||||
// varying part is one number, which is eight boxes of noise to type and to read.
|
||||
// {value} keeps the address in one place and leaves the numbers in the grid.
|
||||
// The second is the reason this driver exists. A hand-made switch often has
|
||||
// URLs with nothing in common between channels, and a template with {relay}
|
||||
// cannot express that.
|
||||
//
|
||||
// {relay} may carry an offset — {relay-1} for a board that counts its channels
|
||||
// from zero, which is otherwise impossible to express without giving up the
|
||||
// pattern entirely.
|
||||
// TWO SUBSTITUTIONS are available in either form:
|
||||
//
|
||||
// {relay} the relay number, 1-based. {relay-1} for a board that counts its
|
||||
// channels from zero — otherwise the whole pattern has to be given
|
||||
// up for eight hand-typed URLs over one missing offset.
|
||||
// {value} that relay's LABEL, the name given to it in Relay labels. A switch
|
||||
// addressed by antenna name rather than by channel number
|
||||
// (…/relay?on=Ant1) is then one pattern instead of eight URLs, and
|
||||
// renaming the antenna re-addresses it — the name the operator reads
|
||||
// on the button and the name on the wire cannot drift apart because
|
||||
// they are the same string.
|
||||
//
|
||||
// The label is percent-encoded, so a name with a space or an accent goes out as
|
||||
// a valid URL rather than a request the board rejects without saying why.
|
||||
//
|
||||
// STATE IS REMEMBERED, NOT READ. Most of these boxes have no status endpoint,
|
||||
// or answer with a web page nobody can parse reliably. Status therefore returns
|
||||
@@ -45,6 +52,7 @@ type httpGen struct {
|
||||
offURLs []string
|
||||
onPat string // pattern with {relay}, used when the per-relay URL is empty
|
||||
offPat string
|
||||
labels []string // index 0 = relay 1; what {value} resolves to
|
||||
user string
|
||||
pass string
|
||||
count int
|
||||
@@ -55,8 +63,8 @@ type httpGen struct {
|
||||
|
||||
// NewHTTPGeneric builds the driver. onURLs/offURLs are per relay (index 0 =
|
||||
// relay 1) and may be short or hold empty entries; onPat/offPat are the
|
||||
// fallback patterns.
|
||||
func NewHTTPGeneric(onURLs, offURLs []string, onPat, offPat, user, pass string, count int) Device {
|
||||
// fallback patterns; labels are the relay names {value} substitutes.
|
||||
func NewHTTPGeneric(onURLs, offURLs []string, onPat, offPat, user, pass string, count int, labels []string) Device {
|
||||
if count <= 0 {
|
||||
count = len(onURLs)
|
||||
}
|
||||
@@ -65,7 +73,7 @@ func NewHTTPGeneric(onURLs, offURLs []string, onPat, offPat, user, pass string,
|
||||
}
|
||||
return &httpGen{
|
||||
onURLs: onURLs, offURLs: offURLs,
|
||||
onPat: onPat, offPat: offPat,
|
||||
onPat: onPat, offPat: offPat, labels: labels,
|
||||
user: user, pass: pass, count: count,
|
||||
state: make([]bool, count),
|
||||
}
|
||||
@@ -94,28 +102,34 @@ func (h *httpGen) entryFor(relay int, on bool) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// urlFor builds the request for one relay in one direction.
|
||||
//
|
||||
// THE PATTERN DECIDES WHAT THE PER-RELAY BOXES HOLD. With {value} in it they
|
||||
// hold values to drop into it; without, they hold whole URLs that win over it.
|
||||
// One rule, and it is the pattern the operator can see while typing them — a
|
||||
// per-box guess ("does this look like a URL?") would change meaning silently on
|
||||
// a typo, which is not a thing to do to something wired to an antenna.
|
||||
// labelFor returns the relay's name, as typed in Relay labels.
|
||||
func (h *httpGen) labelFor(relay int) string {
|
||||
if i := relay - 1; i >= 0 && i < len(h.labels) {
|
||||
return strings.TrimSpace(h.labels[i])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// urlFor builds the request for one relay in one direction: the per-relay URL
|
||||
// if there is one, the pattern otherwise, with both substitutions applied.
|
||||
func (h *httpGen) urlFor(relay int, on bool) string {
|
||||
pat, entry := h.patFor(on), h.entryFor(relay, on)
|
||||
if strings.Contains(pat, "{value}") {
|
||||
if entry == "" {
|
||||
u := h.entryFor(relay, on)
|
||||
if u == "" {
|
||||
u = h.patFor(on)
|
||||
}
|
||||
if u == "" {
|
||||
return ""
|
||||
}
|
||||
return expandRelay(strings.ReplaceAll(pat, "{value}", entry), relay)
|
||||
return expand(u, relay, h.labelFor(relay))
|
||||
}
|
||||
if entry != "" {
|
||||
return expandRelay(entry, relay)
|
||||
}
|
||||
if pat == "" {
|
||||
return ""
|
||||
}
|
||||
return expandRelay(pat, relay)
|
||||
|
||||
// escapeValue percent-encodes a relay label for use anywhere in a URL.
|
||||
//
|
||||
// url.QueryEscape alone is wrong: it writes a space as "+", which is a space
|
||||
// only in a query string and a literal plus sign in a path. Encoding it as %20
|
||||
// instead is correct in both, and {value} may land in either.
|
||||
func escapeValue(s string) string {
|
||||
return strings.ReplaceAll(url.QueryEscape(s), "+", "%20")
|
||||
}
|
||||
|
||||
// withScheme supplies http:// when none was typed, and leaves https:// alone.
|
||||
@@ -139,10 +153,12 @@ func withScheme(u string) string {
|
||||
// relayToken matches {relay} and its offset forms, {relay-1} / {relay+2}.
|
||||
var relayToken = regexp.MustCompile(`\{relay([+-]\d+)?\}`)
|
||||
|
||||
// expandRelay substitutes the relay number, honouring an offset. A board that
|
||||
// numbers its channels from zero is written {relay-1}; without that the whole
|
||||
// pattern has to be abandoned for four hand-typed URLs.
|
||||
func expandRelay(s string, relay int) string {
|
||||
// expand substitutes {value} with the relay's label and {relay} with its
|
||||
// number, honouring an offset. A board that numbers its channels from zero is
|
||||
// written {relay-1}; without that the whole pattern has to be abandoned for
|
||||
// four hand-typed URLs.
|
||||
func expand(s string, relay int, label string) string {
|
||||
s = strings.ReplaceAll(s, "{value}", escapeValue(label))
|
||||
return relayToken.ReplaceAllStringFunc(s, func(m string) string {
|
||||
n := relay
|
||||
if i := strings.IndexAny(m, "+-"); i >= 0 {
|
||||
@@ -158,22 +174,27 @@ func (h *httpGen) Set(ctx context.Context, relay int, on bool) error {
|
||||
if relay < 1 || relay > h.count {
|
||||
return fmt.Errorf("relay %d out of range 1..%d", relay, h.count)
|
||||
}
|
||||
u := h.urlFor(relay, on)
|
||||
if u == "" {
|
||||
// Naming the direction matters: an operator who filled the ON URLs and
|
||||
// left OFF empty gets a switch that latches, and "no URL configured"
|
||||
// alone would not say which half is missing. Name what is missing too —
|
||||
// with {value} in the pattern the empty box wants a number, not a URL,
|
||||
// and being told to enter a URL there sends them the wrong way.
|
||||
dir, what := "OFF", "URL"
|
||||
// Naming the direction matters: an operator who filled the ON URLs and left
|
||||
// OFF empty gets a switch that latches, and "no URL configured" alone would
|
||||
// not say which half is missing.
|
||||
dir := "OFF"
|
||||
if on {
|
||||
dir = "ON"
|
||||
}
|
||||
if strings.Contains(h.patFor(on), "{value}") {
|
||||
what = "value"
|
||||
tmpl := h.entryFor(relay, on)
|
||||
if tmpl == "" {
|
||||
tmpl = h.patFor(on)
|
||||
}
|
||||
return fmt.Errorf("no %s %s configured for relay %d", dir, what, relay)
|
||||
if tmpl == "" {
|
||||
return fmt.Errorf("no %s URL configured for relay %d", dir, relay)
|
||||
}
|
||||
// {value} with no label would send "?on=" — an empty parameter to an antenna
|
||||
// switch, which most boards answer with a cheerful 200 and no movement. Say
|
||||
// what is missing instead of firing it.
|
||||
if strings.Contains(tmpl, "{value}") && h.labelFor(relay) == "" {
|
||||
return fmt.Errorf("the %s URL for relay %d uses {value}, but relay %d has no label to put there", dir, relay, relay)
|
||||
}
|
||||
u := h.urlFor(relay, on)
|
||||
u = withScheme(u)
|
||||
if _, err := get(ctx, u, h.user, h.pass); err != nil {
|
||||
return err
|
||||
|
||||
@@ -22,7 +22,7 @@ func TestHTTPGenericPattern(t *testing.T) {
|
||||
|
||||
d := NewHTTPGeneric(nil, nil,
|
||||
srv.URL+"/relay?n={relay}&state=on",
|
||||
srv.URL+"/relay?n={relay}&state=off", "", "", 4)
|
||||
srv.URL+"/relay?n={relay}&state=off", "", "", 4, nil)
|
||||
if err := d.Set(context.Background(), 2, true); err != nil {
|
||||
t.Fatalf("Set on: %v", err)
|
||||
}
|
||||
@@ -53,7 +53,7 @@ func TestHTTPGenericPerRelayURLsWinOverThePattern(t *testing.T) {
|
||||
d := NewHTTPGeneric(
|
||||
[]string{srv.URL + "/FF0101", "", srv.URL + "/weird/on"},
|
||||
[]string{srv.URL + "/FF0100", "", ""},
|
||||
srv.URL+"/pattern/on/{relay}", srv.URL+"/pattern/off/{relay}", "", "", 3)
|
||||
srv.URL+"/pattern/on/{relay}", srv.URL+"/pattern/off/{relay}", "", "", 3, nil)
|
||||
|
||||
_ = d.Set(context.Background(), 1, true) // its own URL
|
||||
_ = d.Set(context.Background(), 2, true) // empty → falls back to the pattern
|
||||
@@ -66,36 +66,36 @@ func TestHTTPGenericPerRelayURLsWinOverThePattern(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The {value} form: one address, and the per-relay boxes hold the number that
|
||||
// goes into it. A bit-mask board (qro.cz) is the case — /Set0/1, /Set0/2,
|
||||
// /Set0/4, /Set0/8 — where four full URLs differ by one character.
|
||||
func TestHTTPGenericValueSubstitution(t *testing.T) {
|
||||
// {value} is the relay's LABEL: a switch addressed by antenna name rather than
|
||||
// by channel number is one pattern instead of eight URLs.
|
||||
func TestHTTPGenericValueIsTheRelayLabel(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var got []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
got = append(got, r.URL.Path)
|
||||
got = append(got, r.URL.String())
|
||||
mu.Unlock()
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
d := NewHTTPGeneric(
|
||||
[]string{"1", "2", "4", "8"},
|
||||
[]string{"0", "0", "0", "0"},
|
||||
srv.URL+"/Set0/{value}", srv.URL+"/Set0/{value}", "", "", 4)
|
||||
_ = d.Set(context.Background(), 3, true)
|
||||
_ = d.Set(context.Background(), 1, false)
|
||||
[]string{srv.URL + "/relay?on={value}"}, // per-relay URL
|
||||
nil,
|
||||
"", srv.URL+"/relay?off={value}", // and the pattern, for the other direction
|
||||
"", "", 3, []string{"Ant1", "Beam 20m", ""})
|
||||
_ = d.Set(context.Background(), 1, true)
|
||||
_ = d.Set(context.Background(), 2, false)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
want := []string{"/Set0/4", "/Set0/0"}
|
||||
// The space in "Beam 20m" must go out as %20 — a "+" would be a literal plus
|
||||
// in a path, and this substitution can land in either half of a URL.
|
||||
want := []string{"/relay?on=Ant1", "/relay?off=Beam%2020m"}
|
||||
if strings.Join(got, " ") != strings.Join(want, " ") {
|
||||
t.Errorf("requested %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// {value} and {relay-1} together: the other API of the same board, whose
|
||||
// channels are numbered from zero. Without the offset the pattern has to be
|
||||
// abandoned for four hand-typed URLs.
|
||||
// {relay-1} for a board whose channels are numbered from zero.
|
||||
func TestHTTPGenericRelayOffset(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var got []string
|
||||
@@ -106,10 +106,8 @@ func TestHTTPGenericRelayOffset(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
d := NewHTTPGeneric(
|
||||
[]string{"1", "1", "1", "1"},
|
||||
[]string{"0", "0", "0", "0"},
|
||||
srv.URL+"/set0/{relay-1}/{value}", srv.URL+"/set0/{relay-1}/{value}", "", "", 4)
|
||||
d := NewHTTPGeneric(nil, nil,
|
||||
srv.URL+"/set0/{relay-1}/1", srv.URL+"/set0/{relay-1}/0", "", "", 4, nil)
|
||||
_ = d.Set(context.Background(), 1, true)
|
||||
_ = d.Set(context.Background(), 4, false)
|
||||
mu.Lock()
|
||||
@@ -120,14 +118,15 @@ func TestHTTPGenericRelayOffset(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// With {value} in the pattern the per-relay boxes hold values, so an empty one
|
||||
// must be reported as a missing VALUE. Telling the operator to enter a URL in a
|
||||
// box that wants "4" sends them to rewrite a configuration that was nearly right.
|
||||
func TestHTTPGenericNamesAMissingValue(t *testing.T) {
|
||||
d := NewHTTPGeneric(nil, nil, "http://x/Set0/{value}", "http://x/Set0/{value}", "", "", 2)
|
||||
// A URL that uses {value} on an unlabelled relay would go out as "?on=" — an
|
||||
// empty parameter, which most boards answer with a cheerful 200 and no
|
||||
// movement. It must be refused, and the message must say the label is what is
|
||||
// missing.
|
||||
func TestHTTPGenericRefusesValueWithoutALabel(t *testing.T) {
|
||||
d := NewHTTPGeneric(nil, nil, "http://x/relay?on={value}", "", "", "", 2, []string{"", ""})
|
||||
err := d.Set(context.Background(), 1, true)
|
||||
if err == nil || !strings.Contains(err.Error(), "value") {
|
||||
t.Errorf("err = %v, want it to name the missing value", err)
|
||||
if err == nil || !strings.Contains(err.Error(), "label") {
|
||||
t.Errorf("err = %v, want it to name the missing label", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +149,7 @@ func TestHTTPGenericSuppliesTheScheme(t *testing.T) {
|
||||
// A switch with the ON URLs filled and OFF left empty latches. The error has to
|
||||
// name the direction, or the operator cannot tell which half is missing.
|
||||
func TestHTTPGenericNamesTheMissingDirection(t *testing.T) {
|
||||
d := NewHTTPGeneric([]string{"http://x/on"}, nil, "", "", "", "", 1)
|
||||
d := NewHTTPGeneric([]string{"http://x/on"}, nil, "", "", "", "", 1, nil)
|
||||
err := d.Set(context.Background(), 1, false)
|
||||
if err == nil || !strings.Contains(err.Error(), "OFF") {
|
||||
t.Errorf("err = %v, want it to name the OFF direction", err)
|
||||
@@ -161,7 +160,7 @@ func TestHTTPGenericNamesTheMissingDirection(t *testing.T) {
|
||||
func TestHTTPGenericRemembersWhatItCommanded(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
defer srv.Close()
|
||||
d := NewHTTPGeneric(nil, nil, srv.URL+"/on/{relay}", srv.URL+"/off/{relay}", "", "", 3)
|
||||
d := NewHTTPGeneric(nil, nil, srv.URL+"/on/{relay}", srv.URL+"/off/{relay}", "", "", 3, nil)
|
||||
_ = d.Set(context.Background(), 2, true)
|
||||
st, err := d.Status(context.Background())
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user