plexus-agent 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
plexus/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """
2
+ Plexus Agent - Send sensor data to Plexus in one line of code.
3
+
4
+ Usage:
5
+ from plexus import Plexus
6
+
7
+ px = Plexus()
8
+ px.send("temperature", 72.5)
9
+ """
10
+
11
+ from plexus.client import Plexus
12
+ from plexus.config import load_config, save_config
13
+
14
+ __version__ = "0.1.0"
15
+ __all__ = ["Plexus", "load_config", "save_config"]
plexus/cli.py ADDED
@@ -0,0 +1,320 @@
1
+ """
2
+ Command-line interface for Plexus Agent.
3
+
4
+ Usage:
5
+ plexus init # Set up API key
6
+ plexus send temperature 72.5 # Send a single value
7
+ plexus stream temperature # Stream from stdin
8
+ plexus status # Check connection
9
+ """
10
+
11
+ import sys
12
+ import time
13
+ from typing import Optional
14
+
15
+ import click
16
+
17
+ from plexus import __version__
18
+ from plexus.client import Plexus, AuthenticationError, PlexusError
19
+ from plexus.config import (
20
+ load_config,
21
+ save_config,
22
+ get_api_key,
23
+ get_endpoint,
24
+ get_device_id,
25
+ get_config_path,
26
+ )
27
+
28
+
29
+ @click.group()
30
+ @click.version_option(version=__version__, prog_name="plexus")
31
+ def main():
32
+ """
33
+ Plexus Agent - Send sensor data to Plexus.
34
+
35
+ Quick start:
36
+
37
+ plexus init # Set up your API key
38
+
39
+ plexus send temperature 72.5 # Send a value
40
+
41
+ plexus stream temperature # Stream from stdin
42
+ """
43
+ pass
44
+
45
+
46
+ @main.command()
47
+ @click.option("--api-key", prompt="API Key", hide_input=True, help="Your Plexus API key")
48
+ @click.option("--endpoint", default=None, help="API endpoint (default: https://app.plexusaero.space)")
49
+ def init(api_key: str, endpoint: Optional[str]):
50
+ """
51
+ Initialize Plexus with your API key.
52
+
53
+ Get your API key from https://app.plexusaero.space/settings
54
+ """
55
+ config = load_config()
56
+ config["api_key"] = api_key.strip()
57
+
58
+ if endpoint:
59
+ config["endpoint"] = endpoint.strip()
60
+
61
+ # Generate device ID if not present
62
+ if not config.get("device_id"):
63
+ import uuid
64
+ config["device_id"] = f"device-{uuid.uuid4().hex[:8]}"
65
+
66
+ save_config(config)
67
+
68
+ click.echo(f"Config saved to {get_config_path()}")
69
+ click.echo(f"Device ID: {config['device_id']}")
70
+
71
+ # Test the connection
72
+ click.echo("\nTesting connection...")
73
+ try:
74
+ px = Plexus(api_key=api_key)
75
+ px.send("plexus.agent.init", 1, tags={"event": "init"})
76
+ click.secho("✓ Connected successfully!\n", fg="green")
77
+ click.echo("You're all set! Try these commands:")
78
+ click.echo(" plexus send temperature 72.5 # Send a single value")
79
+ click.echo(" plexus send motor.rpm 3450 -t id=1 # Send with tags")
80
+ click.echo(" plexus stream sensor_name # Stream from stdin")
81
+ click.echo(" plexus status # Check connection")
82
+ click.echo(f"\nEndpoint: {px.endpoint}")
83
+ except AuthenticationError as e:
84
+ click.secho(f"✗ Authentication failed: {e}", fg="red")
85
+ click.echo("\nCheck that your API key is valid at:")
86
+ click.echo(f" {config.get('endpoint', 'https://app.plexusaero.space')}/settings?tab=connections")
87
+ sys.exit(1)
88
+ except PlexusError as e:
89
+ click.secho(f"✗ Connection failed: {e}", fg="yellow")
90
+ click.echo("\nYour config is saved. Troubleshooting:")
91
+ click.echo(" • Check your network connection")
92
+ click.echo(" • Verify the endpoint is correct")
93
+ click.echo(f" • Current endpoint: {config.get('endpoint', 'https://app.plexusaero.space')}")
94
+
95
+
96
+ @main.command()
97
+ @click.argument("metric")
98
+ @click.argument("value", type=float)
99
+ @click.option("--tag", "-t", multiple=True, help="Tag in key=value format")
100
+ @click.option("--timestamp", type=float, help="Unix timestamp (default: now)")
101
+ def send(metric: str, value: float, tag: tuple, timestamp: Optional[float]):
102
+ """
103
+ Send a single metric value.
104
+
105
+ Examples:
106
+
107
+ plexus send temperature 72.5
108
+
109
+ plexus send motor.rpm 3450 -t motor_id=A1
110
+
111
+ plexus send pressure 1013.25 --timestamp 1699900000
112
+ """
113
+ api_key = get_api_key()
114
+ if not api_key:
115
+ click.secho("No API key configured. Run 'plexus init' first.", fg="red")
116
+ sys.exit(1)
117
+
118
+ # Parse tags
119
+ tags = {}
120
+ for t in tag:
121
+ if "=" in t:
122
+ k, v = t.split("=", 1)
123
+ tags[k] = v
124
+ else:
125
+ click.secho(f"Invalid tag format: {t} (expected key=value)", fg="yellow")
126
+
127
+ try:
128
+ px = Plexus()
129
+ px.send(metric, value, timestamp=timestamp, tags=tags if tags else None)
130
+ click.secho(f"✓ Sent {metric}={value}", fg="green")
131
+ if tags:
132
+ click.echo(f" Tags: {tags}")
133
+ except AuthenticationError as e:
134
+ click.secho(f"✗ Authentication error: {e}", fg="red")
135
+ click.echo(" Run 'plexus init' to reconfigure your API key")
136
+ sys.exit(1)
137
+ except PlexusError as e:
138
+ click.secho(f"✗ Error: {e}", fg="red")
139
+ sys.exit(1)
140
+
141
+
142
+ @main.command()
143
+ @click.argument("metric")
144
+ @click.option("--rate", "-r", type=float, default=None, help="Max samples per second")
145
+ @click.option("--tag", "-t", multiple=True, help="Tag in key=value format")
146
+ @click.option("--session", "-s", help="Session ID for grouping data")
147
+ def stream(metric: str, rate: Optional[float], tag: tuple, session: Optional[str]):
148
+ """
149
+ Stream values from stdin.
150
+
151
+ Reads numeric values from stdin (one per line) and sends them to Plexus.
152
+
153
+ Examples:
154
+
155
+ # Stream from a sensor script
156
+ python read_sensor.py | plexus stream temperature
157
+
158
+ # Rate-limited to 100 samples/sec
159
+ cat data.txt | plexus stream pressure -r 100
160
+
161
+ # With session tracking
162
+ python read_motor.py | plexus stream motor.rpm -s test-001
163
+ """
164
+ api_key = get_api_key()
165
+ if not api_key:
166
+ click.secho("No API key configured. Run 'plexus init' first.", fg="red")
167
+ sys.exit(1)
168
+
169
+ # Parse tags
170
+ tags = {}
171
+ for t in tag:
172
+ if "=" in t:
173
+ k, v = t.split("=", 1)
174
+ tags[k] = v
175
+
176
+ min_interval = 1.0 / rate if rate else 0
177
+ last_send = 0
178
+ count = 0
179
+
180
+ try:
181
+ px = Plexus()
182
+
183
+ context = px.session(session) if session else nullcontext()
184
+ with context:
185
+ click.echo(f"Streaming {metric} from stdin... (Ctrl+C to stop)", err=True)
186
+
187
+ for line in sys.stdin:
188
+ line = line.strip()
189
+ if not line:
190
+ continue
191
+
192
+ try:
193
+ value = float(line)
194
+ except ValueError:
195
+ click.echo(f"Skipping non-numeric: {line}", err=True)
196
+ continue
197
+
198
+ # Rate limiting
199
+ now = time.time()
200
+ if min_interval and (now - last_send) < min_interval:
201
+ time.sleep(min_interval - (now - last_send))
202
+
203
+ px.send(metric, value, tags=tags if tags else None)
204
+ count += 1
205
+ last_send = time.time()
206
+
207
+ # Progress indicator every 100 samples
208
+ if count % 100 == 0:
209
+ click.echo(f"Sent {count} samples", err=True)
210
+
211
+ except KeyboardInterrupt:
212
+ click.echo(f"\nStopped. Sent {count} samples.", err=True)
213
+ except AuthenticationError as e:
214
+ click.secho(f"Authentication error: {e}", fg="red")
215
+ sys.exit(1)
216
+ except PlexusError as e:
217
+ click.secho(f"Error: {e}", fg="red")
218
+ sys.exit(1)
219
+
220
+
221
+ @main.command()
222
+ def status():
223
+ """
224
+ Check connection status and configuration.
225
+ """
226
+ config = load_config()
227
+ api_key = get_api_key()
228
+
229
+ click.echo("\nPlexus Agent Status")
230
+ click.echo("─" * 40)
231
+ click.echo(f" Config: {get_config_path()}")
232
+ click.echo(f" Endpoint: {get_endpoint()}")
233
+ click.echo(f" Device ID: {get_device_id()}")
234
+
235
+ if api_key:
236
+ # Show only prefix of API key
237
+ masked = api_key[:12] + "..." if len(api_key) > 12 else "****"
238
+ click.echo(f" API Key: {masked}")
239
+ click.echo("─" * 40)
240
+
241
+ # Test connection
242
+ click.echo(" Testing connection...")
243
+ try:
244
+ px = Plexus()
245
+ px.send("plexus.agent.status", 1, tags={"event": "status_check"})
246
+ click.secho(" Status: ✓ Connected\n", fg="green")
247
+ except AuthenticationError as e:
248
+ click.secho(f" Status: ✗ Auth failed - {e}\n", fg="red")
249
+ except PlexusError as e:
250
+ click.secho(f" Status: ✗ Connection failed - {e}\n", fg="yellow")
251
+ else:
252
+ click.secho(" API Key: Not configured", fg="yellow")
253
+ click.echo("─" * 40)
254
+ click.echo("\n Run 'plexus init' to set up your API key.\n")
255
+
256
+
257
+ @main.command()
258
+ def config():
259
+ """
260
+ Show current configuration.
261
+ """
262
+ cfg = load_config()
263
+ click.echo(f"Config file: {get_config_path()}\n")
264
+
265
+ for key, value in cfg.items():
266
+ if key == "api_key" and value:
267
+ # Mask API key
268
+ value = value[:8] + "..." + value[-4:] if len(value) > 12 else "****"
269
+ click.echo(f" {key}: {value}")
270
+
271
+
272
+ @main.command()
273
+ def connect():
274
+ """
275
+ Connect to Plexus for remote terminal access.
276
+
277
+ This opens a persistent connection to the Plexus server, allowing
278
+ you to run commands on this machine from the web UI.
279
+
280
+ Example:
281
+
282
+ plexus connect
283
+ """
284
+ from plexus.connector import run_connector
285
+
286
+ api_key = get_api_key()
287
+ if not api_key:
288
+ click.secho("No API key configured. Run 'plexus init' first.", fg="red")
289
+ sys.exit(1)
290
+
291
+ endpoint = get_endpoint()
292
+ device_id = get_device_id()
293
+
294
+ click.echo("\nPlexus Remote Terminal")
295
+ click.echo("─" * 40)
296
+ click.echo(f" Device ID: {device_id}")
297
+ click.echo(f" Endpoint: {endpoint}")
298
+ click.echo("─" * 40)
299
+
300
+ def status_callback(msg: str):
301
+ click.echo(f" {msg}")
302
+
303
+ click.echo("\n Press Ctrl+C to disconnect\n")
304
+
305
+ try:
306
+ run_connector(api_key=api_key, endpoint=endpoint, on_status=status_callback)
307
+ except KeyboardInterrupt:
308
+ click.echo("\n Disconnected.")
309
+
310
+
311
+ # Null context manager for Python 3.8 compatibility
312
+ class nullcontext:
313
+ def __enter__(self):
314
+ return None
315
+ def __exit__(self, *args):
316
+ return False
317
+
318
+
319
+ if __name__ == "__main__":
320
+ main()
plexus/client.py ADDED
@@ -0,0 +1,268 @@
1
+ """
2
+ Plexus client for sending sensor data.
3
+
4
+ Usage:
5
+ from plexus import Plexus
6
+
7
+ px = Plexus()
8
+ px.send("temperature", 72.5)
9
+
10
+ # With tags
11
+ px.send("motor.rpm", 3450, tags={"motor_id": "A1"})
12
+
13
+ # Batch send
14
+ px.send_batch([
15
+ ("temperature", 72.5),
16
+ ("humidity", 45.2),
17
+ ("pressure", 1013.25),
18
+ ])
19
+
20
+ # Session recording
21
+ with px.session("motor-test-001"):
22
+ while True:
23
+ px.send("temperature", read_temp())
24
+ time.sleep(0.01)
25
+ """
26
+
27
+ import time
28
+ from contextlib import contextmanager
29
+ from typing import Any, Dict, List, Optional, Tuple, Union
30
+
31
+ import requests
32
+
33
+ from plexus.config import get_api_key, get_device_id, get_endpoint
34
+
35
+
36
+ class PlexusError(Exception):
37
+ """Base exception for Plexus errors."""
38
+
39
+ pass
40
+
41
+
42
+ class AuthenticationError(PlexusError):
43
+ """Raised when API key is missing or invalid."""
44
+
45
+ pass
46
+
47
+
48
+ class Plexus:
49
+ """
50
+ Client for sending sensor data to Plexus.
51
+
52
+ Args:
53
+ api_key: Your Plexus API key. If not provided, reads from
54
+ PLEXUS_API_KEY env var or ~/.plexus/config.json
55
+ endpoint: API endpoint URL. Defaults to https://app.plexusaero.space
56
+ device_id: Unique identifier for this device. Auto-generated if not provided.
57
+ timeout: Request timeout in seconds. Default 10s.
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ api_key: Optional[str] = None,
63
+ endpoint: Optional[str] = None,
64
+ device_id: Optional[str] = None,
65
+ timeout: float = 10.0,
66
+ ):
67
+ self.api_key = api_key or get_api_key()
68
+ self.endpoint = (endpoint or get_endpoint()).rstrip("/")
69
+ self.device_id = device_id or get_device_id()
70
+ self.timeout = timeout
71
+
72
+ self._session_id: Optional[str] = None
73
+ self._session: Optional[requests.Session] = None
74
+
75
+ # Buffer for batch operations
76
+ self._buffer: List[Dict[str, Any]] = []
77
+ self._buffer_size = 100
78
+
79
+ def _get_session(self) -> requests.Session:
80
+ """Get or create a requests session for connection pooling."""
81
+ if self._session is None:
82
+ self._session = requests.Session()
83
+ if self.api_key:
84
+ self._session.headers["x-api-key"] = self.api_key
85
+ self._session.headers["Content-Type"] = "application/json"
86
+ self._session.headers["User-Agent"] = "agent/0.1.0"
87
+ return self._session
88
+
89
+ def _make_point(
90
+ self,
91
+ metric: str,
92
+ value: Union[int, float],
93
+ timestamp: Optional[float] = None,
94
+ tags: Optional[Dict[str, str]] = None,
95
+ ) -> Dict[str, Any]:
96
+ """Create a data point dictionary."""
97
+ point = {
98
+ "metric": metric,
99
+ "value": value,
100
+ "timestamp": timestamp or time.time(),
101
+ "device_id": self.device_id,
102
+ }
103
+ if tags:
104
+ point["tags"] = tags
105
+ if self._session_id:
106
+ point["session_id"] = self._session_id
107
+ return point
108
+
109
+ def send(
110
+ self,
111
+ metric: str,
112
+ value: Union[int, float],
113
+ timestamp: Optional[float] = None,
114
+ tags: Optional[Dict[str, str]] = None,
115
+ ) -> bool:
116
+ """
117
+ Send a single metric value to Plexus.
118
+
119
+ Args:
120
+ metric: Name of the metric (e.g., "temperature", "motor.rpm")
121
+ value: Numeric value to send
122
+ timestamp: Unix timestamp. If not provided, uses current time.
123
+ tags: Optional key-value tags for the metric
124
+
125
+ Returns:
126
+ True if successful
127
+
128
+ Raises:
129
+ AuthenticationError: If API key is missing or invalid
130
+ PlexusError: If the request fails
131
+
132
+ Example:
133
+ px.send("temperature", 72.5)
134
+ px.send("motor.rpm", 3450, tags={"motor_id": "A1"})
135
+ """
136
+ if not self.api_key:
137
+ raise AuthenticationError(
138
+ "No API key configured. Run 'plexus init' or set PLEXUS_API_KEY"
139
+ )
140
+
141
+ point = self._make_point(metric, value, timestamp, tags)
142
+ return self._send_points([point])
143
+
144
+ def send_batch(
145
+ self,
146
+ points: List[Tuple[str, Union[int, float]]],
147
+ timestamp: Optional[float] = None,
148
+ tags: Optional[Dict[str, str]] = None,
149
+ ) -> bool:
150
+ """
151
+ Send multiple metrics at once.
152
+
153
+ Args:
154
+ points: List of (metric, value) tuples
155
+ timestamp: Shared timestamp for all points. If not provided, uses current time.
156
+ tags: Shared tags for all points
157
+
158
+ Returns:
159
+ True if successful
160
+
161
+ Example:
162
+ px.send_batch([
163
+ ("temperature", 72.5),
164
+ ("humidity", 45.2),
165
+ ("pressure", 1013.25),
166
+ ])
167
+ """
168
+ if not self.api_key:
169
+ raise AuthenticationError(
170
+ "No API key configured. Run 'plexus init' or set PLEXUS_API_KEY"
171
+ )
172
+
173
+ ts = timestamp or time.time()
174
+ data_points = [self._make_point(m, v, ts, tags) for m, v in points]
175
+ return self._send_points(data_points)
176
+
177
+ def _send_points(self, points: List[Dict[str, Any]]) -> bool:
178
+ """Send data points to the API."""
179
+ url = f"{self.endpoint}/api/ingest"
180
+
181
+ try:
182
+ response = self._get_session().post(
183
+ url,
184
+ json={"points": points},
185
+ timeout=self.timeout,
186
+ )
187
+
188
+ if response.status_code == 401:
189
+ raise AuthenticationError("Invalid API key")
190
+ elif response.status_code == 403:
191
+ raise AuthenticationError("API key doesn't have write permissions")
192
+ elif response.status_code >= 400:
193
+ raise PlexusError(f"API error: {response.status_code} - {response.text}")
194
+
195
+ return True
196
+
197
+ except requests.exceptions.Timeout:
198
+ raise PlexusError(f"Request timed out after {self.timeout}s")
199
+ except requests.exceptions.ConnectionError as e:
200
+ raise PlexusError(f"Connection failed: {e}")
201
+
202
+ @contextmanager
203
+ def session(self, session_id: str, tags: Optional[Dict[str, str]] = None):
204
+ """
205
+ Context manager for recording a session.
206
+
207
+ All sends within this context will be tagged with the session ID,
208
+ making it easy to replay and analyze later.
209
+
210
+ Args:
211
+ session_id: Unique identifier for this session (e.g., "motor-test-001")
212
+ tags: Optional tags to apply to all points in this session
213
+
214
+ Example:
215
+ with px.session("motor-test-001"):
216
+ while True:
217
+ px.send("temperature", read_temp())
218
+ time.sleep(0.01)
219
+ """
220
+ self._session_id = session_id
221
+
222
+ # Notify API that session started
223
+ try:
224
+ self._get_session().post(
225
+ f"{self.endpoint}/api/sessions",
226
+ json={
227
+ "session_id": session_id,
228
+ "device_id": self.device_id,
229
+ "status": "started",
230
+ "tags": tags,
231
+ "timestamp": time.time(),
232
+ },
233
+ timeout=self.timeout,
234
+ )
235
+ except Exception:
236
+ pass # Session tracking is optional, don't fail if it doesn't work
237
+
238
+ try:
239
+ yield
240
+ finally:
241
+ # Notify API that session ended
242
+ try:
243
+ self._get_session().post(
244
+ f"{self.endpoint}/api/sessions",
245
+ json={
246
+ "session_id": session_id,
247
+ "device_id": self.device_id,
248
+ "status": "ended",
249
+ "timestamp": time.time(),
250
+ },
251
+ timeout=self.timeout,
252
+ )
253
+ except Exception:
254
+ pass
255
+ self._session_id = None
256
+
257
+ def close(self):
258
+ """Close the client and release resources."""
259
+ if self._session:
260
+ self._session.close()
261
+ self._session = None
262
+
263
+ def __enter__(self):
264
+ return self
265
+
266
+ def __exit__(self, exc_type, exc_val, exc_tb):
267
+ self.close()
268
+ return False
plexus/config.py ADDED
@@ -0,0 +1,82 @@
1
+ """
2
+ Configuration management for Plexus Agent.
3
+
4
+ Config is stored in ~/.plexus/config.json
5
+ """
6
+
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ from typing import Optional
11
+
12
+ CONFIG_DIR = Path.home() / ".plexus"
13
+ CONFIG_FILE = CONFIG_DIR / "config.json"
14
+
15
+ DEFAULT_CONFIG = {
16
+ "api_key": None,
17
+ "endpoint": "https://app.plexusaero.space",
18
+ "device_id": None,
19
+ }
20
+
21
+
22
+ def get_config_path() -> Path:
23
+ """Get the path to the config file."""
24
+ return CONFIG_FILE
25
+
26
+
27
+ def load_config() -> dict:
28
+ """Load config from file, creating defaults if needed."""
29
+ if not CONFIG_FILE.exists():
30
+ return DEFAULT_CONFIG.copy()
31
+
32
+ try:
33
+ with open(CONFIG_FILE, "r") as f:
34
+ config = json.load(f)
35
+ # Merge with defaults to handle missing keys
36
+ return {**DEFAULT_CONFIG, **config}
37
+ except (json.JSONDecodeError, IOError):
38
+ return DEFAULT_CONFIG.copy()
39
+
40
+
41
+ def save_config(config: dict) -> None:
42
+ """Save config to file."""
43
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
44
+ with open(CONFIG_FILE, "w") as f:
45
+ json.dump(config, f, indent=2)
46
+ # Set restrictive permissions (API key is sensitive)
47
+ os.chmod(CONFIG_FILE, 0o600)
48
+
49
+
50
+ def get_api_key() -> Optional[str]:
51
+ """Get API key from config or environment variable."""
52
+ # Environment variable takes precedence
53
+ env_key = os.environ.get("PLEXUS_API_KEY")
54
+ if env_key:
55
+ return env_key
56
+
57
+ config = load_config()
58
+ return config.get("api_key")
59
+
60
+
61
+ def get_endpoint() -> str:
62
+ """Get the API endpoint URL."""
63
+ env_endpoint = os.environ.get("PLEXUS_ENDPOINT")
64
+ if env_endpoint:
65
+ return env_endpoint.rstrip("/")
66
+
67
+ config = load_config()
68
+ return config.get("endpoint", DEFAULT_CONFIG["endpoint"]).rstrip("/")
69
+
70
+
71
+ def get_device_id() -> Optional[str]:
72
+ """Get the device ID, generating one if not set."""
73
+ config = load_config()
74
+ device_id = config.get("device_id")
75
+
76
+ if not device_id:
77
+ import uuid
78
+ device_id = f"device-{uuid.uuid4().hex[:8]}"
79
+ config["device_id"] = device_id
80
+ save_config(config)
81
+
82
+ return device_id
plexus/connector.py ADDED
@@ -0,0 +1,206 @@
1
+ """
2
+ WebSocket connector for remote terminal access.
3
+
4
+ Connects to the Plexus server and allows remote command execution.
5
+ """
6
+
7
+ import asyncio
8
+ import json
9
+ import os
10
+ import platform
11
+ import subprocess
12
+ import sys
13
+ from typing import Optional, Callable
14
+
15
+ import websockets
16
+ from websockets.exceptions import ConnectionClosed
17
+
18
+ from plexus.config import get_api_key, get_endpoint, get_device_id
19
+
20
+
21
+ class PlexusConnector:
22
+ """
23
+ WebSocket client that connects to Plexus and executes commands remotely.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ api_key: Optional[str] = None,
29
+ endpoint: Optional[str] = None,
30
+ device_id: Optional[str] = None,
31
+ on_status: Optional[Callable[[str], None]] = None,
32
+ ):
33
+ self.api_key = api_key or get_api_key()
34
+ self.endpoint = (endpoint or get_endpoint()).rstrip("/")
35
+ self.device_id = device_id or get_device_id()
36
+ self.on_status = on_status or (lambda x: None)
37
+
38
+ self._ws = None
39
+ self._running = False
40
+ self._current_process: Optional[subprocess.Popen] = None
41
+
42
+ def _get_ws_url(self) -> str:
43
+ """Convert HTTP endpoint to WebSocket URL."""
44
+ url = self.endpoint.replace("https://", "wss://").replace("http://", "ws://")
45
+ return f"{url}/api/agent/ws"
46
+
47
+ async def connect(self):
48
+ """Connect to the Plexus server and listen for commands."""
49
+ if not self.api_key:
50
+ raise ValueError("No API key configured. Run 'plexus init' first.")
51
+
52
+ ws_url = self._get_ws_url()
53
+ self.on_status(f"Connecting to {ws_url}...")
54
+
55
+ headers = [
56
+ ("x-api-key", self.api_key),
57
+ ("x-device-id", self.device_id),
58
+ ("x-platform", platform.system()),
59
+ ("x-python-version", platform.python_version()),
60
+ ]
61
+
62
+ self._running = True
63
+
64
+ while self._running:
65
+ try:
66
+ async with websockets.connect(
67
+ ws_url,
68
+ additional_headers=headers,
69
+ ping_interval=30,
70
+ ping_timeout=10,
71
+ ) as ws:
72
+ self._ws = ws
73
+ self.on_status("Connected! Waiting for commands...")
74
+
75
+ # Send initial handshake
76
+ await ws.send(json.dumps({
77
+ "type": "handshake",
78
+ "device_id": self.device_id,
79
+ "platform": platform.system(),
80
+ "cwd": os.getcwd(),
81
+ }))
82
+
83
+ # Listen for messages
84
+ async for message in ws:
85
+ await self._handle_message(message)
86
+
87
+ except ConnectionClosed as e:
88
+ self.on_status(f"Connection closed: {e.reason}")
89
+ if self._running:
90
+ self.on_status("Reconnecting in 5 seconds...")
91
+ await asyncio.sleep(5)
92
+ except Exception as e:
93
+ self.on_status(f"Connection error: {e}")
94
+ if self._running:
95
+ self.on_status("Reconnecting in 5 seconds...")
96
+ await asyncio.sleep(5)
97
+
98
+ async def _handle_message(self, message: str):
99
+ """Handle incoming WebSocket message."""
100
+ try:
101
+ data = json.loads(message)
102
+ msg_type = data.get("type")
103
+
104
+ if msg_type == "execute":
105
+ await self._execute_command(data)
106
+ elif msg_type == "cancel":
107
+ self._cancel_current()
108
+ elif msg_type == "ping":
109
+ await self._ws.send(json.dumps({"type": "pong"}))
110
+
111
+ except json.JSONDecodeError:
112
+ self.on_status(f"Invalid message: {message}")
113
+
114
+ async def _execute_command(self, data: dict):
115
+ """Execute a shell command and stream output back."""
116
+ command = data.get("command", "")
117
+ cmd_id = data.get("id", "unknown")
118
+
119
+ if not command:
120
+ return
121
+
122
+ self.on_status(f"Executing: {command}")
123
+
124
+ # Send start notification
125
+ await self._ws.send(json.dumps({
126
+ "type": "output",
127
+ "id": cmd_id,
128
+ "event": "start",
129
+ "command": command,
130
+ }))
131
+
132
+ try:
133
+ # Execute command
134
+ self._current_process = subprocess.Popen(
135
+ command,
136
+ shell=True,
137
+ stdout=subprocess.PIPE,
138
+ stderr=subprocess.STDOUT,
139
+ text=True,
140
+ bufsize=1,
141
+ cwd=os.getcwd(),
142
+ )
143
+
144
+ # Stream output line by line
145
+ for line in iter(self._current_process.stdout.readline, ""):
146
+ if not self._running:
147
+ break
148
+ await self._ws.send(json.dumps({
149
+ "type": "output",
150
+ "id": cmd_id,
151
+ "event": "data",
152
+ "data": line,
153
+ }))
154
+
155
+ # Wait for process to complete
156
+ return_code = self._current_process.wait()
157
+
158
+ # Send completion
159
+ await self._ws.send(json.dumps({
160
+ "type": "output",
161
+ "id": cmd_id,
162
+ "event": "exit",
163
+ "code": return_code,
164
+ }))
165
+
166
+ except Exception as e:
167
+ await self._ws.send(json.dumps({
168
+ "type": "output",
169
+ "id": cmd_id,
170
+ "event": "error",
171
+ "error": str(e),
172
+ }))
173
+
174
+ finally:
175
+ self._current_process = None
176
+
177
+ def _cancel_current(self):
178
+ """Cancel the currently running command."""
179
+ if self._current_process:
180
+ self._current_process.terminate()
181
+ self.on_status("Command cancelled")
182
+
183
+ def disconnect(self):
184
+ """Disconnect from the server."""
185
+ self._running = False
186
+ self._cancel_current()
187
+ if self._ws:
188
+ asyncio.create_task(self._ws.close())
189
+
190
+
191
+ def run_connector(
192
+ api_key: Optional[str] = None,
193
+ endpoint: Optional[str] = None,
194
+ on_status: Optional[Callable[[str], None]] = None,
195
+ ):
196
+ """Run the connector (blocking)."""
197
+ connector = PlexusConnector(
198
+ api_key=api_key,
199
+ endpoint=endpoint,
200
+ on_status=on_status,
201
+ )
202
+
203
+ try:
204
+ asyncio.run(connector.connect())
205
+ except KeyboardInterrupt:
206
+ connector.disconnect()
@@ -0,0 +1,205 @@
1
+ Metadata-Version: 2.4
2
+ Name: plexus-agent
3
+ Version: 0.1.0
4
+ Summary: Send sensor data to Plexus in one line of code
5
+ Project-URL: Homepage, https://plexus.dev
6
+ Project-URL: Documentation, https://docs.plexus.dev
7
+ Project-URL: Repository, https://github.com/plexus-oss/agent
8
+ Project-URL: Issues, https://github.com/plexus-oss/agent/issues
9
+ Author-email: Plexus <hello@plexus.dev>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: hardware,iot,observability,robotics,sensors,telemetry
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Topic :: Scientific/Engineering
24
+ Classifier: Topic :: System :: Hardware
25
+ Requires-Python: >=3.8
26
+ Requires-Dist: click>=8.0.0
27
+ Requires-Dist: requests>=2.28.0
28
+ Requires-Dist: websockets>=12.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest; extra == 'dev'
31
+ Requires-Dist: pytest-cov; extra == 'dev'
32
+ Requires-Dist: ruff; extra == 'dev'
33
+ Provides-Extra: mqtt
34
+ Requires-Dist: paho-mqtt>=1.6.0; extra == 'mqtt'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # Plexus Agent
38
+
39
+ > Send sensor data to Plexus in one line of code.
40
+
41
+ ## Quick Start
42
+
43
+ ```bash
44
+ pip install plexus-agent
45
+ plexus init # paste your API key from app.plexusaero.space
46
+ plexus send temperature 72.5
47
+ ```
48
+
49
+ That's it. Works on any device with Python - Raspberry Pi, servers, laptops, containers.
50
+
51
+ ## Get Your API Key
52
+
53
+ 1. Go to [app.plexusaero.space/settings](https://app.plexusaero.space/settings?tab=connections)
54
+ 2. Create an API key
55
+ 3. Copy the key and paste it when running `plexus init`
56
+
57
+ ## Sending Data
58
+
59
+ ### Command Line
60
+
61
+ ```bash
62
+ # Basic
63
+ plexus send temperature 72.5
64
+
65
+ # With tags (for multiple sensors)
66
+ plexus send motor.temperature 72.5 -t motor_id=A1
67
+ plexus send motor.temperature 68.3 -t motor_id=A2
68
+
69
+ # Stream from any script
70
+ python read_sensor.py | plexus stream temperature
71
+ ```
72
+
73
+ ### Python SDK
74
+
75
+ ```python
76
+ from plexus import Plexus
77
+
78
+ px = Plexus()
79
+
80
+ # Send values
81
+ px.send("temperature", 72.5)
82
+ px.send("motor.rpm", 3450, tags={"motor_id": "A1"})
83
+
84
+ # Batch send (more efficient)
85
+ px.send_batch([
86
+ ("temperature", 72.5),
87
+ ("humidity", 45.2),
88
+ ("pressure", 1013.25),
89
+ ])
90
+ ```
91
+
92
+ ### Session Recording
93
+
94
+ Group related data for easy analysis:
95
+
96
+ ```python
97
+ from plexus import Plexus
98
+
99
+ px = Plexus()
100
+
101
+ with px.session("motor-test-001"):
102
+ for _ in range(1000):
103
+ px.send("temperature", read_temp())
104
+ px.send("rpm", read_rpm())
105
+ time.sleep(0.01) # 100Hz
106
+ ```
107
+
108
+ ## CLI Reference
109
+
110
+ | Command | Description |
111
+ |---------|-------------|
112
+ | `plexus init` | Set up API key |
113
+ | `plexus send <metric> <value>` | Send a single value |
114
+ | `plexus stream <metric>` | Stream from stdin |
115
+ | `plexus status` | Check connection |
116
+
117
+ ### Examples
118
+
119
+ ```bash
120
+ # Send with tags
121
+ plexus send motor.rpm 3450 -t motor_id=A1 -t location=lab
122
+
123
+ # Send with timestamp
124
+ plexus send pressure 1013.25 --timestamp 1699900000
125
+
126
+ # Stream with rate limiting
127
+ cat data.txt | plexus stream pressure -r 100
128
+
129
+ # Stream with session
130
+ python read_motor.py | plexus stream motor.rpm -s test-001
131
+ ```
132
+
133
+ ## Configuration
134
+
135
+ Config is stored in `~/.plexus/config.json`.
136
+
137
+ ### Environment Variables
138
+
139
+ Override config with environment variables:
140
+
141
+ ```bash
142
+ export PLEXUS_API_KEY=plx_xxxxx
143
+ export PLEXUS_ENDPOINT=https://plexus.yourcompany.com # for self-hosted
144
+ ```
145
+
146
+ ## Examples
147
+
148
+ ### Raspberry Pi + DHT22
149
+
150
+ ```python
151
+ from plexus import Plexus
152
+ import adafruit_dht
153
+ import board
154
+ import time
155
+
156
+ px = Plexus()
157
+ dht = adafruit_dht.DHT22(board.D4)
158
+
159
+ while True:
160
+ try:
161
+ px.send("temperature", dht.temperature)
162
+ px.send("humidity", dht.humidity)
163
+ except RuntimeError:
164
+ pass
165
+ time.sleep(2)
166
+ ```
167
+
168
+ ### Arduino Serial Bridge
169
+
170
+ ```python
171
+ from plexus import Plexus
172
+ import serial
173
+
174
+ px = Plexus()
175
+ ser = serial.Serial('/dev/ttyUSB0', 9600)
176
+
177
+ while True:
178
+ line = ser.readline().decode().strip()
179
+ if ':' in line:
180
+ metric, value = line.split(':')
181
+ px.send(metric, float(value))
182
+ ```
183
+
184
+ ### Motor Test Stand
185
+
186
+ ```python
187
+ from plexus import Plexus
188
+ import time
189
+
190
+ px = Plexus()
191
+
192
+ with px.session("endurance-test-001"):
193
+ start = time.time()
194
+ while time.time() - start < 3600: # 1 hour
195
+ px.send_batch([
196
+ ("motor.rpm", read_rpm()),
197
+ ("motor.current", read_current()),
198
+ ("motor.temperature", read_temp()),
199
+ ])
200
+ time.sleep(0.01) # 100Hz
201
+ ```
202
+
203
+ ## License
204
+
205
+ Apache-2.0
@@ -0,0 +1,10 @@
1
+ plexus/__init__.py,sha256=QAVFcw9_lTTOsdKxLzblgVDU9uv0PgSYaPpPJKigHfA,320
2
+ plexus/cli.py,sha256=a-l92hAkoBvThs4WfJLxu_3ZRxoSy888EU_M7xdXwSU,9822
3
+ plexus/client.py,sha256=-kg7BgSFu11Eh_3U6cN_azmtNBFnkhm5A93rsXGiCaQ,8208
4
+ plexus/config.py,sha256=SkMcO6O8gcw0oAVQF0Yo4aY2ak5LbHWaK1CTPN0PImA,2102
5
+ plexus/connector.py,sha256=SjUMuxIPeWHU5tlmGdDTM7msfYpeedZhtWyX_dhPLKc,6377
6
+ plexus_agent-0.1.0.dist-info/METADATA,sha256=yOhXVjB90u_FtCr0lrjWDGNsb3p1D45rchcuJyfc5r4,4722
7
+ plexus_agent-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
8
+ plexus_agent-0.1.0.dist-info/entry_points.txt,sha256=YlkOtTn_7Q_IGuJaKdvpU-90dCeBSPx2p_UTGMAz5Zs,43
9
+ plexus_agent-0.1.0.dist-info/licenses/LICENSE,sha256=nm3qP1F-JAGcfLpRVtIX24L20LMnRpxmZ2oKZzFpLVo,10755
10
+ plexus_agent-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ plexus = plexus.cli:main
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2024 Plexus
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.