Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Add orca-service #2492

Merged
merged 3 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/server/services/machine/ConnectionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ import { ConnectionType } from './types';
import SacpChannelBase from './channels/SacpChannel';
import { L2WLaserToolModule } from '../../../app/machines/snapmaker-2-toolheads';

import { openServer, closeServer } from './orca-service'

const log = logger('lib:ConnectionManager');

const ensureRange = (value, min, max) => {
Expand Down Expand Up @@ -127,13 +129,22 @@ class ConnectionManager {
public onConnection = (socket: SocketServer) => {
sstpHttpChannel.onConnection();
this.scheduledTasksHandle = new ScheduledTasks(socket);

//开启服务
openServer().then(res=>{
log.info(`service open success: ${res}`);
}).catch((e)=>{
log.info(`service open failed: ${e}`);
});

};

// TODO: Refactor this
public onDisconnection = (socket: SocketServer) => {
sstpHttpChannel.onDisconnection();
textSerialChannel.onDisconnection(socket);
this.scheduledTasksHandle.cancelTasks();
closeServer();
};

/**
Expand Down Expand Up @@ -568,12 +579,11 @@ class ConnectionManager {
if (!options.filePath.startsWith('/')) {
options.filePath = path.resolve(`${DataStorage.tmpDir}/${options.filePath}`);
}

if (!options.targetFilename) {
options.targetFilename = path.basename(options.filePath);
}

log.info(`Upload file to controller... ${options.filePath} to ${options.targetFilename}`);
log.info(`Upload file to controller...2 ${options.filePath} to ${options.targetFilename}`);

const success = await (this.channel as FileChannelInterface).uploadFile(options);
if (success) {
Expand Down
150 changes: 150 additions & 0 deletions src/server/services/machine/orca-service/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import * as Formidable from 'formidable';
import { connectionManager } from '../ConnectionManager';
import SocketServer from '../../../lib/SocketManager';
import SocketEvent from '../../../../app/communication/socket-events';
import DataStorage from '../../../DataStorage';
import logger from '../../../lib/logger';

const log = logger('lib:ConnectionManager');

const http = require('http');

const io = new SocketServer();

function checkConnection() {
log.info(`connectionManager: ${connectionManager}`);

if (connectionManager?.machineInstance?.id) {
return true;
}
return false;
}

async function sendGcodeFile(file): Promise<any> {
if (!checkConnection()) {
return {
err: true,
text: 'No machine connection',
}
}

return new Promise((resolve, reject) => {
connectionManager.uploadFile(io, {
filePath: file.newFilename,
targetFilename: file.originalFilename,
});

const event = SocketEvent.UploadFile;
io.on(event, (data) => {
resolve(data);
});
});
}

let server;
let SERVER_PORT = 65526;
let SERVER_IP = '127.0.0.1';
const Version = '0.0.1';
const printer = { ID: '123', IP: SERVER_IP + ':' + SERVER_PORT, Sacp: true };
const maxMemory = 64 * 1024 * 1024; // 64MB

function openServer() {
// 防止重复开启
closeServer();

server = http.createServer();
server.on('request', (req, res) => {
const start = new Date().getTime();
const connectionStatus = `machine connection: ${checkConnection()}`;
log.info(`connectionStatus: ${connectionStatus}`);

res.on('finish', () => {
const end = new Date().getTime();;
const duration = end - start;
log.info(`Request ${req.method} ${req.url} completed in ${duration}ms`);
});

if (req.url === '/') {
const protocol = printer.Sacp ? 'SACP' : 'HTTP';
const resp = `sm2uploader ${Version}
printer id: ${printer.ID}
printer ip: ${printer.IP}
machineConnection: ${checkConnection()}
protocol: ${protocol}`;
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(resp);
} else if (req.url === '/api/version') {
const respVersion = JSON.stringify({ api: '0.1', server: '1.2.3', text: 'OctoPrint 1.2.3/Dummy', machineConnection: checkConnection() });
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(respVersion);
} else if (req.url === '/api/files/local') {
if(!checkConnection()) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify({ text: 'No machine connection' }));
return;
}
const form = new Formidable.IncomingForm({
maxFileSize: maxMemory,
uploadDir: DataStorage.tmpDir // set temporary file path
});
form.parse(req, async (err, fields, files) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify({ err, text: 'Internal Server Error' }));
return;
}

const file: Formidable.File = files.file;
log.info(`file: ${file}`);
if (!file) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify({ text: 'No file uploaded' }));
return;
}
const payload = { Name: file.originalFilename, Size: file.size };
const result = await sendGcodeFile(file);
log.info(`upload file result: ${result}`);

if (result.err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify({ done: result.text || 'Error uploading to printer', payload }));
log.info(`upload file error: ${result.text}`)
} else {
// Simulating upload to printer
log.info(`Upload finished: ${payload.Name} [${payload.Size}]`);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ done: true, payload }));
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});

// return server;
return new Promise((resolve, reject) => {
server.listen(SERVER_PORT, SERVER_IP, () => {
resolve(`orca server start, address: http://${SERVER_IP}:${SERVER_PORT}`)
});
server.on("error", (err) => {
if (err.code === 'EADDRINUSE') {
reject(`port:${SERVER_PORT} occupied, please replace the port`)
}
});

});

}

function closeServer() {
server && server.removeAllListeners();
server && server.close(() => {
log.info(`server closed`);
});
}

export {
openServer,
closeServer
}