# W2

Week 2. Cross-Device Interaction (WebSocket)

## 1. Mobile Modality & Parametric Interface

**Mobile Modality: The Phone as an Instrument**

- Think of the classic "2001: A Space Odyssey" scene: a bone becomes a satellite. This represents the evolution of a tool.
  - [2001: A Space Odyssey (1968) - From Bone to Satellite Scene (1/6) | Movieclips](https://www.youtube.com/watch?v=avjdKTqiVvQ)
- Steve Jobs introducing the iPhone in 2007 was a similar moment. It put a powerful new tool in our hands.
  - [Steve Jobs introduces iPhone in 2007](https://youtu.be/MnrJzXM7a6o?si=eriyVK-ald9RRGN9&t=274)
- The best tool we have is our fingers. The iPhone/smartphone is an instrument played by our fingers.
- **Our Goal**: To build interfaces that respond to this "performance."
  - Instrumental Interface

**Two Types of Interaction**

- **1. Semantic Interaction (Meaning-based)**
  - **What it is**: Discontinuous, categorical. You make a clear choice.
  - **Examples**: Clicking a button, selecting an option from a menu.
  - **Used in**: Most practical interfaces (apps, websites).
- **2. Phenomenological Interaction (Experience-based)**
  - **What it is**: Continuous, flowing.
  - **Examples**: Moving your body, dragging your finger, scrolling.
  - **Used in**: Interactive art, games.
**Parametric Web Interface**

- **What is it?** An interface where your mobile interactions (inputs) are used to change _parameters_ (variables).
- Think of it like playing an instrument: your actions change the sound. Here, your actions change the _context_, the _time_, or the _space_.
- **Example: Changing Time**
  - _Semantic way_: Typing "8:00 AM" in a box.
  - _Phenomenological way_: Dragging a dial, like the iOS Alarm clock. (iOS Wheel Picker - inspired from Las Vegas)
  - _Question_: Which is more intuitive? More fun?
- **Example: Changing Season**
  - _Semantic way_: 4 separate buttons ("Spring," "Summer," "Fall," "Winter").
  - _Phenomenological way_: A continuous X-axis or Y-axis slider that blends between seasons.
- **Example: Changing Job**
  - _Semantic way_: A dropdown list of pre-set jobs.
  - _Phenomenological way_: A "blurry" selection space where you can slide between different job categories.

**Input Materials (The "Keys" of Your Instrument)**

- **I. Selection / Navigation (Broad Control)**
  - Scrolling
  - Swiping (e.g., Tinder-style card swipe)
  - Zoom-in / Zoom-out
- **II. Fine-Tuning (Precise Control)**
  - Finger-Skating / Sketching (drawing on the screen)
  - Set of Togglers (on/off switches)
  - Set of Sliders
  - Set of Buttons
  - Accelerometer (tilting the phone)
  - Voice/Speech
    - _Semantic_: Speech-to-Text (what you say)
    - _Non-Semantic_: Volume size (how loud you are)
  - Camera Tracking (Eye tracking, Object detection)
  - Rotating & Zooming an object

## 2. Multi-Device Interaction

- Multi-Device Interaction: Using two or more devices
  - Ex. Mobile: Input, Screen/Laptop: Output
- Ex. Banpo-Xism: multiple mobiles (input) → 1 media wall + 3 vertical TVs (output)

**Single Device vs. Multi-Device**

- **Single Device (e.g., Laptop only)**
  - **Structure**: User Input (Mouse/Keyboard) → Parameter Conversion → Visual Output
  - **Inputs**: Mouse click duration, mouse move velocity/path, keyboard typing speed.
  - **Artistic Strategy**: "Verfremdungseffekt" (Defamiliarization effect) – making a normal interaction (like typing) create an unexpected result.
- **Multi-Device Web Artwork (Our Focus)**
  - **Input Device**: Mobile (iOS / Android)
  - **Output Device**: Laptop (1920 x 1080 screen)
  - **Why?** Phone interactions (touch, tilt) have a different _phenomenological_ feel than laptop interactions (mouse, keyboard).

**Creating Your 'Visual Instrument'**

- This is the core design structure for your project.
- **The Flow**: Mobile Input → Parameter Conversion + System Rules → Laptop Output
- **Which Inputs to Use? (Mobile)**
  - Button 'Tab'
  - Finger 'Swipe'
  - Zoom, Pinch, Rotate
  - Voice Input, Camera Input
  - TTS/STT (Text-to-Speech, Speech-to-Text)
  - LLM API (sending prompts to an AI)
  - Decibel (sound level)
  - External Data (weather, traffic, stock prices)
- **Which Outputs to Use? (Laptop)**
  - Creative Coding (Canvas, GLSL)
  - Text / Typography (changing font, size, layout)
  - Collage of Images / Videos
  - 3D Graphics (e.g., using Three.js)
  - Audio Elements (e.g., using Tone.js)

## 3. Socket.io

- WebSocket: Bi-directional real-time communication btw client/server, enabling real-time inter-device interaction in web applications
- Socket.io: Javascript library, high-level abstraction of WebSocket, beginner-friendly (Automatic reconnection, Default fallback option)
- Strategy
  - Let's say we have Client A (Interaction Input) and Client B (Interaction Output)
  - Client A sends a message → the relay server forwards it to all other clients in the same room → Client B receives it
- Already installed in the template: `socket.io` (server), `socket.io-client` (browser)

**How it is structured in this repo**

- `socket-server.mjs`: the relay server. One file, port 4000
  - `join(room)`: A device joins a room
  - `message({ type, data })`: Forwarded as-is to every other device in the same room
  - It is not part of Next.js. It is a separate Node process (that's why Vercel can't host it, see [§7](#7-socket-deployment))
- `hooks/shared/useSocket.ts`: the client-side hook
  - `const { send, connected } = useSocket(room, onMessage)`
  - `send(type, data)`: sends a message to the room
  - `onMessage(type, data)`: called for every message from the other devices
  - Address: `NEXT_PUBLIC_SOCKET_URL` if set, otherwise the current host at port 4000
- Route convention for one experiment
  - Both call `useSocket("<name>", ...)` with the same room name

  | | File | Address |
  |---|---|---|
  | Client A · Mobile | `app/experiments/w2/<name>/mobile/page.tsx` | localhost:3000/experiments/w2/name/mobile |
  | Client B · Screen | `app/experiments/w2/<name>/screen/page.tsx` | localhost:3000/experiments/w2/name/screen |

**Overall workflow**

The five numbers of the diagram:

1. Screen page opens: `useSocket("drawing", onMessage)` connects to the relay and joins the room
2. Mobile page opens: the same
3. Mobile: `send("move", { x, y })`
4. Relay: forwards `{ type: "move", data: { x, y } }` to the rest of the room
5. Screen: `onMessage("move", { x, y })` is called. Update your state, draw

- This is the base code. You can make it more complicated/add modularity on top of it
- What will be your speculative inter-device interaction? How will you use this technology to design your interactive/immersive audio-visual design practice?
- You can also connect Socket.io/WebSocket with TouchDesigner or Unreal (W3)

## 4. Socket.io Examples

**In this repo** ([/experiments/w2](/experiments/w2))

1. Drawing: touch move on mobile → line on screen ([mobile](/experiments/w2/drawing/mobile) · [screen](/experiments/w2/drawing/screen))
2. Signature
   - Live: sign on mobile → the signature appears on screen as you write ([mobile](/experiments/w2/signature/live/mobile) · [screen](/experiments/w2/signature/live/screen))
   - Contracts: sign on mobile, send → the signature lands on 40 documents ([mobile](/experiments/w2/signature/contracts/mobile) · [screen](/experiments/w2/signature/contracts/screen))
3. Typing: type on mobile → the sentence is sent in eight chat apps, every room answers ([mobile](/experiments/w2/typing/mobile) · [screen](/experiments/w2/typing/screen))
4. 3D (Three.js)
   - Rotate: drag on mobile → 3D shape turns on screen ([mobile](/experiments/w2/3d/rotate/mobile) · [screen](/experiments/w2/3d/rotate/screen))
   - Particles: two fingers on mobile, pulled apart → a sphere breaks into 40,000 particles ([mobile](/experiments/w2/3d/particles/mobile) · [screen](/experiments/w2/3d/particles/screen))
   - Togglers: finger-skating over 40 switches on mobile → 40 wave sources in a simulated surface ([mobile](/experiments/w2/3d/togglers/mobile) · [screen](/experiments/w2/3d/togglers/screen))
   - City: three modes on mobile (Settings, Navigate, Statistics) → the parameters, the camera and the statistics of a generated city, with live sound ([mobile](/experiments/w2/3d/city/mobile) · [screen](/experiments/w2/3d/city/screen))
- Examples that need the mobile's sensors (tilt, camera) need HTTPS: [§5](#5-mobile-https-debugging), then [§6](#6-mobile-sensors)

**XD Lab works**

## 5. Mobile HTTPS Debugging

- Mobile Debugging: Hard
- Cross-Device (Mobile + Desktop) Debugging: VERY HARD

### A1. Local Network Connection

Open your laptop's page on your mobile. Keep `pnpm dev` running.

- `localhost` means "this device itself". On your laptop, localhost:3000 is your laptop. Typed on your mobile, localhost is the mobile, and nothing runs there
- So the mobile needs your laptop's address on the Wi-Fi: its IP address. The Wi-Fi router gives one to every device. It looks like 192.168.0.12 or 10.0.0.12
- Find your laptop's IP address. Two ways:
  1. In the Terminal
     - **macOS** or **Linux**: `ifconfig | grep "inet "`
     - **Windows**: `ipconfig`
     - Take the address that looks like 192.168.x.x or 10.x.x.x. Not 127.0.0.1: that one is localhost
  2. Ask your AI agent: "What is my computer's local IP address?" It runs the command and tells you
- Connect the mobile and the laptop to the **same Wi-Fi**. If the school Wi-Fi blocks device-to-device traffic, use your mobile's hotspot
- On the mobile's browser, type `http://<YOUR_IP>:3000` and the path. For example: http://192.168.0.12:3000/experiments/w2/drawing/mobile
- On the laptop, open the screen page as before: localhost:3000/experiments/w2/drawing/screen

### A2. HTTPS for Local Dev: `pnpm dev:mobile`

**Why HTTPS**

- `http://`: what the page and the browser send each other is not encrypted. Anyone on the same network can read it
- `https://`: it is encrypted. Only the page and the browser can read it
- Camera, microphone and motion sensors show you and the room you are in. So browsers give them only to pages opened with `https://`
- One exception: `localhost`. Nothing leaves your own device there. That is why the camera worked on your laptop in W1 with `pnpm dev`
- Your mobile opens the page with `http://192.168.x.x`. That is not localhost, and not https. So the camera and the sensors are blocked, until you serve your page over https

**How**

1. Stop the server that is running: press `Ctrl + C` in the terminal where `pnpm dev` runs
2. Start it again with `pnpm dev:mobile`. The same two servers (3000 and 4000), now over https. The first time it may ask for your password. It prints the address for your mobile
3. On the mobile, open `https://<YOUR_IP>:3000` and the path. A warning page appears ("Your connection is not private")
   - This is **normal**. The certificate that proves "this is really that site" was made by your own laptop, so the mobile cannot check it
   - Tap **"Advanced"** → **"Proceed (unsafe)"**
4. Do the same for the relay: open `https://<YOUR_IP>:4000` on the mobile and pass the warning. You should see "socket relay ok"
   - If you skip this: the page loads but nothing arrives on the screen
5. On the laptop, open https://localhost:3000

You only need to pass the warnings once per device.

### A3. Remote Debugging (iOS vs. Android)

See your mobile's console.log() messages, DOM and network requests on your computer's screen.

#### Android (Chrome Debugging)

1. **On Your Android Device:** Enable "Developer Options" (this is usually hidden; search how to enable it for your specific phone). Inside Developer Options, toggle on "USB Debugging".
2. **On Your Computer:** Connect your phone to your computer with a USB cable.
3. Open desktop **Chrome** and type `chrome://inspect#devices` into the address bar.
4. You should see your device and any open tabs. Click "Inspect" on the tab you want to debug.
5. A full DevTools window will open, allowing you to inspect your mobile browser session.

#### iOS (Safari Web Inspector)

**Note:** This process requires a **Mac**.

1. **On Your iPhone:** Go to Settings > Safari > Advanced and toggle on "Web Inspector".
2. **On Your Mac:** Open **Safari**. Go to Safari > Preferences > Advanced and tick the box at the bottom: "Show Develop menu in menu bar".
3. **Connect:** Connect your iPhone to your Mac with a USB cable.
4. On your Mac's Safari, click the new "Develop" menu. You should see your iPhone's name.
5. Hover over your iPhone's name to see a list of open tabs. Click the tab you wish to debug to open a Web Inspector window.

## 6. Mobile Sensors

- Camera, microphone and motion sensors work only on HTTPS (or localhost): `pnpm dev:mobile` ([A2](#a2-https-for-local-dev-pnpm-devmobile))
- They start after a user tap. The browser asks for permission

| | Input | Browser API | Example |
| --- | --- | --- | --- |
|  | Tilt | `deviceorientation` event → `alpha`, `beta`, `gamma` (degrees) | [w2/tilt](/experiments/w2/tilt/screen) |
|  | Shake | `devicemotion` event → `acceleration` | |
|  | Microphone | `navigator.mediaDevices.getUserMedia({ audio: true })` | [w1/video](/experiments/w1/video) |
|  | Camera | `navigator.mediaDevices.getUserMedia({ video: true })` | [w2/camera-slit-scan](/experiments/w2/camera-slit-scan/screen) · [w1/glsl/creation-webcam](/experiments/w1/glsl/creation-webcam) |

**Tilt (accelerometer)**

- iOS: `DeviceOrientationEvent.requestPermission()` inside a tap handler. Android: no permission pop-up

```tsx
async function start() {
  // iOS only: ask for permission (must be called from a tap)
  const eventClass = DeviceOrientationEvent as unknown as { requestPermission?: () => Promise<string> };
  if (eventClass.requestPermission) await eventClass.requestPermission();

  window.addEventListener("deviceorientation", (event) => {
    const x = (event.gamma ?? 0) / 45; // left / right
    const y = (event.beta ?? 0) / 45; // front / back
    send("tilt", { x, y });
  });
}
```

- Full code: `app/experiments/w2/tilt/`

**Examples (HTTPS)**

1. Tilt: mobile tilt → ball on screen ([mobile](/experiments/w2/tilt/mobile) · [screen](/experiments/w2/tilt/screen))
2. Camera Slit-Scan: mobile camera → slit-scan on screen ([mobile](/experiments/w2/camera-slit-scan/mobile) · [screen](/experiments/w2/camera-slit-scan/screen))

## 7. Socket Deployment

- Deployment ([W1 §12](/lecture-materials/w1#12-deployment)): your app moves from localhost to a public address, on Vercel
- A multi-device piece is two programs ([§3](#3-socketio)): the Next.js app (port 3000) and the relay, `socket-server.mjs` (port 4000)
- Vercel runs the Next.js app. It cannot run the relay
  - Vercel is serverless: it runs your code only for the moment a page is requested, then stops
  - The relay has to stay on all the time, holding the connection to the mobile and to the screen
- So the relay needs a computer that stays on. Two choices

**1. Your laptop**

- What we did in class: `pnpm dev` (or `pnpm dev:mobile`) runs both programs on your laptop, and the mobile joins over the same Wi-Fi ([§5](#5-mobile-https-debugging))
- No deployment. It works only on that Wi-Fi

**2. A server on the internet**

- The app goes on Vercel, as in W1. The relay goes on a hosting service that keeps a program running: Render or Railway
  - AWS EC2 is another example. Banpo-Xism runs its relay there
- Then anyone can open your piece, from any network
- For the final in the Black Room, deploy this way

**Telling the app where the relay is**

- On your laptop, the app and the relay were on the same computer. The page did not need an address: it connected to "port 4000 of this computer"
- After deployment they are in two different places. The app is on Vercel, the relay is on Render, and each has its own address. The app does not know where the relay is, so you have to tell it
- You tell it with an environment variable on Vercel. An environment variable is a value you do not write in the code: you type it into the service's settings as "name = value", and the app reads it from there
  - Name: `NEXT_PUBLIC_SOCKET_URL`. The template's `useSocket` looks for the relay's address under this name
  - Value: the relay's address that Render gives you, for example `https://my-relay.onrender.com`

**Step by step: Render**

1. The app: push your repo to GitHub and deploy it on Vercel ([W1 §12](/lecture-materials/w1#12-deployment))
2. The relay: https://render.com → sign up → **+ New > Web Service** → select the same GitHub repo → **Connect**
3. Fill in the form. The Start Command is what makes this service run the relay, not the app
   - Language: `Node`
   - Build Command: `pnpm install`
   - Start Command: `node socket-server.mjs`
   - Compute: `Free`
   - Environment Variables: `NODE_VERSION` = `24`
4. Deploy. Render gives the relay an address, `https://<name>.onrender.com`. Open it: it shows "socket relay ok"
5. Register this address on Vercel as an environment variable
   - On Vercel, open your project → **Settings** → **Environment Variables**
   - Type `NEXT_PUBLIC_SOCKET_URL` into Key and `https://<name>.onrender.com` into Value, then press **Save**
   - Deploy again: **Deployments** → the **⋯** of the latest deployment → **Redeploy**. The value goes into the app when it is deployed, so it only takes effect after a new deployment
6. Open `/screen` on the laptop and `/mobile` on the mobile, both on the Vercel address

- Free plan: the relay sleeps after 15 minutes without use. The next connection takes about one minute
- Docs: [Your first deploy](https://render.com/docs/your-first-deploy) · [WebSockets](https://render.com/docs/websocket) · [Free plan](https://render.com/docs/free)

**Step by step: Railway**

1. The app: on Vercel, as above
2. The relay: https://railway.com → sign up with GitHub → **New Project** → **GitHub repo** → select the same repo
3. Service → **Settings** → Custom Start Command: `node socket-server.mjs` → **Deploy**
4. Service → **Settings** → **Networking** → **Generate Domain**. Open `https://<name>.up.railway.app`: it shows "socket relay ok"
5. Register this address on Vercel as an environment variable: same as step 5 above, with the Railway address

- Trial: $5 credit, 30 days. After that $5/month
- Docs: [Quick start](https://docs.railway.com/quick-start) · [Build and start commands](https://docs.railway.com/builds/build-and-start-commands) · [Domains](https://docs.railway.com/networking/domains/working-with-domains)

## 8. Homework: Web Assignment 2

**Build a Mobile-to-Laptop Interactive Experience.** Due to Web 3 (11/16).