So I've installed the SocketCAN, Express, and Socket.io node modules.
What I want to do, is: *initialize a Socket via Socket.io on a Express server *use socketCAN "node-can" module on the server to send messages to my Frontend (Angular6)
What i've done so far:
*Created a Express server and initialized Socket.io and node-can there *Being able to connect to my socket in my App
Here is the code achieving this:
const express = require('express');
const path = require('path');
const http = require('http');
const socketIO = require('socket.io');
var can = require('socketcan');
var channel = can.createRawChannel("vcan0", true);
channel.start();
const app = express();
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'dist/akkaDiagTool')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/akkaDiagTool/index.html'));
});
const server = http.createServer(app);
const io = socketIO(server);
io.on('connection', (socket) => {
console.log('socket connected');
socket.on('can message', (from, msg) => {
msg.channel.addListener("onMessage", function(data) {console.log(data);});
console.log('Recieved message by', from , 'sayin ', msg);
});
socket.on('disconnected', (socket) => {
console.log('socket disconnected');
})
})
server.listen(port, () => {
console.log(`Server running on port ${port}`)
})
So when i Start my app and send a can message with socketcan:cansend vcan0 37F#0000000012343412
i will only see the log of my msg.channel.addListener("onMessage", function(data) {console.log(data);});
but not the console.log('Recieved message by', from , 'sayin ', msg);
log
my Angular Component looks like this:
import { Component, OnInit } from '@angular/core';
import * as io from 'socket.io-client';
@Component({
.
.
.
})
export class StaticDataComponent implements OnInit {
socket;
constructor() {
this.socket = io();
this.socket.on('can message', (data) => {
console.log(data);
});
}
The Socket should be connected, since i get the socket connected
log in my console.
Any help would be appreciated
Thx in advance.
Allright, I managed to figure it out.
I had to io.emit() inside an socket.emit with socket.io on the server:
io.on('connection', (socket) => {
//create canChannel with socketcan(node-can)
var channel = can.createRawChannel('vcan0', true);
//emit messagees to the *can message* listening to the canChannel
socket.emit('can message', channel.addListener('onMessage', (data) => {
io.emit('can message', data);
}));
channel.start();
//disconnect
socket.on('disconnected', (socket) => {
console.log('socket disconnected');
});
and here the code inside the Angular Component:
constructor() {
this.socket = io();
this.socket.on('can message', (msg) => {
console.log('data', msg);
});
}
The provided code is minimalistic and just loggin the data in the developer console.