Handles communication with the puppet API.
| 16 | |
| 17 | |
| 18 | class PuppetController: |
| 19 | """Handles communication with the puppet API.""" |
| 20 | |
| 21 | def __init__(self, host="localhost", port=42943): |
| 22 | self.base_url = f"http://{host}:{port}" |
| 23 | self._connected = False |
| 24 | |
| 25 | def is_connected(self): |
| 26 | """Check if the puppet API is reachable.""" |
| 27 | try: |
| 28 | response = requests.get(f"{self.base_url}/expressions", timeout=1) |
| 29 | self._connected = response.status_code == 200 |
| 30 | return self._connected |
| 31 | except requests.RequestException: |
| 32 | self._connected = False |
| 33 | return False |
| 34 | |
| 35 | def get_expressions(self): |
| 36 | """Get available expressions from the puppet.""" |
| 37 | try: |
| 38 | response = requests.get(f"{self.base_url}/expressions", timeout=2) |
| 39 | response.raise_for_status() |
| 40 | return response.json() |
| 41 | except requests.RequestException: |
| 42 | return [] |
| 43 | |
| 44 | def set_expression(self, expression): |
| 45 | """Set an expression on the puppet.""" |
| 46 | try: |
| 47 | response = requests.post( |
| 48 | f"{self.base_url}/expression", |
| 49 | json={"expression": expression}, |
| 50 | timeout=2 |
| 51 | ) |
| 52 | response.raise_for_status() |
| 53 | return True |
| 54 | except requests.RequestException: |
| 55 | return False |
| 56 | |
| 57 | def get_motions(self): |
| 58 | """Get available motions from the puppet.""" |
| 59 | try: |
| 60 | response = requests.get(f"{self.base_url}/motions", timeout=2) |
| 61 | response.raise_for_status() |
| 62 | return response.json() |
| 63 | except requests.RequestException: |
| 64 | return {} |
| 65 | |
| 66 | def set_motion(self, motion): |
| 67 | """Set a motion on the puppet.""" |
| 68 | try: |
| 69 | response = requests.post( |
| 70 | f"{self.base_url}/motion", |
| 71 | json={"motion": motion}, |
| 72 | timeout=2 |
| 73 | ) |
| 74 | response.raise_for_status() |
| 75 | return True |