I'm trying to get a web page based serial communication working with an Arduino which is connected to a router running Openwrt, it does work but only when either screen is running or remotely connected via putty, for some reason the php to serial is not starting a session properly? I use ser2net to manage the serial with the following setting
1000:raw:0:/dev/ttyACM0:9600
I have also tried stty with various settings advised on this forum
Update 1
also tried 80:raw:0:/dev/ttyACM0:9600 as setting for ser2net assuming port 80 is web/http port
my php code is
if (isset($_GET['action']))
{
$serial = new phpSerial();
$serial->deviceSet('/dev/ttyACM0');
$serial->confBaudRate(9600);
$serial->confParity('none');
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl('none');
$serial->deviceOpen();
if ($_GET['action'] == "PIN_12_HIGH")
{
$serial->sendMessage("A");
}
if ($_GET['action'] == "PIN_12_LOW")
{
$serial->sendMessage("B");
}
if ($_GET['action'] == "PIN_11_HIGH")
{
$serial->sendMessage("C");
}
if ($_GET['action'] == "PIN_11_LOW")
{
$serial->sendMessage("D");
}
$serial->deviceClose();
}
update 2
if i add sleep(1); to my php code it seems to solve some of the problems
a few points
adding sleep to php code allows the commands to reach the arduino after a reset caused by the serial connection, but if i turn on led 1 when i turn led 2 on led 1 gets reset to off. so this would mean a more complicated code in the form of logging an array of choices and sending the whole updated array to arduino, i would like to avoid this and just send 1 command at a time.
again when screen or putty are active the arduino does not have this reset problem? so the question is what does screen and putty do to keep the connection alive that stty and php serial does'nt?
Update 3
After finding this helpful post i seem to have discovered a possible solution with no reset hacking needed to the Arduino.
Adding cat /dev/ttyACM0 & to the start up config of the Openwrt router enables serial communication with the Arduino without reseting it on every transmission of data.
problems left:
I think this code is binding arduino to a session with the router? But im unsure.
It seems to be eating the return value from the Arduino stopping my php page getting the data return?
My System Log file contains the missing returned data from Arduino?
Update 4
As i needed to get this working, i used a capacitor to stop the auto reset from serial communication on the arduino.
As stated screen and putty dont create this reset problem when communicating with arduino, i tried many different settings with STTY but couldnt find a solution , but i am still trying and keen to discover how screen/putty does this.
It looks like your PHP is attempting to directly connect to the tty. Where the ser2net is likely already connected to the tty. Only one application at a time can be connected to the tty. Either stop the ser2net or your PHP should connect to the tcp listener of the desired tty as per your ser2net.conf
Related
I'm building a dashboard that allows me to visualise my crontab as it runs (Think a queue of upcoming tasks, those that are running currently and those that have finished and whether the outcome was successful.) To do this, I need to send messages from the tasks (running or monitored by PHP) on my server, to the client browsers that run the dashboard using javascript. It also has to be secure.
To solve this issue I implemented a Twisted/Autobahn socket server in Python, which worked fine once I had paid for proper security certificates. The problem I have however is getting the PHP running the crontasks to be able to send messages to the webSocket server which passes them on to the client browsers, so far I have hacked this by writing a Python client that accepts the message to send as an argument and run this as an exec from PHP.
Obviously this is not a robust solution (which is also relatively slow to execute) and I'd now like to send logfile entries from the crontasks over websockets to my dashboards so I can see what's happening on my servers as tasks run. I've been looking for a while and tried various approaches (most are too long to post) however they range from tutorials, to segments from the PHP website to libraries such as Thruway (which seems too over-engineered for my use case, specialised and hard to adapt).
The best progress I have so far is Pawl, and using the following code I'm able to successfully send three messages to the Python Socket Server using wss:
<?php
require __DIR__ . '/vendor/autoload.php';
\Ratchet\Client\connect('wss://127.0.0.1:9000')->then(function($conn) {
$conn->on('message', function($msg) use ($conn) {
echo "Received: {$msg}\n";
$conn->close();
});
$conn->send('MSG 1');
$conn->send('MSG 2');
$conn->send('MSG 3');
}, function ($e) {
echo "Could not connect: {$e->getMessage()}\n";
});
?>
(Note that this depends on the libraries found here)
The problem I have is that I would like to be able to open and close the connection and send messages as separate steps, in the code example (which I've had difficulty adapting) it seems that as open, send and close are all wrapped in the then method and anonymous function I cannot call these methods seperately. Ideally I'd like to open the connection at the beginning of my crontask execution, each time a message is logged call the send method and close the connection at the end without wasting time opening and closing a connection to my socket server for each and every message. Please note that listening for replies isn't necessary.
Also, any solutions that work to 127.0.0.1:9000 over WSS and don't need libraries or use a different one I'm happy to consider. Please also note (after seeing other posts) this question specifically refers to a websocket client, not a server.
Many thanks,
James
Leaving this in case anybody else finds this final solution welcome:
In the end I wrapped a module called Textalk by Fredrik Liljegren et al in a small class to make it more accesible and this solved my issue.
Here is the code I used in the end:
require('vendor/autoload.php');
use WebSocket\Client;
class secureSocketClient {
private $OClient;
function __construct($VProtocol, $VLocation, $VPort, $VDir) {
$this->OClient = new Client("$VProtocol://$VLocation:$VPort" . ($VDir != null ? "/$VDir" : ""));
}
function sendMessage($ORequestData) {
$VLocalMessage = json_encode($ORequestData);
$this->OClient->send($VLocalMessage);
}
function __destruct() {
$this->OClient->close();
}
}
Which can be invoked as so:
require_once <class location>
$this->OSecureSocketClient = new secureSocketClient("wss", "127.0.0.1", "9000", null);
$this->OSecureSocketClient->sendMessage($OMSG1);
$this->OSecureSocketClient->sendMessage($OMSG2);
$this->OSecureSocketClient->sendMessage($OMSG3);
To install textTalk (on linux), you can use the following commands in the directory where the class will reside:
curl -sS https://getcomposer.org/installer | php
add the following to composer.json (in the same directory):
{
"require": {
"textalk/websocket": "1.0.*"
}
}
then run the following:
sudo php composer.phar install
Regards,
James
I have written a slack auto-message service on heroku that will auto send a message on some event. However, I have accidentally made an infinity loop and it keeps sending error message to my slack account. (the loop caused by retrying on error and I forgot to add a counter on that)
I have tried restarting the server by typing the command heroku restart (at that directory, so app name can be omitted), as well as git pushing my corrected version which should restart the server. I even turn off the server by settings 0 dymo to it. None of these works and I still keep receiving message on slack.
I am quite sure I have turn off my heroku server, so I think there should be other way to stop the process. The php process will have a bash_exec to trigger phantomjs. Not sure if it is related to the current problem. Do anyone has any suggestions?
P.S. As request, this is my code with important information hidden.
<?php
sendSlackMessageToChannel("Request received. Loading, please wait.");
startPhantomJS();
function startPhantomJS() {
$return_value = bash_exec("path/to/phantomjs myscript.js");
sendSlackMessageToMyself($return_value);
if ($return_value == "error")
startPhantomJS();
else
sendSlackMessageToChannel($return_value);
}
I would like to make a web interface in PHP to see the FreeSWITCH activities (calls, etc), possibly hosted on a different server than the one where FS is running.
I've seen the server status on the FS server using command line (php single_command.php status), but now I would like to see this status from another server.
When I try to copy ESL.php file to this remote server and try to check the status, I get this error message:
Fatal error: Call to undefined function new_ESLconnection() in
/var/www/freeswitch/ESL.php on line 127
This is my index.php file:
<?php
ini_set('display_errors', 1);
$password = "ClueCon";
$port = "8021";
$host = "192.168.2.12";
require_once('ESL.php');
set_time_limit(0); // Remove the PHP time limit of 30 seconds for completion due to loop watching events
// Connect to FreeSWITCH
$sock = new ESLconnection($host, $port, $password);
// We want all Events (probably will want to change this depending on your needs)
$sock->sendRecv("status");
// Grab Events until process is killed
while($sock->connected()){
$event = $sock->recvEvent();
print_r($event->serialize());
}
?>
I undestand that the webserver doesn't have FreeSWITCH installed, so the error message is obvious, but i don't see how to access to this information from this webserver.
Thank you for your help.
Depending upon your need you can use either Inbound or Outbound socket. I do not know much about PHP and FS Event Socket but yeah tried enough with python. I highly recommended to go through thislink.
So if you just want to do small task like initiating a call, bridging any two given number etc i think you should go with Inbound socket(making cli command from your web server to freeswitch server) or mod_xml_rpc.
And if you want to have full control of everything that happens on FS server like showing live call status and modifying their states or say a complete interactive telephony dashboard then you should go with Outbound socket.(Your FS server will send all events to your web server.)
However in your case problem is I think you did not properly build the php ESL module.
this link might help you installing ESL
Rather than using ESL, you might want to consider using the XMLRPC. The connection is very straight forward:
https://wiki.freeswitch.org/wiki/Freeswitch_XML-RPC
The credentials for the XMLRPC are in your autoloads_configs/xml_rpc.conf.xml
I am trying to get my head round node.js...
I am very happy with my LAMP set up as it currently fulfils my requirements. Although I want to add some real-time features into my PHP app. Such as showing all users currently logged into my site and possible chat features.
I don't want to replace my PHP backend, but I do want scalable real-time solutions.
1. Can I throw node.js into the mix to serve my needs without rebuilding the whole application server-side script?
2. How best could node.js serve my 'chat' and 'currently logged in' features?
Great to hear your views!
W.
I suggest you use Socket.io along side node.js. Install and download the libs from http://socket.io/. You can run it along side your Apache server no problems.
First create a node server:
var http = require('http')
, url = require('url')
, fs = require('fs')
, io = require('../')//path to your socket.io lib
, sys = require(process.binding('natives').util ? 'util' : 'sys')
, server;
server = http.createServer(function(req, res){
var path = url.parse(req.url).pathname;
}),
server.listen(8084);//This could be almost any port number
Second, run your server from the command line using:
node /path/to/your/server.js
Third, connect to the socket using client side js:
var socket = new io.Socket(null, {port: 8084, rememberTransport: false});
socket.connect();
You will have to have include the socket.io lib client side aswell.
Send data from client side to the node server using:
socket.send({data:data});
Your server.js should also have functions for processing requests:
io.on('connection', function(client){
//action when client connets
client.on('message', function(message){
//action when client sends msg
});
client.on('disconnect', function(){
//action when client disconnects
});
});
There are two main ways to send data from the server to the client:
client.send({ data: data});//sends it back to the client making the request
and
client.broadcast({ data: data});//sends it too every client connected to the server
I suspect the chat as well as the logged in listing would work via Ajax.
The chat part would be pretty easy to program in Node.js, use one of the mysql modules for Node to connect to your existing database and query login information and such and then do all the actual chatting via Node.js, I recommend you to check out Socket.io since it makes Browser/Node.js communcation really trivial, this should allow you to focus on the actual chat logic.
Also, you could take a look at the "official" chat demo of Node.js, for some inspiration.
As far as the currently online part goes, this is never easy to implement since all you can do is to display something along the lines of "5 users active in the last X minutes".
Of course you could easily add some Ajax that queries the chat server and display the userlist from that on the homepage.
Or you completely crazy and establish a Socket.io connection for every visitor and monitor it this way, although it's questionable whether this is worth the effort.
What about using a socket file
just like pedro did with ngnx ?
http://nodetuts.com/tutorials/25-nginx-and-nodejs.html
You can run php from node js using node-php: https://github.com/mkschreder/siteboot_php
I'm running a wss (secure websocket) server alongside my LAMP setup.
Node.js can easily run alongside any other web server (apache) you want. In #KitCarrau example, he lets node run on port 8084 - that's where it's running and listening to, not 80 or 443 etc (those are usually taken by apache anyway). But you can still use the same port to also serve http/https (in my case just stating some conf and general info that the service is up).
Starting from the console isn't the best way (remotely, node stops when closing the console).
I recommend taking a look at Running node as service
Easy to track log in realtime (log with console.log("hello"); in your application) with:
tail -f /var/.../SocketServer.log
Sample script (node-server.conf):
author ....
description "node.js server"
# used to be: start on startup
# until we found some mounts weren't ready yet while booting:
start on started mountall
stop on shutdown
# Automatically Respawn:
respawn
respawn limit 99 5
# Max open files are # 1024 by default. Bit few.
limit nofile 32768 32768
script
# Not sure why $HOME is needed, but we found that it is:
export HOME="/root"
exec node /var/.../SocketServer.js >> /var/www/node/.../SocketServer.log 2>&1
end script
post-start script
# Optionally put a script here that will notifiy you node has (re)started
# /root/bin/hoptoad.sh "node.js has started!"
echo "\n*********\nServer started\n$(date)\n*********" >> /var/.../SocketServer.log
end script
I am using MySQL 5.0 for a site that is hosted by GoDaddy (linux).
I was doing some testing on my web app, and suddenly I noticed that the pages were refreshing really slowly. Finally, after a long wait, I got to a page that said something along the lines of "MySQL Error, Too many connections...", and it pointed to my config.php file which connects to the database.
It has just been me connecting to the database, no other users. On each of my pages, I include the config.php file at the top, and close the mysql connection at the end of the page. There may be several queries in between. I fear that I am not closing mysql connections enough (mysql_close()).
However, when I try to close them after running a query, I receive connection errors on the page. My pages are PHP and HTML. When I try to close a query, it seems that the next one won't connect. Would I have to include config.php again after the close in order to connect?
This error scared me because in 2 weeks, about 84 people start using this web application.
Thanks.
EDIT:
Here is some pseudo-code of my page:
require_once('../scripts/config.php');
<?php
mysql_query..
if(this button is pressed){
mysql_query...
}
if(this button is pressed){
mysql_query...
}
if(this button is pressed){
mysql_query...
}
?>
some html..
..
..
..
..
<?php
another mysql_query...
?>
some more html..
..
..
<?php mysql_close(); ?>
I figured that this way, each time the page opens, the connection opens, and then the connection closes when the page is done loading. Then, the connection opens again when someone clicks a button on the page, and so on...
EDIT:
Okay, so I just got off the phone with GoDaddy. Apparently, with my Economy Package, I'm limited to 50 connections at a time. While my issue today happened with only me accessing the site, they said that they were having some server problems earlier. However, seeing as how I am going to have 84 users for my web app, I should probably upgrade to "Deluxe", which allows for 100 connections at a time. On a given day, there may be around 30 users accessing my site at a time, so I think the 100 would be a safer bet. Do you guys agree?
Shared-hosting providers generally allow a pretty small amount of simultaneous connections for the same user.
What your code does is :
open a connection to the MySQL server
do it's stuff (generating the page)
close the connection at the end of the page.
The last step, when done at the end of the page is not mandatory : (quoting mysql_close's manual) :
Using mysql_close() isn't usually
necessary, as non-persistent open
links are automatically closed at the
end of the script's execution.
But note you probably shouldn't use persistent connections anyway...
Two tips :
use mysql_connect insead of mysql_pconnect (already OK for you)
Set the fourth parameter of mysql_connect to false (already OK for you, as it's the default value) : (quoting the manual) :
If a second call is made to
mysql_connect() with the same
arguments, no new link will be
established, but instead, the link
identifier of the already opened link
will be returned.
The new_link
parameter modifies this behavior and
makes mysql_connect() always open a
new link, even if mysql_connect() was
called before with the same
parameters.
What could cause the problem, then ?
Maybe you are trying to access several pages in parallel (using multiple tabs in your browser, for instance), which will simulate several users using the website at the same time ?
If you have many users using the site at the same time and the code between mysql_connect and the closing of the connection takes lots of time, it will mean many connections being opened at the same time... And you'll reach the limit :-(
Still, as you are the only user of the application, considering you have up to 200 simultaneous connections allowed, there is something odd going on...
Well, thinking about "too many connections" and "max_connections"...
If I remember correctly, max_connections does not limit the number of connections you can open to the MySQL Server, but the total number of connections that can bo opened to that server, by anyone connecting to it.
Quoting MySQL's documentation on Too many connections :
If you get a Too many connections
error when you try to connect to the
mysqld server, this means that all
available connections are in use by
other clients.
The number of connections allowed is
controlled by the max_connections
system variable. Its default value is
100. If you need to support more connections, you should set a larger
value for this variable.
So, actually, the problem might not come from you nor your code (which looks fine, actually) : it might "just" be that you are not the only one trying to connect to that MySQL server (remember, "shared hosting"), and that there are too many people using it at the same time...
... And if I'm right and it's that, there's nothing you can do to solve the problem : as long as there are too many databases / users on that server and that max_connection is set to 200, you will continue suffering...
As a sidenote : before going back to GoDaddy asking them about that, it would be nice if someone could validate what I just said ^^
I had about 18 months of dealing with this (http://ianchanning.wordpress.com/2010/08/25/18-months-of-dealing-with-a-mysql-too-many-connections-error/)
The solutions I had (that would apply to you) in the end were:
tune the database according to MySQLTuner.
defragment the tables weekly based on this post
Defragmenting bash script from the post:
#!/bin/bash
# Get a list of all fragmented tables
FRAGMENTED_TABLES="$( mysql -e `use information_schema; SELECT TABLE_SCHEMA,TABLE_NAME
FROM TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','mysql') AND
Data_free > 0` | grep -v '^+' | sed 's,t,.,' )"
for fragment in $FRAGMENTED_TABLES; do
database="$( echo $fragment | cut -d. -f1 )"
table="$( echo $fragment | cut -d. -f2 )"
[ $fragment != "TABLE_SCHEMA.TABLE_NAME" ] && mysql -e "USE $database;
OPTIMIZE TABLE $table;" > /dev/null 2>&1
done
Make sure you are not using persistent connections. This is usually a bad idea..
If you've got that .. At the very most you will need to support just as much connections as you have apache processes. Are you able to change the max_connections setting?
Are you completely sure that the database server is completely dedicated to you?
Log on to the datbase as root and use "SHOW PROCESSLIST" to see who's connected. Ideally hook this into your monitoring system to view how many connections there are over time and alert if there are too many.
The maximum database connections can be configured in my.cnf, but watch out for running out of memory or address space.
If you have shell access, use netstat to see how many sockets are opened to your database and where they come from.
On Linux, type:
netstat -n -a |grep 3306
On windows, type:
netstat -n -a |findstr 3306
The solution could one of these, i came across this in a MCQA test, even i did not understood which one is right!
Set this in my.cnf "set-variable=max_connections=200"
Execute the command "SET GLOBALmax_connections = 200"
Use always mysql_connect() function in order to connect to the mysql server
Use always mysql_pconnect() function in order to connect to the mysql server
Followings are possible solutions:
1) Increase the max connection setting by setting the global variable in mysql.
set global max_connection=200;
Note: It will increase the server load.
2) Empty your connection pool as below :
FLUSH HOSTS;
3) check your processList and kill specific processlist if you don't want any of them.
You may refer this :-
article link