I'd like create a web application which is communicating with X-lite SIP phone. I found API documentation Click here but I don't understand how should I parsed the data for request. For example GET /status "phone". I know use just simple request as GET /showHistory. Thanks for any advice.
function WebSocketTest(){
var ws = new WebSocket("wss://cpclientapi.softphone.com:9002/counterpath/socketapi/v1");
ws.onopen = function (event) {
//here I dont know how to write xml request from documentation
//for example GET /status "phone"
ws.send('GET /showHistory');
};
ws.onerror = function(error){
console.log('Error detected: ' + error);
}
ws.onmessage = function(messageEvent) {
if (typeof messageEvent.data === "string"){
console.log("received text data from the server: " + messageEvent.data);
} else if (messageEvent.data instanceof Blob){
console.log("Blob data received")
}
};
}
Try using localhost:9002
function WebSocketTest(){
var ws = new WebSocket("wss://localhost:9002/counterpath/socketapi/v1");
ws.onopen = function (event) {
//here I dont know how to write xml request from documentation
//for example GET /status "phone"
ws.send('GET /showHistory');
};
ws.onerror = function(error){
console.log('Error detected: ' + error);
}
ws.onmessage = function(messageEvent) {
if (typeof messageEvent.data === "string"){
console.log("received text data from the server: " + messageEvent.data);
} else if (messageEvent.data instanceof Blob){
console.log("Blob data received")
}
};
}
Related
I have a websocket listening on some interfaces so the client could call more than one ip. I don't have a dns for these IPs. This failes even in the try block
window.onload = function() {
ws = "";
try {
ws_connection = "ws://" + lblInfoIP.value + ":9080/websockets";
ws = new WebSocket(ws_connection);
}
catch(err) {
ws_connection = "ws://127.0.01:9080/websockets";
ws = new WebSocket(ws_connection);
}
ws.onmessage = function(msg) { showInfo(msg.data); };
ws.onerror = function(evt){ alert ('Websocket failed with ' + evt.data) };
}
manually using the same ip as the called url works.
How would I correctly handle that ?
Is there somesthing like ws_connection = "ws://" + called_url + "/websockets"; ?
Instead of your try/catch construct, use a simple "or" (||) operation:
window.onload = function () {
let ws = new WebSocket(`ws://${lblInfoIP.value || "127.0.01:9080"}/websockets`)
ws.onmessage = function (msg) { showInfo(msg.data); };
ws.onerror = function (evt) { alert('Websocket failed with ' + evt.data) };
}
In development, set lblInfoIP.value to null or "undefined".
Or use "document.location.host:9080"
I am trying to run this program in Raspberry Pi 3.
I have installed nodejs and ws on my raspberry pi.
Then I installed serial port module.
I am trying to create this project:enter link description here
I have tried to find solutions everywhere but I could not find one.
If any one knows how to solve this problem please help me.
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "5bb3ba9304674086bee67fa507a215cf"; //DEVICE ID
var device_token = "36b278345b6d4d11abf764ae213c5c70"; //DEVICE TOKEN
var WebSocket = require('ws');
var isWebSocketReady = false;
var data="";
var ws = null;
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var sp = new SerialPort("/dev/ttyACM0", { //for serial communication with arduino
baudrate: 9600,
// The baud rate of uno is 9600
parser: serialport.parsers.readline("\n")
});
/**
* Gets the current time in millis
*/
function getTimeMillis(){
return parseInt(Date.now().toString());
}
/**
* Create a /websocket connection and setup GPIO pin
*/
function start() {
//Create the WebSocket connection
isWebSocketReady = false;
ws = new WebSocket(webSocketUrl);
ws.on('open', function() {
console.log("WebSocket connection is open ....");
register();
});
ws.on('message', function(data) {
//this loop is called whenever the client sends some message
handleRcvMsg(data); //data is send to the function handleRcvMsg()
});
ws.on('close', function() {
console.log("WebSocket connection is closed ....");
});
}
/**
* Sends a register message to /websocket endpoint
*/
//Client will only work when device gets registered from here
function register(){
console.log("Registering device on the WebSocket connection");
try{
var registerMessage = '{"type":"register", "sdid":"'+device_id+'", "Authorization":"bearer '+device_token+'", "cid":"'+getTimeMillis()+'"}';
console.log('Sending register message ' + registerMessage + '\n');
ws.send(registerMessage, {mask: true});
isWebSocketReady = true;
}
catch (e) {
console.error('Failed to register messages. Error in registering message: ' + e.toString());
}
}
//data after receiving is sent here for processing
function handleRcvMsg(msg){
var msgObj = JSON.parse(msg);
if (msgObj.type != "action") return; //Early return;
var actions = msgObj.data.actions;
var actionName = actions[0].name; //assume that there is only one action in actions
console.log("The received action is " + actionName);
}
/**
* Send one message to ARTIK Cloud
*/
//This function is responsible for sending commands to cloud
//function sendStateToArtikCloud(parking,temperature,water){
function sendDataToArtikCloud(pantry){
var result=pantry.split(" ");//data gets split by " " to get the values
try{
ts = ', "ts": '+getTimeMillis();
var data = {
"Garlic": result[1],
"Potato":result[2],
"Temperature":result[3],
"Chilli":result[4],
"Humidity": result[5],
"Ginger":result[6],
"Onion": result[7]
};
var payload = '{"sdid":"'+device_id+'"'+ts+', "data": '+JSON.stringify(data)+', "cid":"'+getTimeMillis()+'"}';
console.log('Sending payload ' + payload + '\n');
ws.send(payload, {mask: true});
} catch (e) {
console.error('Error in sending a message: ' + e.toString() +'\n');
}
}
function exitClosePins() {
console.log('Exit and destroy all pins!');
process.exit();
}
start();
//exectes every second when data is received from arduino (5sec programmed delay from arduino)
sp.on("open", function () {
sp.on('data', function(data) {
console.log("Serial port received data:" + data);
//var result=data.split(" ");//data gets split by " " to get the values
//sendStateToArtikCloud(result[0],result[2],result[1]);//parking,temperature,waterlevel
sendDataToArtikCloud(data);
});
});
process.on('SIGINT', exitClosePins);
I am getting an error on my raspberry pi
enter image description here
Suggest me a solution.
The documentation will tell you that Readline is spelled with a capital R
https://www.npmjs.com/package/serialport#module_serialport--SerialPort.parsers
parser: serialport.parsers.Readline("\n")
~
[TypeError: serialport.parsers.readline is not a function.]
If it has not been resolved yet, try this method.
var serialport = require("serialport")
var SerialPort = serialport.SerialPort;
var sp = new serialport("/dev/ttyACM0"),{
BaudRate: 9600,
parser: new serialport.parsers.Readline("\r\n")
});
I hope your problem is solved.
I'm using window.error to try to capture all client side errors.
It's working fine with Javascript errors but It doesn't capture all errors like Network Errors, or AJAX errors.
This is my code (I can't use jQuery, so is not possible to use .ajaxError):
window.onerror = function(messageOrEvent, source, lineno, colno, error) {
console.log("Captured: " + messageOrEvent)
}
This is the result:
Anyone knows a way to capture ALL errors on the client side?
Thanks
Maybe hook over the default request object:
(function(orig){
window.XMLHttpRequest=function(...args){
var instance=new orig(...args);
instance.addEventListener("readyStateChange",function(){
if(instance.status!==200){
throw new Error(instance.status+":"+instance.statusText);
}
});
return instance;
};
})(XMLHttpRequest);
I've found a way. This is my code. I think that this capture all errors.
// JavaScript Errors
window.onerror = function(messageOrEvent, source, lineno, colno, error) {
console.log("Captured: " + messageOrEvent)
}
// 404 FILES
window.addEventListener('error', function(e) {
console.log(e);
}, true);
// AJAX Errors
var open = window.XMLHttpRequest.prototype.open,
send = window.XMLHttpRequest.prototype.send;
function openReplacement(method, url, async, user, password) {
this._url = url;
return open.apply(this, arguments);
}
function sendReplacement(data) {
if(this.onreadystatechange) {
this._onreadystatechange = this.onreadystatechange;
}
this.onreadystatechange = onReadyStateChangeReplacement;
return send.apply(this, arguments);
}
function onReadyStateChangeReplacement() {
// CAPTURE HERE.
if(this.status != 200){
console.log(this.responseURL + " " + this.status + " " + this.statusText);
}
if(this._onreadystatechange) {
return this._onreadystatechange.apply(this, arguments);
}
}
window.XMLHttpRequest.prototype.open = openReplacement;
window.XMLHttpRequest.prototype.send = sendReplacement;
I'm writing a telegram bot to report fail2ban bans. It's very simple and dirty, written hastily, but it can be used to report any message to a single telegram user:
var TelegramBot = require('node-telegram-bot-api');
var fs = require('fs');
var store = {
get: function (key) {
return fs.readFileSync(__dirname + '/' + key, { encoding: 'utf-8' });
},
set: function (key, value) {
fs.writeFileSync(__dirname + '/' + key, value, { encoding: 'utf-8' });
}
};
var token = store.get('token');
var args = process.argv.slice(2);
if (args.length == 0) {
console.error('No mode specified');
process.exit(0);
}
TelegramBot.prototype.unregisterText = function (regexp) {
for (var i = 0; i < bot.textRegexpCallbacks.length; ++i) {
if (bot.textRegexpCallbacks[i].regexp.toString() == regexp) {
bot.textRegexpCallbacks.splice(i, 1);
return;
}
}
};
fs.appendFileSync(__dirname + '/logs',
'[' + (new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')) + '] '
+ args.join(' ') + '\n',
{ encoding: 'utf-8' });
switch (args[0]) {
case 'setup':
var bot = new TelegramBot(token, { polling: true });
var step = 'none';
bot.onText(/\/setup/, function (msg, match) {
var fromId = msg.from.id;
step = 'setup-started';
bot.sendMessage(fromId, 'Starting setup. Please enter the verification key.');
bot.onText(/(.+)/, function (msg, match) {
if (step == 'setup-started') {
var key = match[1];
var verification = store.get('key');
if (key == verification) {
store.set('owner', msg.from.id);
step = 'verified';
bot.sendMessage(msg.from.id, 'Correct. Setup complete.');
} else {
step = 'none';
bot.unregisterText(/(.+)/);
bot.sendMessage(msg.from.id, 'Wrong. Setup aborted.');
}
}
});
});
break;
case 'report':
var bot = new TelegramBot(token, { polling: false });
var owner = store.get('owner');
var subject = args[1];
if (subject == 'message') {
var message = args.slice(2).join(' ');
bot.sendMessage(owner, message);
} else if (subject == 'file') {
var content = fs.readFileSync(args[2], { encoding: 'utf-8' });
bot.sendMessage(owner, content);
}
break;
default:
console.error('Unrecognized mode', args[0]);
break;
}
On my developer machine it works fine. I invoke:
node bot.js report message whatever message i want
And I correctly received "whatever message i want" on telegram. However, once I gitted it on my digitalocean vps, it no longer worked. It turns out the problem is with the telegram library:
Unhandled rejection Error: Error parsing Telegram response: <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bots: An introduction for developers</title>
...
Which apparently returns an html page instead of json... I also tried to contact the same endpoint (api.telegram.org/bothash/sendMessage) with curl on my vps and it returned json (with an error message because i didnt send any parameters, but still json).
I cannot fathom why this happens. Any help?
It seems like either you don't have a file with token on your VPN or the token is incorrect.
You can check it by yourself:
When you make a request to api.telegram.org/{token}/sendMessage, and {token} is incorrect, it redirects you to this page, which responds with HTML you've mentioned in your question.
So you have to debug a behavior of your store.get and store.get functions along with files and tokens to make sure you are using a correct one.
Also, I'd recommend to run bot.getMe() before using any other Telegram API methods to ensure you specified a correct bot token.
I try to create simple chat application using secure layer WSS. Without wss it works. Here is my code:
FleckLog.Level = LogLevel.Info;
var allsockets = new List<IWebSocketConnection>();
var server = new WebSocketServer("wss://localhost:8181");
server.Certificate = new X509Certificate2(#"C:\Users\user\Desktop\sharpchat-master\server\Sharpchat\Certificate.pfx", "123");
server.Start(socket =>
{
socket.OnOpen = () =>
{ //See socket.ConnectionInfo.* for additional informations
Console.WriteLine(String.Empty);
Console.WriteLine("[NEW CLIENT CONNECTION]======================");
Console.WriteLine("GUID: " + socket.ConnectionInfo.Id);
Console.WriteLine("IP: " + socket.ConnectionInfo.ClientIpAddress);
Console.WriteLine("Port: " + socket.ConnectionInfo.ClientPort);
Console.WriteLine("=============================================");
Console.WriteLine(String.Empty);
allsockets.Add(socket);
};
socket.OnClose = () =>
{
Console.WriteLine(String.Empty);
Console.WriteLine("[DISCONNECTED CLIENT]=======================");
Console.WriteLine("GUID: " + socket.ConnectionInfo.Id);
Console.WriteLine("IP: " + socket.ConnectionInfo.ClientIpAddress);
Console.WriteLine("Port: " + socket.ConnectionInfo.ClientPort);
Console.WriteLine("=============================================");
Console.WriteLine(String.Empty);
allsockets.Remove(socket);
};
socket.OnMessage = (message) =>
{
//TODO: Json.Net Deserialize
Console.WriteLine("[JSON MESSAGE] " + message);
allsockets.ToList().ForEach(s => s.Send(message));
};
});
var input = Console.ReadLine();
while (input != "exit")
{
foreach (var socket in allsockets.ToList())
{
socket.Send(input);
}
input = Console.ReadLine();
}
When client connects to server there is an exception:
[Warn] Failed to Authenticate System.AggregateEx
ception: One or more errors occurred. ---> System.IO.IOException: The handshake
failed due to an unexpected packet format.
at System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncRes
ult lazyResult)
at System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result)
at System.Net.Security.SslStream.EndAuthenticateAsServer(IAsyncResult asyncRe
sult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar,
Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchron
ization)
--- End of inner exception stack trace ---
---> (Inner Exception #0) System.IO.IOException: The handshake failed due to an
unexpected packet format.
at System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncRes
ult lazyResult)
at System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result)
at System.Net.Security.SslStream.EndAuthenticateAsServer(IAsyncResult asyncRe
sult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar,
Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchron
ization)<---
Here is client code in JavaScript:
// Websocket Endpoint url
var URL = 'wss://localhost:8181';
var chatClient = null;
function connect () {
chatClient = new WebSocket(URL);
chatClient.onmessage = function (event) {
var messagesArea = document.getElementById("messages");
var jsonObj = JSON.parse(event.data);
var message = "<"+ jsonObj.user + "> " + jsonObj.message + "\r\n";
messagesArea.value = messagesArea.value + message;
messagesArea.scrollTop = messagesArea.scrollHeight;
};
}
function disconnect () {
chatClient.close();
}
function sendMessage() {
var user = document.getElementById("userName").value.trim();
if (user === "")
alert ("Please enter your name!");
var inputElement = document.getElementById("messageInput");
var message = inputElement.value.trim();
if (message !== "") {
var jsonObj = {"user" : user, "message" : message};
chatClient.send(JSON.stringify(jsonObj));
inputElement.value = "";
}
inputElement.focus();
}
Can anyone help me fix this problem?
Thank you very much!
Use full domain name in URL i.e. var URL = 'wss://localhost.company.com:8181';
Allow invalid certificates for resources loaded from localhost # Enable.
More Details are here