we are using serial port device for sending and receiving data from this device to application, everything is going on perfect, but when we setting up wrong setting in device as well as in application but we got garbage value from device but we need setting value output from device is there any idea to get setting value from the device.
is there any idea ?
when we are trying to change settings we didn't receive garbage value when again try connection with same settings then we are receiving value from device starting with garbage value.
let serial = {
path: data.port,
baudRate: parseInt(data.baurate),
databits: parseInt(data.databits),
stopbits: parseInt(data.stopbits),
parity: data.parity,
protocol: data.protocol,
encoding: data.encoding,
};
/* here we try to make connection to the peripheral based on the settings selected.*/
if (connect.current === 1) {
sp = new serialport(serial);
}
/* Re-establish connection with new settings */
if (connect.current > 1) {
console.log("second click condition connect.current > 1");
if (spRef.current?.sp) {
const myInterval = new Promise((resolve, reject) => {
spRef.current.sp.lock = false;
spRef.current?.sp?.flush((err) => {
console.log("data will stop coming", err);
});
spRef.current?.sp?.close((err) => {
if (err === null) {
reconnect.current = true;
if (reconnect.current) {
resolve("connection is closed");
} else {
reject("connection is not closed");
}
}
});
});
await myInterval;
console.log("connection trying after closed conenction");
sp = new serialport(serial);
console.log("sp", sp);
}
}
/* here we try to check connection is established or not to the peripheral.*/
sp.on("open", () => {
console.log("sp event open");
let response = "Connected";
setTraffic({ connected: response });
setStatus(response);
spRef.current.sp = sp;
});
/* Now we check to see if incoming packets have arrived. we will parse messages based on the parser
they have selected. */
const parser = sp.pipe(new ReadlineParser({ delimiter: "\r\n" }));
parser.on("data", (device) => {
console.log("device", device);
let values = sortStr(device);
console.log("values", values);
let value = roundingLogic(values);
console.log("value", value);
if (togglePause) {
devicevalueDemo.push({
value: value,
currenttime: currentdatetimeevents(),
status: "incoming",
});
devicevalue.push(value);
}
let copy = [...newvalue];
setNewvalue([
...newvalue,
{
uuid: data.uuid,
peripheralvalue: value,
},
]);
});
/* if peripheral started sending some errors then we will send erorr message */
sp.on("error", (err) => {
console.log("Error coming from device", err);
let response = { Message: "Some error passed from device" };
});
/* Here we will find that device is disconnected from the comport then we will message to the logs */
sp.on("close", (err) => {
console.log("port is closed", err);
let response = "Disconnected";
setTraffic({ disconnected: response });
setStatus(response);
setNewvalue("");
lostperipheral = `Connection error "Lost Peripheral"`;
peripheralLogfile(lostperipheral, "Error");
});
Related
I am using Nest.Js and Socket.io on a server and React with Next in order to make a chat app.
But the problem is when i try to get some messages from the server i need to reconnect (If I connect for the first time handlers do not emit anything). And I think the problem is in the server (because I tried it also in Postman and the same problem is there).
Here is the code
async handleConnection(socket: Socket) {
this.server.once('connection', async (socket) => {
const token = socket.handshake.auth.token;
if (!token) {
socket.disconnect();
return;
}
const user = await this.authService.verifyAndReturnUser(token);
if (!user) {
console.log('USER IS NOT VALID');
socket.disconnect();
return;
}
// Set a userId in socket data
socket.data.userId = user.id;
// Get the rooms (chats) of the user
const userChats = await this.chatService.getUserChats(user.id);
//Emitting the rooms (chats)
socket.emit('getChats', userChats);
socket.on('joinRoom', async (data: { user: string; item?: string }) => {
// This code does not work on first connect (even the client commits)
const forwardedId = Number(data.user);
const forwardedItemId = Number(data.item);
const isForwardedNaN = Number.isNaN(forwardedId);
const isItemNan = Number.isNaN(forwardedItemId);
if (forwardedId == user.id) {
console.log('disconnect ID IS THE SAME');
socket.disconnect();
return;
}
if (!forwardedId || isForwardedNaN) {
console.log(forwardedId);
socket.disconnect();
return;
}
socket.data.forwardedId = forwardedId;
// Get forwarded info info
const getUser = await this.userService.getProfile(forwardedId);
// Get a time info
if (!getUser) {
socket.disconnect();
return;
}
const getCurrentRoom = await this.chatService.getCurrentRoom(
socket.data.forwardedId,
user.id,
);
if (getCurrentRoom) {
if (!getUser) {
socket.disconnect();
return;
}
}
socket.data.room = getCurrentRoom;
// Disconnect from all previous rooms
socket.rooms.forEach(async (room) => {
if (room) {
await socket.leave(room);
}
});
await socket.join(String(getCurrentRoom));
console.log(forwardedItemId, isItemNan);
// Set item to room
if (data.item) {
if (isItemNan) {
socket.disconnect();
return;
}
const room = await this.chatService.setItemToRoom(
getCurrentRoom,
forwardedId,
forwardedItemId,
);
// If there is no room updated disconnect
if (!room) {
socket.disconnect();
return;
}
socket.emit('getItem', room.item);
}
// Set message to seen when second user connected to socket
await this.chatService.markSeen(getCurrentRoom, user.id);
const roomMessages = await this.chatService.getRoomMessages(
getCurrentRoom,
);
// Get the user count in room
this.clientSize = (
await this.server.of('/').in(String(getCurrentRoom)).allSockets()
).size;
// Get the previous chat messages
this.server
.in(String(getCurrentRoom))
.emit('getRoomMessages', roomMessages);
// Get info about forwarded user in a room
socket.emit('getUser', getUser);
});
});
}
I want to add notifications to an application I've developed.
Unfortunately, Deno has removed the ws package.(https://deno.land/std#0.110.0/ws/mod.ts)
That's why I'm using the websocket inside the denon itself. Since it doesn't have many functions, I have to add some things myself.
For example, sending all messages to open clients.
What I want to do is when the pdf is created, a (data, message) comes from the socket and update the notifications on the page according to the incoming data.
I keep all open clients in a Map. and when the pdf is created, I return this Map and send it to all sockets (data, message).
However, this works for one time.
server conf...
import {
path,
paths,
ctid,
} from "../deps.ts";
const users = new Map();
const sockets = new Map()
const userArr = [];
export const startNotif = (socket,req) => {
const claims = req.get("claims");
const org = req.get("org");
claims.org = org;
console.log("connected")
users.set(claims.sub, {"username":claims.sub,"socket":socket})
users.forEach((user)=>{
if(userArr.length === 0){
userArr.push(user)
}
else if(userArr.every((w)=> w.username !== user.username) )
userArr.push(user)
})
sockets.set(org, userArr)
function broadcastMessage(message) {
sockets.get(org).map((u)=>{
console.log(u.socket.readyState)
u.socket.send(message)
})
}
if (socket.readyState === 3) {
sockets.delete(uid)
return
}
const init = (msg) => {
socket.send(
JSON.stringify({
status: "creating",
})
);
};
const ondata = async (msg) => {
const upfilepath = path.join(paths.work, `CT_${msg.sid}_report.pdf`);
try {
const s=await Deno.readTextFile(upfilepath);
if(s){
socket.send(
JSON.stringify({
status: "end",
})
);
} else {
socket.send(
JSON.stringify({
status: "creating",
})
);
}
} catch(e) {
if(e instanceof Deno.errors.NotFound)
console.error('file does not exists');
}
};
const end = () => {
try {
const endTime = Date.now()
const msg = "Your PDF has been created"
const id = ctid(12) // random id create
broadcastMessage(
JSON.stringify({
id: id,
date: endTime,
status: "done",
message: msg,
read: 'negative',
action: 'pdf'
})
);
} catch (e) {
console.log(400, "Cannot send.", e);
}
}
socket.onmessage = async (e) => {
const cmd = JSON.parse(e.data);
if(cmd.bid === 'start'){
await init(cmd)
}
if(!cmd.bid && cmd.sid){
await ondata(cmd)
}
if(cmd.bid === 'end'){
await end();
}
}
socket.onerror = (e) => {
console.log(e);
};
}
client conf...
export const webSocketHandler = (request) =>
new Promise((res, rej) => {
let url;
if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
url = `http://localhost:8080/api/notifications/ws`.replace('http', 'ws');
} else {
url = `${window.location.origin}/api/notifications/ws`.replace('http', 'ws');
}
const token = JSON.parse(sessionStorage.getItem('token'));
const orgname = localStorage.getItem('orgname');
const protocol = `${token}_org_${orgname}`;
const socket = new WebSocket(url, protocol);
const response = Object.create({});
socket.onopen = function () {
socket.send(
JSON.stringify({
bid: 'start',
})
);
};
socket.onmessage = function (event) {
response.data = JSON.parse(event.data);
if (response.data.status === 'creating') {
socket.send(
JSON.stringify({
sid: request.sid,
})
);
} else if (response.data.status === 'end') {
socket.send(
JSON.stringify({
bid: 'end',
})
);
} else if (response.data.status === 'done') {
try {
res(response);
} catch (err) {
rej(err);
}
}
};
socket.onclose = function (event) {
response.state = event.returnValue;
};
socket.onerror = function (error) {
rej(error);
};
});
onclick function of button I use in component...
const donwloadReport = async (type) => {
const query = `?sid=${sid}&reportType=${type}`;
const fileName = `CT_${sid}_report.${type}`;
try {
type === 'pdf' && setLoading(true);
const response = await getScanReportAction(query);
const request = {
sid,
};
webSocketHandler(request)
.then((data) => {
console.log(data);
dispatch({
type: 'update',
data: {
id: data.data.id,
date: data.data.date,
message: data.data.message,
action: data.data.action,
read: data.data.read,
},
});
})
.catch((err) => {
console.log(err);
});
if (type === 'html') {
downloadText(response.data, fileName);
} else {
const blobUrl = await readStream(response.data);
setLoading(false);
downloadURL(blobUrl, fileName);
}
} catch (err) {
displayMessage(err.message);
}
};
Everything works perfectly the first time. When I press the download button for the pdf, the socket works, then a data is returned and I update the notification count with the context I applied according to this data.
Later I realized that this works in a single tab. When I open a new client in the side tab, my notification count does not increase. For this, I wanted to keep all sockets in Map and return them all and send a message to each socket separately. But in this case, when I press the download button for the second time, no data comes from the socket.
Actually, I think that I should do the socket initialization process on the client in the context. When you do this, it starts the socket 2 times in a meaningless way.
In summary, consider an application with organizations and users belonging to those organizations. If the clients of A, B, C users belonging to X organization are open at the same time and user A pressed a pdf download button, I want A, B, C users to be notified when the pdf is downloaded.
I would be very grateful if someone could show me a way around this issue.
Have you looked at the BroadcastChannel API? Maybe that could solve your issue. See for example:
Deno specific: https://medium.com/deno-the-complete-reference/broadcast-channel-in-deno-f76a0b8893f5
Web/Browser API: https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API
I want to show the response coming from WebSocket server to emulator that is Microsoft Bot Builder but I am having a issue that inside ws.addEventListener. Here is the code
ws.addEventListener('message',async function (event) {
const msg = JSON.parse(event.data);
if(msg.topic === 'aws/chat' && msg.contentType === 'application/json'){
const content = JSON.parse(msg.content);
switch(content.Type){
case 'MESSAGE':
try{
if(content.ParticipantRole !== 'CUSTOMER'){
responseMessage = `${content.DisplayName} : ${content.Content}`;
console.log(`responseMessage :- ${responseMessage}`);
await turnContext.sendActivity(responseMessage);
}
}catch(error){
console.log("Insise Error");
console.log(error);
}
break;
case 'Event':
if(content.ContentType.includes('ended')){
responseMessage = `Chat ended`;
}
}
}
});
When I debugged await turnContext.sendActivity(responseMessage) is loosing scope inside the listener function and not able to return the response to the emulator.
From WS server receiving response and getting printed in console with error.
responseMessage :- BOT : To speak to an agent, press or say #
Insise Error
TypeError: Cannot perform 'get' on a proxy that has been revoked
at WebSocket. (D:\azure-bot\echo-bot\bots\stateManagementBot.js:155:59)
Here is the full code of stateManagementBot.js
// The accessor names for the conversation data and user profile state property accessors.
const CONVERSATION_DATA_PROPERTY = 'conversationData';
const USER_PROFILE_PROPERTY = 'userProfile';
let responseMessage;
let connectionToken;
let ws;
class StateManagementBot extends ActivityHandler {
constructor(conversationState, userState) {
super();
// Create the state property accessors for the conversation data and user profile.
this.conversationDataAccessor = conversationState.createProperty(CONVERSATION_DATA_PROPERTY);
this.userProfileAccessor = userState.createProperty(USER_PROFILE_PROPERTY);
// The state management objects for the conversation and user state.
this.conversationState = conversationState;
this.userState = userState;
this.onMessage(async (turnContext, next) => {
// Get the state properties from the turn context.
// By calling next() you ensure that the next BotHandler is run.await next()
if(turnContext.activity.text === '#'){
const url = await this.connectToAgent(turnContext.activity.text);
const initialMessage = {
topic: "aws/subscribe",
content: {
topics: ["aws/chat"]
}
};
console.log(url[1]);
ws = new WebSocket(url[1]);
console.log('Before Websocket....');
ws.addEventListener("open", () => {
console.log('Websocket....');
ws.send(JSON.stringify(initialMessage));
});
console.log("Websocket Conn...");
const param = {
ConnectionToken: connectionToken, /* required */
Content: turnContext.activity.text, /* required */
ContentType: 'text/plain', /* required */
};
connectparticipant.sendMessage(param, function(err, data) {
console.log('Sending....');
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
ws.addEventListener('message',async function (event) {
const msg = JSON.parse(event.data);
if(msg.topic === 'aws/chat' && msg.contentType === 'application/json'){
const content = JSON.parse(msg.content);
switch(content.Type){
case 'MESSAGE':
try{
if(content.ParticipantRole !== 'CUSTOMER'){
responseMessage = `${content.DisplayName} : ${content.Content}`;
console.log(`responseMessage :- ${responseMessage}`);
await turnContext.sendActivity(responseMessage);
}
}catch(error){
console.log("Insise Error");
console.log(error);
}
break;
case 'Event':
if(content.ContentType.includes('ended')){
responseMessage = `Chat ended`;
}
}
}
});
}
// By calling next() you ensure that the next BotHandler is run.
await next();
});
I am currently figuring out how to configure webRTC for my test application. I am able to get the user media API part of webrtc to work but the ICE config is what causes me issues. I have tried to look here on stackoverflow and it seems like noone else have had a similar error returned from the client. I am testing it on a live server where the inital communcation is through WSS. I have left out the markup and websocket config because it's irrelevant.
let myPeerConnection;
/* step 1: get users media stream inputs */
function getUserMediaClient(type = ""){
let mediaConstraints = {video:true, audio:true};
createPeerConnection();
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(function(localStream) {
document.getElementById("myVideo").srcObject = localStream;
document.getElementById("myVideo").onloadedmetadata = function(){
document.getElementById("myVideo").play();
}
localStream.getTracks().forEach(track => myPeerConnection.addTrack(track, localStream));
})
.catch(handleGetUserMediaError);
}
getUserMediaClient();
/*
preparation for step 2:
get users Peer connection information when the user calls createPeerCandidate()
to send the offer or handleVideoOfferMsg() to send the answer
*/
function createPeerConnection(){
myPeerConnection = new RTCPeerConnection(
{
iceServers: [
{
urls: [
'stun:stun.l.google.com:19302',
'stun:stun1.l.google.com:19302'
]
}/*,
{
urls: 'turn:192.158.29.39:3478?transport=tcp',
credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
username: '28224511:1379330808'
}*/
]
}
);
return myPeerConnection;
}
/*
step 2:
send information to opposite part through websocket with SDP info
*/
function handleNegotiationNeededEvent(myUsername = "", targetUsername = "") {
myPeerConnection.createOffer().then(function(offer) {
return myPeerConnection.setLocalDescription(offer);
})
.then(function() {
sendToServer({
name: myUsername,
target: targetUsername,
type: "video-offer",
sdp: myPeerConnection.localDescription
});
})
.catch(reportError);
}
/*
step 3:
"if" answering user accepts - load tracks to stream and respond with SDP config info
*/
function handleVideoOfferMsg(msg) {
let mediaConstraints = {video:true, audio:true};
var localStream = null;
targetUsername = msg.name;
let myUsername = document.getElementById("user1").value;
createPeerConnection();
var desc = new RTCSessionDescription(msg.sdp);
myPeerConnection.setRemoteDescription(desc).then(function () {
return navigator.mediaDevices.getUserMedia(mediaConstraints);
})
.then(function(stream) {
localStream = stream;
document.getElementById("myVideo").srcObject = localStream;
localStream.getTracks().forEach(track => myPeerConnection.addTrack(track, localStream));
})
.then(function() {
return myPeerConnection.createAnswer();
})
.then(function(answer) {
return myPeerConnection.setLocalDescription(answer);
})
.then(function() {
var msg = {
name: myUsername,
target: targetUsername,
type: "video-answer",
sdp: myPeerConnection.localDescription
};
sendToServer(msg);
})
.catch(handleGetUserMediaError);
}
/*
step 4:
when both users have exchanged information - the ice processing can begin
the user that initially sent the request can now reply with a communication method
*/
var candidateData = null;
function handleICECandidateEvent(event) {
if ((event.sdp)||(event.candidate)){
if (event.candidate){
candidateData = event.candidate;
} else if (event.sdp) {
candidateData = event.sdp;
}
sendToServer({
type: "new-ice-candidate",
target: event.target,
candidate: candidateData
});
}
}
///////////////////// non functional part under ////////////////////////////
function handleNewICECandidateMsg(msg) {
candidateData = msg.candidate;
myPeerConnection.addIceCandidate(new RTCIceCandidate({sdpMLineIndex:1,candidate: candidateData})).catch(e => {
console.log("Failure during addIceCandidate(): " + JSON.stringify(e));
});
////////////// non functional part above ///////////////
console.log("MSG: " + JSON.stringify(msg));
}
function handleGetUserMediaError(e){
//removed for simplicity
}
//wss connection estabilshment from client removed
wss.onmessage = function(e){
if (type == "video-offer" && document.getElementById("user1").value == target){
// create counteroffer
handleVideoOfferMsg(data);
} else if (type == "video-answer"){
handleICECandidateEvent(data);
} else if (type == "new-ice-candidate"){
handleNewICECandidateMsg(data);
}
}
Most of the code is from MDN's tutorial here: https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling
The issue is within the handleNewICECandidateMsg() function (or so i think). Because when i enter sdpMLineIndex and sdpMid i get an empty json string and when i leave it with only the candidates sdp info it throws a typeerror saying it needs either sdpMid or sdpMLineIndex.
Any thoughts, links. Anything is appreciated!
I am trying to build a simple Chatroom where multiple users can post the messages.I have setup the node web socket and it's broadcasting for a single message, but it closes the connection immediately after that.
This includes react on the front-end and node.js on the backend.
For simplicity i am storing and retrieving all the messages in a json file.
I am using ws: a node.js websocket library to setup the socket connection.
In client side i am using browsers WebSocket instance and listening on the same port.
// In server.js (Backend)
const server = http.createServer(doOnRequest)
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 1994 })
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(data) {
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN){
client.send(data);
}
});
});
ws.on('close', () => {
console.log('server conn closed');
setTimeout(() => {
console.log('closed by server console. log');
}, 2000);
})
});
function doOnRequest(request, response) {
// This functions handles all the get and post calls and stores
it in a file
}
const server = http.createServer(doOnRequest)
server.listen(3001);
// IN Chatroom.js ( UI )
const URL = 'ws://localhost:1994'
class Chatroom extends React.Component {
ws = new WebSocket(URL)
constructor(props) {
////// binding classes declaring state ////
}
componentDidMount() {
this.ws.onopen = () => {
console.log('connected')
}
this.ws.onmessage = evt => {
// on receiving a message, add it to the list of messages
let x = this.state.messageList;
x ? x.push(JSON.parse(evt.data)) : [JSON.parse(evt.data)];
this.setState({
messageList: x,
value: ''
});
}
this.ws.onclose = () => {
console.log('disconnected')
}
this.renderOlderMessages();
}
renderOlderMessages() {
// render older messages using GET request
}
addNewMessage(chatObj) {
// let res = a Post request (with Request body as chatObj).
res.then(() => {
this.ws.send(JSON.stringify(chatObj))
let x = this.state.messageList;
x ? x.push(chatObj) : [chatObj];
this.setState({
messageList: x,
value: ''
});
});
}
render() {
return (
<div>
/// render old messages ///
</div>
<div>
<form>
Input ---> New message ---> Submit
</form>
</div>
)
}
}