From 4bc42d6ae90da291b7a801e0cfd755c3e70c6321 Mon Sep 17 00:00:00 2001 From: norman-andrians Date: Sun, 10 Mar 2024 19:13:28 +0700 Subject: [PATCH] Open API with clent --- package-lock.json | 1 + package.json | 1 + src/handlers/socketHandler.ts | 8 +++++--- src/index.ts | 4 ++++ test/serial/servo.ts | 2 +- 5 files changed, 12 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index deb0bce..2c4d932 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "@serialport/bindings": "^9.2.9", "@serialport/list": "^12.0.0", "chalk": "^4.1.2", + "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.18.3", "firmata": "^2.3.0", diff --git a/package.json b/package.json index 0afa5a5..1fb8716 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "@serialport/bindings": "^9.2.9", "@serialport/list": "^12.0.0", "chalk": "^4.1.2", + "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.18.3", "firmata": "^2.3.0", diff --git a/src/handlers/socketHandler.ts b/src/handlers/socketHandler.ts index 68c73e8..cd08ce5 100644 --- a/src/handlers/socketHandler.ts +++ b/src/handlers/socketHandler.ts @@ -1,20 +1,22 @@ import { Socket } from "socket.io"; +import { Pin } from "johnny-five"; import { board } from "../setup"; export default (socket: Socket) => { console.log(`${socket.id} | ${socket.client.request.headers.host} | Joined`); - socket.on("control-servo", (p: string, ang: string) => { + socket.on("servo", (p: string, ang: string) => { const pin = Number.parseInt(p); const angle = Number.parseInt(ang); + board.pinMode(pin, Pin.SERVO); board.servoWrite(pin, angle); console.log(socket.id, pin, angle); }) - socket.on("read-photoresistor", (pin: string) => { + socket.on("set-photoresistor", (pin: string) => { board.analogRead(pin, (value) => { - socket.emit("read-photoresistor", value); + socket.emit("photoresistor", value); console.log(socket.id, "A"+pin, value); }); }) diff --git a/src/index.ts b/src/index.ts index 9a7d00c..1fd8eea 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,6 @@ import http from 'node:http'; import express from 'express'; +import cors from 'cors'; import { Server } from 'socket.io'; import chalk from 'chalk'; @@ -23,6 +24,9 @@ const host: string = 'localhost'; const port: number = 3000; // Express middleware +app.use(cors({ + origin: "*" +})); app.use(express.json()); app.use(express.static('client')); diff --git a/test/serial/servo.ts b/test/serial/servo.ts index 03a949d..0447bd5 100644 --- a/test/serial/servo.ts +++ b/test/serial/servo.ts @@ -2,7 +2,7 @@ import { Board, Pin, PinMode } from "johnny-five"; const board: Board = new Board({ port: '/dev/ttyUSB0', - debug: false, + debug: true, repl: false });