nMotion Matrix
WebSocket Command Guide ยท by nChip
www.nchip.in โ†—

WebSocket Command Guide

Version 1.0Target: Motor Tile ControllerProtocol: WebSocket (RFC 6455)
Purpose: This guide documents the WebSocket command protocol used to control the 4ร—4 stepper matrix (Motor Tile). It is intended for developers integrating Grasshopper, Rhino, Python, or other external tools with the Motor Tile Controller.

1. System Overview

ComponentRole
ControllerWireless command hub, wired bus master
Motor BoardsIndividual motor control, position sensing, addressable 0โ€“15
Wired Bus ModulesSignal transceivers between Controller and Motor Boards
Browser / GrasshopperWebSocket client sending commands

Network Details

ParameterValue
Network ModeStation (connects to existing Wi-Fi network)
WebSocket URLws://<CONTROLLER_IP>:81
Web Control Pagehttp://<CONTROLLER_IP>/
Wireless Discovery NameMT_A0-<CONTROLLER_IP>
Bus Speed9600, 8N1

1.1 Create the Access Point (Mobile Hotspot)

The Controller is hard-coded to connect to a Wi-Fi network with fixed credentials. Before powering on the Controller, you must create this network using a mobile hotspot.

ParameterValue
Hotspot SSIDAP
Hotspot Password56784321
SecurityWPA2-PSK (recommended)
Band2.4 GHz (required โ€” 5 GHz is not supported)

Steps to create the hotspot:

  1. On your mobile phone, open Settings โ†’ Hotspot & Tethering (or Personal Hotspot on iOS).
  2. Set the Network Name (SSID) to exactly AP โ€” case-sensitive.
  3. Set the Password to exactly 56784321.
  4. Ensure the hotspot is using 2.4 GHz band (some phones let you choose; on iOS, enable Maximize Compatibility).
  5. Turn the hotspot ON.
Important: The SSID and password are hard-coded in the Controller firmware. Any mismatch โ€” even a single character โ€” will prevent the Controller from connecting. Always use exactly AP and 56784321.

1.2 Power On the Controller

Once the hotspot is active, power on the Motor Tile Controller. It will:

  1. Boot and initialise the wired bus.
  2. Automatically scan for and connect to the Wi-Fi network named AP.
  3. Obtain an IP address from the mobile hotspot (typically in the 192.168.x.x range).
  4. Start its WebSocket server on port 81 and its web page on port 80.
  5. Broadcast its IP over the wireless discovery name MT_A0-<IP>.

1.3 Connect Your Computer to the Same Network

For a computer (Windows / macOS / Linux) to send commands to the Controller, it must be on the same network โ€” i.e., connected to the same mobile hotspot you created in step 1.1.

Steps:

  1. On your computer, open Wi-Fi settings.
  2. Select the network named AP from the list of available networks.
  3. Enter the password 56784321.
  4. Wait for the connection to establish (the computer will receive its own IP from the hotspot).
  5. Verify connectivity by opening a browser and navigating to http://<CONTROLLER_IP>/.
Note: Some mobile hotspots have a limit on connected devices (typically 5โ€“10). If your Controller and computer cannot both connect, check the hotspot settings for a device limit, or use a dedicated Wi-Fi router in Access Point mode instead.

1.4 Finding the Controller IP Address

The Controller's IP address can be obtained using any one of the following methods. You do not need to use all of them โ€” pick whichever is most convenient for your setup.

  1. Wireless Scan โ€” open any Bluetooth scanner app, look for MT_A0-192.168.x.x. The IP is embedded in the discovery name.
  2. Serial Monitor โ€” connect via USB at 115200 baud. The IP is printed on boot.
  3. Router / Hotspot Admin โ€” check the connected devices list for hostname MT_A0.
  4. Mobile Hotspot Client List โ€” most phones show connected devices under Hotspot settings; look for MT_A0.
Tip: If you use method 1 (Wireless Scan), the full discovery name itself contains the IP โ€” for example, MT_A0-192.168.1.45 means the Controller is at 192.168.1.45.

2. Connecting via WebSocket

Open a WebSocket connection to:

ws://<CONTROLLER_IP>:81

On successful connection, the Controller sends a welcome message:

Connected to Motor Tile

2.1 Verify the Connection with Reference Tools

Before integrating with your own software, confirm that the Controller is reachable and responding. Use the following online tools:

Test procedure:

  1. Open the Standalone WebSocket Tester in a browser.
  2. Enter the WebSocket URL: ws://<CONTROLLER_IP>:81.
  3. Click Connect. The status should change to Connected.
  4. Send the query command: ?
  5. You should receive a response like OK ? followed by the address digits of all connected Motor Boards (e.g., 0, 1, 2โ€ฆ).
  6. Send a test move: M 0 1 1500 400
  7. You should receive OK M and the motor should physically move.
Hardware Confirmation: If you see OK M in the log and the motor moves, the Controller is confirmed working end-to-end. You can now proceed with your own integration.

2.2 Connection Requirements

  • Client and Controller must be on the same network / subnet (see section 1.3).
  • Port 81 must be reachable (no firewall blocking).
  • Mobile hotspots must not have "client isolation" enabled.
Important: Mobile Chrome blocks WebSocket connections from file:// pages. Always load the control page from http://<CONTROLLER_IP>/ on mobile devices.

3. Command Reference

All commands are sent as plain text UTF-8 strings over the WebSocket. No framing, no length prefix, no termination character required.

3.1 Motor Movement

Format:

M <addr> <dir> <delay> <steps>
FieldTypeDescriptionRange
MliteralMove command prefixโ€”
addrhex charMotor address0โ€“9, Aโ€“F (0โ€“15)
dircharDirection1=Clockwise, 0=Counter-clockwise
delayintStep delay (ยตs)1000โ€“65535
stepsintNumber of steps1โ€“65535

Examples:

M 0 1 1500 800     โ†’ Motor 0, CW,  1500 ยตs delay, 800 steps
M 5 0 2000 1200    โ†’ Motor 5, CCW, 2000 ยตs delay, 1200 steps
M A 1 1200 400     โ†’ Motor 10, CW,  1200 ยตs delay, 400 steps

Response: OK M

3.2 Homing

CommandActionResponse
H <addr>Home a specific motor (uses onboard position sensor)OK H
HAHome all motors (broadcast)OK HA

Examples:

H 0     โ†’ Home motor 0
H F     โ†’ Home motor 15
HA      โ†’ Home all motors
Homing takes 2โ€“10 seconds per motor. The Motor Board sends RDY when done. Wait ~5 seconds before sending the next command.

3.3 Dynamic Home Management

In addition to the factory absolute zero, Motor Boards can be taught a custom "Zero" position. This is useful for aligning tiles that have mechanical offsets or specific physical starting points.

CommandActionResponse
T <addr>Teach: Saves the motor's current physical position as the new Home.SAVED_T
U <addr>Unset: Clears the custom home and reverts to the factory absolute zero.SAVED_U
G <addr>Get: Queries the current saved home status.HOME:VALID:XXXX or HOME:FACTORY:0

Examples:

T 0     โ†’ Teach motor 0's current position as home
U 5     โ†’ Unset custom home for motor 5 (revert to factory)
G A     โ†’ Query motor 10 to see if it has a custom home
When a custom home is taught, the motor will calculate the shortest path back to this exact encoder tick during future H or HA commands.

3.4 Query

CommandActionResponse
?Query all Motor Board addresses on the busHex digit(s) e.g. 0, 5, A

3.5 System Reset

CommandActionResponse
XSoftware reset all Motor BoardsOK X
Warning: X resets every board on the bus. Use only when the system is idle.

4. Response Codes Summary

ResponseMeaning
Connected to Motor TileWebSocket handshake succeeded
OK MMotor move command accepted
OK HHome command accepted
OK HAHome-all accepted
OK XReset command accepted
OK ASCIIGeneric passthrough command forwarded
OK ?Query sent (no board replied within 300 ms)
ERR MMalformed move command
SAVED_TCustom home taught successfully
SAVED_UCustom home unset, reverted to factory
HOME:VALID:XXXXCurrent custom home angle (e.g., 1234)
HOME:FACTORY:0No custom home saved
RDY / HOMEFAILFrom Motor Board (visible in Serial Monitor only)

5. Grasshopper Integration

5.1 Architecture

Grasshopper (Rhino)
       โ”‚
       โ”‚  HTTP POST (localhost:8080)
       โ–ผ
Python Bridge Server  โ”€โ”€โ”€โ”€ WebSocket (ws://CONTROLLER_IP:81) โ”€โ”€โ”€โ”€โ–บ  Controller
       โ–ฒ
       โ”‚  HTTP response (status)
       โ”‚
Grasshopper Python Component

The Python bridge is required because Grasshopper runs on a single UI thread and cannot safely block on WebSocket replies.

5.2 Python Bridge Server

import asyncio, websockets
from http.server import HTTPServer, BaseHTTPRequestHandler

CONTROLLER_IP = "192.168.x.x"   # โ† replace
HTTP_PORT = 8080

async def send_to_controller(message):
    try:
        async with websockets.connect(f"ws://{CONTROLLER_IP}:81") as ws:
            await ws.send(message)
            try:
                resp = await asyncio.wait_for(ws.recv(), timeout=0.5)
                print(f"Controller: {resp}")
            except asyncio.TimeoutError:
                pass
    except Exception as e:
        print(f"WS error: {e}")

class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        n = int(self.headers['Content-Length'])
        cmd = self.rfile.read(n).decode()
        print(f"GH โ†’ {cmd}")
        asyncio.run(send_to_controller(cmd))
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"OK")

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"Bridge running")

HTTPServer(('0.0.0.0', HTTP_PORT), Handler).serve_forever()

Run: python bridge.py

5.3 Grasshopper Python Component

import urllib.request

if send and command:
    data = command.encode('utf-8')
    req = urllib.request.Request(
        "http://localhost:8080",
        data=data, method='POST')
    try:
        with urllib.request.urlopen(req, timeout=1) as r:
            status = r.read().decode()
    except Exception as e:
        status = f"ERR: {e}"
else:
    status = "IDLE"

Inputs: command (String), send (Boolean)
Output: status (String)

5.4 Grasshopper Command Examples

ActionCommand String
Move motor 0 CW, 800 stepsM 0 1 1500 800
Move motor 5 CCW, 1200 stepsM 5 0 2000 1200
Home motor 3H 3
Home allHA
Query bus?
Reset allX

5.5 Generating Patterns in Grasshopper

Build a list of command strings using standard GH components and send them sequentially. Example using a Series component + Format to generate moves:

M {0} 1 1500 800   โ†’  for addr = 0..15

Feed each string into the Python component, toggling send with a Button or Trigger.

6. Testing Guide

  1. Create the mobile hotspot (SSID: AP, password: 56784321) โ€” see section 1.1.
  2. Power the Controller and Motor Boards. Wait for the Controller to connect to the hotspot.
  3. Connect your computer to the same hotspot โ€” see section 1.3.
  4. Confirm the Controller IP using any one method from section 1.4.
  5. Verify the connection using the Standalone WebSocket Tester โ€” see section 2.1.
  6. Send ? โ€” confirm you receive the address replies from all boards.
  7. Send M 0 1 1500 400 โ€” confirm the motor moves and you receive OK M.
  8. Start the Python bridge on your PC.
  9. Open Grasshopper with the Python component.
  10. Send M 0 1 1500 400 from Grasshopper โ€” the motor should move.

6.1 Online Reference Tools

7. Troubleshooting

SymptomCauseFix
Controller never connects to hotspotSSID or password mismatchVerify SSID is exactly AP and password is 56784321 (case-sensitive)
Controller connects but computer cannot reach itComputer on different networkJoin the same hotspot on the computer โ€” see section 1.3
Hotspot rejects ControllerDevice limit reached or 5 GHz bandIncrease device limit or switch hotspot to 2.4 GHz
[0] WS DisconnectedPage loaded from file:// on mobileOpen from http://<CONTROLLER_IP>/
WebSocket never connectsClient isolation on hotspotDisable client isolation in hotspot settings
Commands send but motors don't moveBus A/B swapped or GND missingSwap A/B, ensure common GND
Motor moves wrong directionDirection wiring reversedSwap motor coil A/B or use opposite dir value
Only some motors respondAddress mismatchVerify DIP switches match command address
Random resets during patternsBus noise / no terminationAdd 120 ฮฉ termination at both bus ends
Wireless name shows -NOIPNetwork failed to connectCheck SSID/password on hotspot (must be AP / 56784321)

8. Safety Notes

  • Never send motor commands while a homing sequence is in progress.
  • Always issue HA on power-up before running patterns.
  • Use X only when all motors are idle.
  • Do not exceed step delay below 1000 ยตs โ€” may cause motor stall.
  • Keep the bus cable away from motor power lines to reduce noise.