Metadata-Version: 2.5
Name: muxit
Version: 0.3.0
Summary: Drive the instruments you set up in Muxit from Python and Jupyter: psu.voltage = 3.
Project-URL: Homepage, https://muxit.io
Project-URL: Documentation, https://docs.muxit.io/guides/python-client
Author: Muxit
License-Expression: MIT
License-File: LICENSE
Keywords: instrument control,jupyter,lab automation,muxit,scpi,test and measurement
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator
Classifier: Topic :: System :: Hardware
Requires-Python: >=3.9
Requires-Dist: websockets>=12
Provides-Extra: test
Requires-Dist: pytest>=7; extra == 'test'
Description-Content-Type: text/markdown

# muxit — Muxit for Python

Set up your instruments once in [Muxit](https://muxit.io). Use them from Python, the dashboard
and AI at the same time.

```python
import muxit

m = muxit.connect()            # Muxit on this computer
psu = m.connector("psu")

psu.voltage = 3.0              # write a property
print(psu.voltage)             # read it back from the device
psu.reset()                    # call an action
```

No VISA install, no SCPI strings, no COM ports on the machine that runs Python: the
connection details live in the Muxit connector. The client talks only to the Muxit server you
point it at. It sends nothing anywhere else.

## Install

```bash
pip install muxit
```

Python 3.9 or newer. The only dependency is [`websockets`](https://pypi.org/project/websockets/).
You also need Muxit running, on this computer or another one on your network.

## Check the connection first

```bash
python -m muxit doctor
```

It shows where the client looks for Muxit, whether Muxit answers, the license tier, the
safety level and the connectors. It ends with the line to paste into Python. `python -m
muxit demo` reads and writes the built-in test device, so it works without hardware.

## Connecting

```python
m = muxit.connect()                                   # 127.0.0.1:8765
m = muxit.connect("192.168.1.20")                     # another computer, default port
m = muxit.connect("192.168.1.20", port=9000)
m = muxit.connect("192.168.1.20", password="...")     # Muxit with remote access on
m = muxit.connect("ws://lab-pc.local:8765/ws")        # a full URL works too

with muxit.connect() as m:                            # closes the connection at the end
    ...
```

Each setting comes from the argument first, then the environment variable, then the
default:

| Setting  | Argument   | Environment      | Default     |
|----------|------------|------------------|-------------|
| Host     | 1st / `host` | `MUXIT_HOST`   | `127.0.0.1` |
| Port     | `port`     | `MUXIT_PORT`     | `8765`      |
| Password | `password` | `MUXIT_PASSWORD` | —           |
| Token    | `token`    | `MUXIT_TOKEN`    | —           |
| Timeout  | `timeout`  | `MUXIT_TIMEOUT`  | `10` s      |

With the environment variables set, a notebook holds no address or password and can be
shared. No password is needed on the Muxit computer itself. From another computer, Muxit
needs remote access on and a password set (Settings › Remote access).

## Connectors, properties and actions

```python
m.connectors()                 # ['psu', 'dmm', 'test-device']
m.cancel("psu", "rampTo")      # ask a running action to stop (leave the action out for all)

psu = m.connector("psu")
psu = m["bk-psu"]              # a name with a dash
psu = m.bk_psu                 # ...or with the dash as underscore

psu.voltage = 3.0              # write
v = psu.voltage                # read (Muxit's latest polled value)
psu.output = True
psu.reset()                    # action
robot.moveAbsolute([100, 200, 50])
robot.move_absolute([100, 200, 50])   # snake_case works when the name is free

psu.read("voltage")            # explicit forms, for names in a variable
psu.write("voltage", 3.0)
psu.call("moveAbsolute", [100, 200, 50])

print(psu.describe())          # every property and action, with units
```

The client fetches each connector's list of properties and actions on first use. So
`psu.voltge` fails at once with `Did you mean 'voltage'?`, writing a read-only property is
refused before anything is sent, and Tab completes names in Jupyter.

**Reads are Muxit's latest value.** Muxit polls the properties of a driver
continuously, every 200 ms by default (`polling.connectorRate`). Straight after a write, a
read can still show the old value for one poll interval. In a sweep, wait for the device
to settle (`time.sleep(...)`) before you read, as you would anyway. Properties that the
connector file defines itself are read live.

Values come back as plain Python: numbers, `True`/`False`, strings, lists and dicts. numpy
values can be sent directly.

## Live values, recording and plots

Muxit polls every connector and pushes the changes. You can read those values straight from
the client, without asking the device again:

```python
m.state("psu", "voltage")              # latest polled value
m.state("psu")                         # {"voltage": 3.0, "current": 0.12, ...}
m.wait_for("psu.voltage", lambda v: v > 2.95, timeout=5)

off = m.on("psu.voltage", print)       # call a function on every change (on a background thread)
off()                                  # stop it

rec = m.record(["psu.voltage", "dmm.current"], seconds=10, every=0.1)
rec.to_pandas()                        # DataFrame indexed by time (needs pandas)
rec.plot()                             # needs pandas + matplotlib
rec.to_csv("run.csv")                  # no pandas needed
rec["dmm.current"]                     # one column as a list
```

`record()` takes samples on a fixed schedule. It stops after `seconds`, when `until()`
returns True, or when you press Ctrl+C (you keep what was recorded so far). Pass a
connector name to record all of its properties.

## Streams and images

```python
with m.stream("camera", "video") as video:
    frame = video.next(timeout=10)     # shows inline in Jupyter
    frame.save("frame.jpg")
    pixels = frame.to_numpy()          # needs pillow + numpy
    for frame in video: ...            # every frame as it arrives (Ctrl+C or break to stop)

muxit.Frame(cam.snapshot()).save("snap.jpg")   # a base64 image from an action or property
```

A frame's `.data` holds the decoded value: a dict or list for JSON, `bytes` for an image,
otherwise text. A stream keeps only its newest `buffer` frames (100 by default). `dropped`
counts the frames it threw away.

## Muxit scripts

```python
m.scripts.files()                      # scripts in the workspace
m.scripts.run("burn-in")               # start it and wait until it ends
m.scripts.start("monitor"); m.scripts.stop("monitor")
m.scripts.stop_all()
m.scripts.run("adhoc", code="log.info('hi'); delay(500);")   # run JavaScript not in a file
```

When a script ends with an error, `run()` and `wait()` raise `muxit.ScriptFailed`.

## Events and AI

The same events a Muxit script uses:

```python
serial = m.events.wait("connector:scanner.scan")      # a barcode scanner, like waitFor() in a script
m.events.wait("dashboard:start", timeout=60)          # a dashboard button with emit: "start"
m.events.on("connector:scanner.*", lambda data, meta: print(meta["event"], data))
m.events.emit("unit-done", {"serial": serial})        # a running script's waitFor("unit-done") returns it

answer = m.ai("Is the green LED lit? Answer PASS or FAIL.", cam.snapshot())   # like ai() in a script
```

`wait()` keeps every event that arrives after its first call (the newest 1000), so nothing is
lost while your code is busy. `m.ai()` asks one question and gets one answer. It has no
history and no tools. Images need Maker.

## Example notebooks

- [First look](https://docs.muxit.io/python/00-first-look.ipynb): the built-in test device.
  Covers properties, live values, a recording with a plot, a camera frame and a script, with
  no hardware needed.
- [LED I-V curve](https://docs.muxit.io/python/01-led-iv-curve.ipynb): a power supply
  and a meter, a voltage sweep, pandas and a log plot.

## Copy as Python

In the Muxit window, open a connector card and click **Py**, or right-click the card and
choose **Copy as Python**. It copies a snippet with that connector's real names and the
address to connect to.

## When something goes wrong

Everything raised is a `muxit.MuxitError` with a message that says what to do.
`.code` holds the server's error code.

| Exception | When |
|-----------|------|
| `muxit.ConnectionFailed` | Muxit is not reachable, or the connection dropped |
| `muxit.AuthenticationFailed` | wrong or missing password or token |
| `muxit.NotFound` | no such connector, property or action (also an `AttributeError`) |
| `muxit.ReadOnly` | writing a property that can only be read |
| `muxit.SafetyBlocked` | Muxit's safety gate refused the write or action |
| `muxit.LimitReached` | a license limit or the per-connection call rate |
| `muxit.Timeout` | no answer within the timeout |
| `muxit.ScriptFailed` | a Muxit script ended with an error (`.line` points into it) |
| `muxit.MuxitError` with `.code == "CALL_CANCELLED"` | the action was cancelled while this call waited for it (`m.cancel`, a dashboard, a stopped script) |
| `muxit.MuxitError` with `.code == "CALL_TIMEOUT"` | the action ran past the time limit it declares; Muxit cancelled it |

**`muxit.SimulatedWarning`.** On the *Observe* safety level Muxit simulates writes and
actions instead of sending them. A new Free installation starts on Observe. The client
then warns that nothing reached the device. Pick another level with the safety chip in the
Muxit window.

**Confirmations.** If the connector asks for a confirmation before a write, the call waits
for someone to click it in the Muxit window. While it waits it prints `Waiting for
confirmation in the Muxit UI`, and it does not time out.

## Good to know

- Every read and write is a round trip to the server, about a millisecond locally plus the
  device's own time. That is fine for setpoints and measurements, but not for kHz control
  loops.
- Muxit allows 50 calls per second per connection by default
  (`security.rateLimit.callsPerSec`).
- Stopping scripts in the Muxit window does not stop your Python program. Use Ctrl+C.
- Free runs 3 connectors. Per-connector safety limits (`safety.limits`) are a Lab feature.
  They apply to calls from Python too.

## License

MIT. See [`LICENSE`](LICENSE). Muxit itself is licensed separately.
