Metadata-Version: 2.4
Name: mksact
Version: 0.1.0
Summary: Linear-actuator control for MKS SERVO42D/57D closed-loop steppers over CAN (Linux SocketCAN): homing, soft limits, fast absolute moves.
Author: Durga Prasad Nasika
License: MIT
Keywords: mks,servo42d,servo57d,stepper,closed-loop,can,canbus,socketcan,actuator,homing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: System :: Hardware :: Hardware Drivers
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: python-can>=4.0
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Dynamic: license-file

# mksact

**Linear-actuator control for MKS SERVO42D / SERVO57D closed-loop stepper drivers over CAN.**

Home once at startup, then send absolute positions from your own Python code.
Every new target is applied instantly, even while the motor is still moving.

```python
from mksact import Actuator

act = Actuator()           # can0, CAN ID 0x0C, range 20000..150000, full speed
act.start()                # setup + homing + park at 20000
act.move_to(120000)        # returns immediately
act.move_to(40000)         # retargets at once
act.close()
```

> **Linux only.** mksact uses the Linux kernel's SocketCAN driver (via
> [python-can](https://pypi.org/project/python-can/)). It does not run on Windows or macOS.

> ⚠️ **Safety.** This software moves real machinery. Read the
> [Disclaimer](#disclaimer) before use and keep a hardware emergency stop within reach.

---

## Contents

1. [Requirements](#requirements)
2. [Installation](#installation)
3. [Hardware and driver setup](#hardware-and-driver-setup)
4. [Bring up the CAN interface](#bring-up-the-can-interface)
5. [Check everything with `mksact doctor`](#check-everything-with-mksact-doctor)
6. [Quick start](#quick-start)
7. [How homing works](#how-homing-works)
8. [API reference](#api-reference)
9. [Command-line tool](#command-line-tool)
10. [Speed and acceleration](#speed-and-acceleration)
11. [Troubleshooting](#troubleshooting)
12. [Disclaimer](#disclaimer) · [License](#license)

---

## Requirements

| What | Details |
|---|---|
| OS | Linux (Ubuntu, Debian, Raspberry Pi OS, Fedora, ...) with SocketCAN (built into the standard kernel) |
| Python | 3.8 or newer |
| Python packages | `python-can` (installed automatically) |
| System tools | `iproute2` (the `ip` command, present on every normal Linux) |
| CAN adapter | Any SocketCAN adapter: InnoMaker USB2CAN, CANable / candleLight (gs_usb), PEAK PCAN-USB, Raspberry Pi CAN HAT (MCP2515), ... |
| Motor | MKS SERVO42D or SERVO57D with CAN firmware |
| Home switch | NPN / mechanical switch on **IN_1** (pulls low when pressed) |

Optional: `can-utils` (`candump`, `cansend`) for debugging:
`sudo apt install can-utils`

## Installation

Modern Debian / Ubuntu / Raspberry Pi OS block `pip install` into the system
Python ("externally-managed-environment"). Use a virtual environment:

```bash
sudo apt install python3-venv          # once, if not installed
python3 -m venv ~/mksact-env
source ~/mksact-env/bin/activate
pip install mksact
```

Activate the environment (`source ~/mksact-env/bin/activate`) in every new
terminal before using mksact. Check the install:

```bash
mksact --version
```

## Hardware and driver setup

**Wiring**

- Adapter `CAN_H` → driver `CAN_H`, `CAN_L` → `CAN_L`, and connect GND.
- 120 Ω termination at **both** ends of the bus (many adapters have a jumper or DIP switch).
- Home switch between **IN_1** and **GND** on the driver (see the MKS manual, section 2.4).
- Power the driver from its V+ input (12-24 V).

**Driver menu** (buttons + screen on the driver):

| Menu | Set to | Why |
|---|---|---|
| `Cal` | run once, shaft free | encoder calibration |
| `CanRate` | `1M` | must match the bus bitrate |
| `CanID` | e.g. `12` (= 0x0C) | the address you pass as `can_id` |
| `MStep` | `16` | speeds are calibrated for 16 microsteps |
| `Ma` | your motor's rated current | torque |

`Mode` does not need to be set by hand: mksact switches the driver to
`SR_vFOC` (bus FOC mode) automatically.

> CAN ID note: the driver menu shows the ID in **decimal**. ID `12` is `0x0C` in code.

## Bring up the CAN interface

After every boot or replug of the adapter:

```bash
sudo ip link set can0 up type can bitrate 1000000
# or the built-in helper:
mksact can-up
```

Make it permanent (optional, systemd-networkd):

```bash
sudo tee /etc/systemd/network/80-can.network > /dev/null <<'EOF'
[Match]
Name=can0

[CAN]
BitRate=1M
EOF
sudo systemctl enable --now systemd-networkd
```

## Check everything with `mksact doctor`

```bash
mksact doctor --channel can0 --id 0x0C
```

```
mksact 0.1.0 doctor
  [ OK ] operating system: Linux
  [ OK ] python-can 4.x
  [ OK ] can0 exists and is up
  [ OK ] motor 0x0C answers, raw position 1234
  [ OK ] home switch: released
  [ OK ] run status: stopped
All good.
```

Any `[FAIL]` line tells you what to fix.

## Quick start

**Interactive test** (homes, then you type positions):

```bash
mksact run --min 20000 --max 150000
```

**From your own code:**

```python
from mksact import Actuator

act = Actuator(channel="can0", can_id=0x0C, min_pos=20000, max_pos=150000)
act.start()                       # setup + homing + park at min_pos

act.move_to(150000)               # non-blocking
act.move_to(60000)                # retarget immediately

act.move_to(100000, wait=True)    # blocking: returns True when it arrives
print(act.position())

act.close()
```

**With a `with` block** (start and close are automatic):

```python
with Actuator() as act:
    act.move_to(100000, wait=True)
```

More in the `examples/` folder of the source distribution.

## How homing works

`start()` (or `home()`) runs this sequence:

1. Switch the driver to bus FOC mode, use IN_1 for the home switch, enable the motor.
2. Drive toward the switch (`home_ccw=True` → counter-clockwise) at `home_rpm`.
   If the switch is already pressed, the driver first moves off it, then comes back.
3. When the switch triggers, the driver stops and sets **position 0** there.
4. Back off in small steps until the switch releases. This also detects which
   encoder direction points away from the switch, so positions are always
   positive numbers growing away from it.
5. Park at `min_pos`.

The driver's limit function stays enabled: if the switch is hit during normal
moves, the driver stops.

**Units:** raw encoder counts from the switch. One motor turn = 16384 counts
(`mksact.COUNTS_PER_TURN`). Carriage travel per count depends on your lead
screw or belt.

The motor forgets its position when powered off, so call `start()` once each
time your program starts.

## API reference

### `Actuator(...)`

| Parameter | Default | Description |
|---|---|---|
| `channel` | `"can0"` | SocketCAN interface |
| `can_id` | `0x0C` | motor CAN ID |
| `min_pos` | `20000` | lowest allowed position (counts from switch) |
| `max_pos` | `150000` | highest allowed position |
| `speed` | `3000` | move speed in RPM, 0-3000 |
| `accel` | `250` | acceleration 0-255 (higher = faster ramp; 0 = no ramp, jerky) |
| `home_ccw` | `True` | switch is in the counter-clockwise direction |
| `home_trigger_high` | `False` | switch level when pressed (`False` = pulls low) |
| `home_rpm` | `60` | homing speed |
| `home_timeout` | `60` | seconds allowed to reach the switch |
| `verbose` | `True` | print progress messages |

### Methods

| Method | Description |
|---|---|
| `start()` | `open()` + `setup()` + `home()`. Returns the actuator. |
| `move_to(pos, wait=False, timeout=10)` | Absolute move at full speed. Non-blocking by default; a new call retargets instantly. With `wait=True` returns `True` when the move completed. Raises `ValueError` outside `min_pos..max_pos`. |
| `wait_done(timeout=10)` | Block until the current move finishes. |
| `position()` | Current position in counts. |
| `status()` | `"stopped"`, `"accelerating"`, `"full speed"`, `"decelerating"`, `"homing"`, ... |
| `is_moving()` | `True` while moving. |
| `switch_pressed()` | Home switch state. |
| `stop()` | Smooth deceleration to a stop. |
| `emergency_stop()` | Immediate stop (avoid above ~1000 RPM). |
| `home()` | Re-run homing. |
| `disable()` | Release the shaft (homing is lost). |
| `close()` | Smooth stop and close the bus. |

`ActuatorError` is raised when the motor does not answer, refuses a command,
or a move is requested before homing.

## Command-line tool

```text
mksact doctor [--channel can0] [--id 0x0C]     check OS, CAN interface, motor, switch
mksact can-up [--channel can0] [--bitrate N]   bring the CAN interface up (sudo)
mksact run    [--min N] [--max N] [--speed N] [--accel N] [--home-cw]
                                               home, then type positions
mksact --version
```

## Speed and acceleration

For the short travel of a typical axis, **acceleration** decides the move
time more than top speed. The driver ramps speed by 1 RPM every
`(256 - accel) × 50 µs`.

Measured on a SERVO42D, 130 000-170 000 count moves at `speed=3000`:

| `accel` | time for ~170 000 counts | note |
|---|---|---|
| 245 | 1.15 s | very smooth |
| 248 | 1.02 s | |
| 250 | 0.90 s | default: fast, accurate |
| 252 | 0.71 s | overshoot touched the switch when `min_pos` was ~1 200 counts from it |

Raise `accel` in small steps, keep `min_pos` well away from the switch at high
values, and increase the driver current (`Ma`) if moves start to fail.

## Troubleshooting

| Symptom | Fix |
|---|---|
| `CAN interface 'can0' not found` | Adapter not plugged in or not supported; check `ip link show`. |
| `can0 is down` | `mksact can-up` |
| `no reply from motor` | Motor power, CAN_H/CAN_L swapped, missing 120 Ω termination, `CanRate` ≠ bitrate, wrong `can_id`. Watch the bus with `candump can0`. |
| `driver refused to home` | Switch not on IN_1, or wrong `home_trigger_high`. `mksact doctor` shows the switch state; press it by hand and run again - the state must change. |
| Homing runs away from the switch | Use `home_ccw=False` (CLI: `--home-cw`). |
| Move stops early near the switch | The driver's limit function saw the switch: raise `min_pos` or lower `accel`. |
| Rough / noisy motion | Lower `accel` (e.g. 240). Check `MStep = 16`. |
| `externally-managed-environment` on pip install | Use a virtual environment (see Installation). |

## Disclaimer

This software controls physical machinery and is provided **"as is", without
warranty of any kind**. The author, **Durga Prasad Nasika**, and contributors
are **not liable for any damage, injury, or loss** of any kind arising from its
use or misuse. You are solely responsible for the safe design, wiring,
configuration and operation of your system, including an independent hardware
emergency stop. Not affiliated with or endorsed by Makerbase (MKS).
See `DISCLAIMER.md` for the full text.

## License

MIT © 2026 Durga Prasad Nasika. See `LICENSE`.

Protocol details are based on the *MKS SERVO42D/57D CAN User Manual V1.0.9*.
