I'm building a webpage to control my home automation system (Teletask) It's an older system which still uses a serial interface. I have a pc running to control other stuff and this pc runs 24/7 I hooked it up to the home automation system and I can control it with a webpage running locally. I installed node.js; created a project folder, did a npm init and install express created a server.js file (see below) front end is talking to back end but nothing is shown on the serial port (monitored with Serial Port Monitor)
relevant code front end look like this:
<script>
async function sendToSerial(hexCode) {
try {
const response = await fetch('http://localhost:3000/sendToSerial', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ hexCode }),
});
if (!response.ok) {
throw new Error(`Request failed with status: ${response.status}`);
}
const data = await response.json();
console.log('Server response:', data);
} catch (error) {
console.error('Error during serial communication:', error.message);
}
}
back end code looks like this:
async function sendToSerial(hexCode) {
console.log('Sending to serial port:', hexCode);
const port = new SerialPort('COM3', { baudRate: 19200 });
return new Promise((resolve, reject) => {
port.on('error', (err) => {
console.error('Serial port error:', err);
reject(err);
});
port.on('open', async () => {
console.log('Serial port opened successfully.');
try {
const data = Buffer.from(hexCode.replace(/0x/g, ''), 'hex');
await port.write(data);
await port.drain();
console.log('Data sent successfully.');
resolve();
} catch (error) {
console.error('Error during serial communication:', error);
reject(error);
} finally {
if (port.isOpen) {
await port.close();
console.log('Serial port closed.');
}
}
});
});
}
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
`
when running:
C:\inetpub\wwwroot\teletask>node server.js Server is running at http://localhost:3000 Sending to serial port: 0x02,0x07,0x01,0x01,0x08,0xff,0x00,0x12 Sending to serial port: 0x02,0x07,0x01,0x01,0x08,0xff,0x00,0x12 Sending to serial port: 0x02,0x07,0x01,0x01,0x08,0xff,0x00,0x12 Sending to serial port: 0x02,0x07,0x01,0x01,0x08,0xff,0x00,0x12 Sending to serial port: 0x02,0x07,0x01,0x01,0x08,0xff,0x00,0x12
codes are seen but not sent to serial port. Yes it's the correct one and yes I can send via serial port monitor commands using this port.
Can you shine your light on this one? :) Much appreciated