2024-11-15 09:06:55 +00:00
|
|
|
import subprocess
|
|
|
|
|
|
|
|
class SainsmartRelay:
|
|
|
|
def __init__(self, executable="sainsmartrelay"):
|
|
|
|
self.executable = executable
|
|
|
|
|
|
|
|
def _run_command(self, args):
|
|
|
|
try:
|
|
|
|
result = subprocess.run(
|
2024-11-18 09:26:00 +00:00
|
|
|
[self.executable] + args,
|
2024-11-15 09:06:55 +00:00
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.PIPE,
|
|
|
|
text=True,
|
|
|
|
check=True
|
|
|
|
)
|
|
|
|
return result.stdout.strip()
|
|
|
|
except subprocess.CalledProcessError as e:
|
|
|
|
print(f"Error: {e.stderr.strip()}")
|
|
|
|
return None
|
|
|
|
|
|
|
|
def turn_on(self, relays):
|
|
|
|
"""Turn on specified relays."""
|
|
|
|
relays_str = ','.join(map(str, relays)) if isinstance(relays, (list, tuple)) else str(relays)
|
|
|
|
return self._run_command(["--on", relays_str])
|
|
|
|
|
|
|
|
def turn_off(self, relays):
|
|
|
|
"""Turn off specified relays."""
|
|
|
|
relays_str = ','.join(map(str, relays)) if isinstance(relays, (list, tuple)) else str(relays)
|
|
|
|
return self._run_command(["--off", relays_str])
|
|
|
|
|
|
|
|
def get_status(self, relays="all"):
|
|
|
|
"""Get the status of specified relays."""
|
|
|
|
return self._run_command(["--status", str(relays)])
|
|
|
|
|
|
|
|
def find_all_devices(self):
|
|
|
|
"""Find all connected FTDI devices."""
|
|
|
|
return self._run_command(["--findall"])
|
|
|
|
|
|
|
|
# Example usage:
|
|
|
|
if __name__ == "__main__":
|
|
|
|
relay = SainsmartRelay()
|
|
|
|
|
|
|
|
# Turn on relay 1
|
|
|
|
print(relay.turn_on(1))
|
|
|
|
|
|
|
|
# Turn off all relays
|
|
|
|
print(relay.turn_off("all"))
|
|
|
|
|
|
|
|
# Get the status of all relays
|
|
|
|
print(relay.get_status())
|
|
|
|
|
|
|
|
# Find all FTDI devices
|
|
|
|
print(relay.find_all_devices())
|