示例#1
2
 public function init()
 {
     if (preg_match('/COM[0-9]+/', $this->source)) {
         $this->_logger->log(__METHOD__ . ' Check Serial port');
         // else it is COM port connection: it can be DataLogger or GSM modem
         ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', SMSCOMPort::getLinuxComName($this->source) . ' is Serial port.');
         try {
             // try to send AT command
             // if script recieves "OK" - this is GSM modem. Else - it can be only DataLogger
             $serial = new PhpSerial($this->_logger);
             $this->_logger->log(__METHOD__ . $this->source);
             $serial->deviceSet($this->source);
             $serial->confFlowControl(Yii::app()->params['com_connect_params']['hardwareflowcontrol']);
             $serial->confBaudRate(Yii::app()->params['com_connect_params']['baudrate']);
             $serial->confParity(Yii::app()->params['com_connect_params']['parity']);
             $serial->confStopBits(Yii::app()->params['com_connect_params']['stopbits']);
             $serial->confCharacterLength(Yii::app()->params['com_connect_params']['databits']);
             $this->_connector = new GsmModemSerialConnector($this->_logger, $serial);
             $this->_connector->setParams(array('port' => $this->source));
             ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', 'Script started to recognize hardware connected to PC via Serial port');
             if ($this->listener->additional_param == 'SMS') {
                 while (1) {
                     if ($this->_connector->check()) {
                         $this->_logger->log(__METHOD__, array('hardware' => 'modem'));
                         $this->hardware = 'modem';
                         ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', 'Hardware connected to PC via Serial port - is GSM Modem');
                         $this->_logger->log(__METHOD__, array('hardware' => $this->hardware));
                         return true;
                     }
                     sleep(60);
                 }
             }
             $this->_connector = new DataLoggerSerialConnector($this->_logger, $serial);
             $this->_connector->setParams(array('port' => $this->source));
             if ($this->listener->additional_param == 'DIRECT') {
                 if ($this->_connector->check()) {
                     $this->_logger->log(__METHOD__, array('hardware' => 'datalogger'));
                     $this->hardware = 'dl';
                     ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', 'Hardware connected to PC via Serial port - is Datalogger');
                     $this->_logger->log(__METHOD__, array('hardware' => $this->hardware));
                     return true;
                 }
             }
         } catch (Exception $e) {
             $this->_logger->log(__METHOD__, array('ExceptionMessage' => $e->getMessage()));
         }
         $this->_logger->log(__METHOD__, array('hardware' => 'unknown'));
         $this->hardware = 'unknown';
         ListenerProcess::addComment($this->listener->listener_id, 'hardware_recognizing', 'No device found.');
         $this->_logger->log(__METHOD__, array('hardware' => $this->hardware));
         return false;
     }
 }
 /**
  * 
  * @param string $message Message to sent to a client.
  * @return boolean True on success, false - otherwise.
  */
 public function sendMessage($message)
 {
     $this->_logger->log(__METHOD__, array('message' => $message));
     if ($this->_serial->_dState !== PhpSerial::SERIAL_DEVICE_OPENED) {
         $this->_logger->log(__METHOD__ . ' Serial port is not opened', array('port' => $this->_serial->_device));
         $this->_errors[] = 'Serial port ' . $this->_serial->_device . ' is not opened';
         return false;
     }
     $this->_serial->sendMessage($message);
     return true;
 }
 /**
  * Opens COM port and test it on specific device.
  * 
  * @return boolean True if device is found, false - otherwise.
  */
 public function check()
 {
     $this->_logger->log(__METHOD__);
     $result = false;
     set_error_handler(array($this, 'errorHandler'));
     try {
         if ($this->_serial->deviceSet($this->_port) === true) {
             if (!is_null($this->_baudrate)) {
                 $this->_serial->confBaudRate($this->_baudrate);
             }
             if (!is_null($this->_flowControl)) {
                 $this->_serial->confFlowControl($this->_flowControl);
             }
             if (!is_null($this->_parity)) {
                 $this->_serial->confParity($this->_parity);
             }
             if (!is_null($this->_stopBits)) {
                 $this->_serial->confStopBits($this->_stopBits);
             }
             if (!is_null($this->_dataBits)) {
                 $this->_serial->confCharacterLength($this->_dataBits);
             }
             if ($this->_serial->deviceOpen('r+b') === true) {
                 $result = $this->checkCustomData();
                 $this->_serial->deviceClose();
             } else {
                 $this->_errors[] = 'Can\'t open port "' . $this->_port . '".';
             }
         } else {
             $this->_errors[] = 'Can\'t set port "' . $this->_port . '".';
         }
     } catch (Exception $ex) {
         if ($this->_serial->_dState === PhpSerial::SERIAL_DEVICE_OPENED) {
             $this->_serial->deviceClose();
         }
         $this->_errors[] = $ex->getMessage();
     }
     restore_error_handler();
     $this->returnResult(__METHOD__, $result);
     return $result && count($this->_errors) === 0;
 }
 /**
  * 
  */
 public function send()
 {
     $this->_logger->log(__METHOD__, array('phone' => $this->_phoneNumber, 'message' => $this->_messageText));
     $this->_errors = array();
     set_error_handler(array($this, 'errorHandler'));
     try {
         if ($this->_serial->deviceSet($this->_serialPort) === true) {
             $this->_serial->confBaudRate($this->_serialPortParams['baudrate']);
             $this->_serial->confStopBits($this->_serialPortParams['stopbits']);
             $this->_serial->confParity($this->_serialPortParams['parity']);
             $this->_serial->confCharacterLength($this->_serialPortParams['databits']);
             $this->_serial->confFlowControl($this->_serialPortParams['hardwareflowcontrol']);
             if ($this->_serial->deviceOpen('r+b') === true) {
                 if ($this->sendSmsMessage()) {
                     $this->_logger->log(__METHOD__ . ' SMS message was sent', array('phone_number' => $this->_phoneNumber, 'serial_port' => $this->_serialPort, 'message' => $this->_messageText));
                     ListenerProcess::addComment($this->_listener->listener_id, 'sms_command', 'SMS message was sent to: "' . $this->_phoneNumber . '" using: ' . $this->_serialPort);
                 } else {
                     $this->_logger->log(__METHOD__ . ' Failed to send SMS message', array('phone_number' => $this->_phoneNumber, 'serial_port' => $this->_serialPort, 'message' => $this->_messageText));
                     ListenerProcess::addComment($this->_listener->listener_id, 'sms_command', 'Failed to send SMS message to: "' . $this->_phoneNumber . '" using: ' . $this->_serialPort);
                     $this->_errors[] = 'SMS message was not sent.';
                 }
                 $this->_serial->deviceClose();
             } else {
                 $this->_errors[] = 'Can\'t open port "' . $this->_serialPort . '".';
             }
         } else {
             $this->_errors[] = 'Can\'t set port "' . $this->_serialPort . '".';
         }
     } catch (Exception $ex) {
         if ($this->_serial->_dState === PhpSerial::SERIAL_DEVICE_OPENED) {
             $this->_serial->deviceClose();
         }
         $this->_errors[] = $ex->getMessage();
     }
     restore_error_handler();
     return count($this->_errors) === 0;
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     while (true) {
         $serial = new PhpSerial();
         // First we must specify the device. This works on both linux and windows (if
         // your linux serial device is /dev/ttyS0 for COM1, etc)
         $serial->deviceSet($this->argument('device'));
         // We can change the baud rate, parity, length, stop bits, flow control
         $serial->confBaudRate(9600);
         $serial->confParity("none");
         $serial->confCharacterLength(8);
         $serial->confStopBits(1);
         $serial->confFlowControl("none");
         $serial->deviceOpen();
         $read = '';
         $theResult = '';
         $start = microtime(true);
         while ($read == '' && microtime(true) <= $start + 0.5) {
             $read = $serial->readPort();
             if ($read != '') {
                 $theResult .= $read;
                 $read = '';
             }
         }
         $theResult = trim($theResult);
         if (!$theResult) {
             continue;
         }
         echo $theResult . "\n";
         $line = explode("\n", $theResult);
         foreach ($line as $l) {
             $l = trim($l);
             $watt_array = explode(" ", $l);
             $unitId = 1;
             if ($watt_array[0] == "watt" && isset($watt_array[1]) && $watt_array[1] != false) {
                 Watts::addWatt($unitId, $watt_array[1]);
                 //funtion sa models/Watts.php
                 Units::lessCredit($unitId, $watt_array[1]);
             }
         }
         $unitId = 1;
         if (Units::hasCredit($unitId)) {
             $serial->sendMessage("on");
         } else {
             $serial->sendMessage("off");
         }
         $serial->deviceClose();
     }
 }
<?php

require 'vendor/autoload.php';
$sensor = intval($_POST['sensor']);
$val = intval($_POST['value']);
$serial = new PhpSerial();
$serial->deviceSet("/dev/ttyACM0");
$serial->confBaudRate(57600);
$serial->confParity("none");
$serial->confCharacterLength(10);
$serial->confStopBits(1);
$serial->confFlowControl("none");
$serial->deviceOpen();
$byte = $val << 8;
$byte |= $sensor;
$serial->sendMessage($byte);
$serial->deviceClose();
示例#7
1
<?php

include 'PhpSerial.php';
// Let's start the class
$serial = new PhpSerial();
// First we must specify the device. This works on both linux and windows (if
// your linux serial device is /dev/ttyS0 for COM1, etc)
$serial->deviceSet("COM1");
// We can change the baud rate, parity, length, stop bits, flow control
$serial->confBaudRate(2400);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl("none");
// Then we need to open it
$serial->deviceOpen();
// To write into
$serial->sendMessage("Hello !");
// Or to read from
$read = $serial->readPort();
// If you want to change the configuration, the device must be closed
$serial->deviceClose();
// We can change the baud rate
$serial->confBaudRate(2400);
// etc...
//
//
/* Notes from Jim :
> Also, one last thing that would be good to document, maybe in example.php:
>  The actual device to be opened caused me a lot of confusion, I was
> attempting to open a tty.* device on my system and was having no luck at
示例#8
0
We then echo back the result received, and present the form again for additional input changes.
*/
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return (double) $usec + (double) $sec;
}
$the_input = $_POST['the_input'];
if ($the_input == '') {
    echo "<div id='newrequestbox'>";
    echo "<form id='FormName' name='FormName' action='example_VS421CPNTA.php' method='post'>\n            <table width=500>\n                <tr>\n                    <td>Switch to input? :</td>\n                    <td><input type=text name=the_input  maxlength=30 size=30></td>\n                    <td><input type=submit value='Switch'></td>\n                </tr>\n            </table>\n        </form>";
    echo "</div>";
} else {
    include 'PhpSerial.php';
    // Let's start the class
    $serial = new PhpSerial();
    // First we must specify the device. This works on both linux and windows (if
    // your linux serial device is /dev/ttyS0 for COM1, etc)
    // $serial->deviceSet("COM1");
    $serial->deviceSet("/dev/cu.usbserial-FTDY7ID6");
    // We can change the baud rate, parity, length, stop bits, flow control
    $serial->confBaudRate(2400);
    $serial->confParity("none");
    $serial->confCharacterLength(8);
    $serial->confStopBits(1);
    $serial->confFlowControl("none");
    // Then we need to open it
    $serial->deviceOpen();
    // To write into
    $serial->sendMessage("I" . $the_input);
    // Or to read from
    exit;
}
$tty = array();
while (false !== ($entry = readdir($handle))) {
    if (substr($entry, 0, 6) == 'ttyACM') {
        $tty[] = substr($entry, 6);
    }
}
if (empty($tty)) {
    DebMes("/dev/ttyACM* not found" . basename(__FILE__));
    exit;
}
sort($tty);
$updated_time = time();
try {
    $serial = new PhpSerial();
    $serial->deviceSet("/dev/ttyACM" . end($tty));
    $serial->confBaudRate(9600);
    $serial->confParity("none");
    $serial->confCharacterLength(8);
    $serial->confStopBits(1);
    $data = "";
    if ($serial->deviceOpen()) {
        DebMes("Open device " . end($tty) . ": " . basename(__FILE__));
        do {
            $data .= $serial->readPort();
            //GET /objects/?object=sensorGarage&op=m&m=statusChanged&status=%i HTTP/1.0
            $start = strpos($data, 'GET ');
            $end = strpos($data, ' HTTP/1.0');
            if ($start !== false && $end) {
                $url = BASE_URL . trim(substr($data, $start + 4, $end - $start - 4));
<?php

require 'vendor/autoload.php';
$serial = new PhpSerial();
$serial->deviceSet("/dev/ttyACM2");
$serial->confBaudRate(57600);
$serial->confParity("none");
$serial->confCharacterLength(32);
$serial->confStopBits(1);
$serial->confFlowControl("none");
$serial->deviceOpen();
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://127.0.0.1:5555");
/*new image*/
$new = "";
$MASK = 255;
$MASK2 = $MASK << 8;
$image = fopen("test2", "w");
$lastFrame = 0;
// default str
$defaultStr = getDefaultStr();
//
while (true) {
    $read = "";
    while (strlen($read .= $serial->readPort()) < 32) {
    }
    $dataStr = substr($read, 0, 32);
    $data = unpack('C*', $dataStr);
    $read = substr($read, count($data));
    $nFrames = ($data[1] << 8 & $MASK2) + $data[2];
示例#11
0
<?php

include 'PhpSerial.php';
// Let's start the class
$serial = new PhpSerial();
// First we must specify the device. This works on both linux and windows (if
// your linux serial device is /dev/ttyS0 for COM1, etc)
// If you are using Windows, make sure you disable FIFO from the modem's
// Device Manager properties pane (Advanced >> Advanced Port Settings...)
$serial->deviceSet("COM4");
// Then we need to open it
$serial->deviceOpen('w+');
// We may need to return if nothing happens for 10 seconds
stream_set_timeout($serial->_dHandle, 10);
// We can change the baud rate
$serial->confBaudRate(9600);
// SMS inbox query - mode command and list command
$serial->sendMessage("AT", 1);
var_dump($serial->readPort());
$serial->sendMessage("AT+CMGF=1\n\r", 1);
var_dump($serial->readPort());
$serial->sendMessage("AT+CMGL=\"ALL\"\n\r", 2);
var_dump($serial->readPort());
// If you want to change the configuration, the device must be closed
$serial->deviceClose();
<?php

require 'vendor/autoload.php';
set_time_limit(60 * 5);
$serial = new PhpSerial();
$serial->deviceSet("/dev/ttyACM0");
$serial->confBaudRate(57600);
$serial->confParity("none");
$serial->confCharacterLength(32);
$serial->confStopBits(1);
$serial->confFlowControl("none");
$source = file_get_contents(isset($_FILES['image']['tmp_name']) ? $_FILES['image']['tmp_name'] : 'descarga.png');
$serial->deviceOpen();
$index = 0;
$len = strlen($source);
$nFrames = ceil($len / 28);
$curFrame = 1;
$start = true;
$MASK = 255;
echo $nFrames . "\n";
while ($index < $len) {
    $aux = substr($source, $index, 28);
    $aux = chr($nFrames >> 8 & $MASK) . chr($nFrames & $MASK) . chr($curFrame >> 8 & $MASK) . chr($curFrame & $MASK) . $aux;
    echo $curFrame . "\n";
    $serial->sendMessage($aux);
    while ($serial->readPort() == "") {
    }
    $index += 28;
    $curFrame++;
}
$serial->deviceClose();
示例#13
0
 protected function _transmit($message, $fetch_answer = false)
 {
     $this->last_message = $message;
     $this->last_raw_message = $this->_buildRawMessage($this->last_message);
     $this->last_answer = '';
     $this->last_raw_answer = '';
     // start the serial connection
     $serial = $serial = new PhpSerial();
     // First we must specify the device. This works on both linux and windows (if
     // your linux serial device is /dev/ttyS0 for COM1, etc)
     $serial->deviceSet($this->serial_port);
     // We can change the baud rate, parity, length, stop bits, flow control
     // http://forum.mysensors.org/topic/340/pidome-domotica-home-automation
     $serial->confBaudRate(115000);
     $serial->confParity("none");
     $serial->confCharacterLength(8);
     $serial->confStopBits(1);
     $serial->confFlowControl("none");
     // ?
     // Then we need to open it
     $serial->deviceOpen();
     // we may have to sleep before arduino restart ?
     // http://stackoverflow.com/questions/13114275/php-serial-port-data-return-from-arduino
     //sleep($this->arduino_boot_time);
     // We may need to return if nothing happens for $timeout seconds
     if ($fetch_answer) {
         $timeout = $this->socket_timeout_answer;
     } else {
         $timeout = $this->socket_timeout_message;
     }
     stream_set_timeout($serial->_dHandle, $timeout);
     // send message
     $serial->sendMessage($this->last_raw_message . "\n");
     if ($fetch_answer) {
         $line = '';
         $until_t = time() + $timeout;
         while (true) {
             if (!$serial->_dHandle or time() > $until_t) {
                 break;
             }
             $line = $serial->readPort();
             if ($this->last_answer = $this->_filterAnswer($line)) {
                 $this->last_raw_answer = trim($line);
                 $out = $this->last_answer['payload'];
                 break;
             }
         }
     } else {
         $out = true;
     }
     $serial->deviceClose();
     return $out;
 }
示例#14
0
 public function test_AtAndCpinCommands()
 {
     $connector = new PhpSerial();
     $connector->deviceSet('COM1');
     $connector->confBaudRate(9600);
     $connector->confParity('none');
     $connector->confFlowControl('rts/cts');
     $connector->confCharacterLength(8);
     $connector->confStopBits(1);
     $connector->deviceOpen('r+b');
     stream_set_timeout($connector->_dHandle, 2);
     $connector->sendMessage("AT+CPIN?\r\n");
     $result = $connector->readPort();
     $connector->deviceClose();
     $result = explode("\r\n", $result);
     $this->assertEquals(4, count($result));
     $this->assertEquals('AT+CPIN?', $result[0]);
     $this->assertEmpty($result[1]);
     $this->assertEquals('+CPIN: READY', $result[2]);
     $this->assertEmpty($result[3]);
 }
示例#15
0
文件: servo2.php 项目: rxcoder/human
<?php

set_time_limit(0);
include "PhpSerial.php";
// Let's start the class
$serial = new PhpSerial();
$serial->deviceSet("COM2");
// We can change the baud rate, parity, length, stop bits, flow control
//$serial->confParity("none");
//$serial->confCharacterLength(8);
//$serial->confStopBits(1);
//$serial->confFlowControl("none");
// Then we need to open it
if (!$serial->deviceOpen()) {
    exit("script closed");
}
$serial->confBaudRate(9600);
$servos = $_REQUEST['servos'] ? $_REQUEST['servos'] : array(0, 88, 90, 48, 90, 93, 90, 89, 92, 97, 50, 90, 94);
//$fp =fopen("com2", "a");
// send('');
//sleep(5);
//send("s01".$servos[1].";02".$servos[2].";03".$servos[3].";");
//send("s04".$servos[4].";05".$servos[5].";06".$servos[6].";");
//send("s07".$servos[7].";08".$servos[8].";09".$servos[9].";");
//send("s10".$servos[10].";11".$servos[11].";12".$servos[12].";");
send("s01" . $servos[1] . ";", true);
send("s02" . $servos[2] . ";", true);
send("s03" . $servos[3] . ";", true);
send("s04" . $servos[4] . ";", true);
send("s05" . $servos[5] . ";", true);
send("s06" . $servos[6] . ";", true);
示例#16
0
文件: servo.php 项目: hck509/arduino
<?php

include 'lib/serial/src/PhpSerial.php';
$serial = new PhpSerial();
$serial->deviceSet("COM11");
//$serial->confBaudRate(9600);
//$serial->confParity("even");
//$serial->confCharacterLength(7);
//$serial->confStopBits(1);
//$serial->confFlowControl("rts/cts");
$serial->deviceOpen('w+');
sleep(5);
// We may need to return if nothing happens for 20 seconds
stream_set_timeout($serial->_dHandle, 20);
for ($i = 0; $i < 100; ++$i) {
    $serial->sendMessage("30,50;");
    var_dump($serial->readPort());
    sleep(0.03);
}
$serial->deviceClose();
示例#17
0
文件: sms.php 项目: kabacs/SMS.server
function enviarSMS($nr_tlm, $sms)
{
    $serial = new PhpSerial();
    $serial->deviceSet("COM6");
    //choose COM port
    $serial->confBaudRate(9600);
    //Choose Bitrate
    $serial->deviceOpen('w+');
    //Open COM port
    $serial->sendMessage("AT" . chr(13));
    //Check if is acessible
    //read response and check if it can continue
    $codigo_at = $serial->readPort();
    $verificar = substr($codigo_at, -4);
    if (substr($verificar, 0, 2) == 'OK') {
        $serial->sendMessage("AT+CMGF=1" . chr(13));
        //Prepare to SMS
        //read response and check if it may continue
        $codigo_at = $serial->readPort();
        $verificar = substr($codigo_at, -4);
        if (substr($verificar, 0, 2) == 'OK') {
            $serial->sendMessage('AT+CMGS="' . $nr_tlm . '"' . chr(13));
            //send destination number
            $serial->sendMessage($sms . chr(26));
            //send SMS text
            sleep(5);
            //read response and check if the sms was sent
            $codigo_at = $serial->readSMS();
            $verificar = substr($codigo_at, -4);
            if (substr($verificar, 0, 2) == 'OK') {
                $resposta = "OK";
            } else {
                $resposta = "NOK";
            }
        } else {
            $resposta = "NOK";
        }
    } else {
        $resposta = "NOK";
    }
    $serial->deviceClose();
    //close COM port - NEVER FORGET THIS STEP!
    return $resposta;
}
示例#18
0
$XB1M = pack("CC", 0xc3, 0x1b);
$XB2S = pack("CCCCCCCC", 0x0, 0x13, 0xa2, 0x0, 0x40, 0xa1, 0x3e, 0xfd);
$XB2M = pack("CC", 0xfe, 0x72);
$XB3S = pack("CCCCCCCC", 0x0, 0x13, 0xa2, 0x0, 0x40, 0xa1, 0x40, 0x16);
$XB3M = pack("CC", 0x66, 0xcf);
$XB4S = pack("CCCCCCCC", 0x0, 0x13, 0xa2, 0x0, 0x40, 0xa1, 0x3f, 0x43);
$XB4M = pack("CC", 0x61, 0xef);
$outstr = isset($_GET['req']) ? $_GET['req'] : "[S]";
$reqlen = strlen($outstr);
$reqlen = $reqlen + 14;
// which index
$lbracket = strpos($outstr, "[");
$rbracket = strpos($outstr, "]", $lbracket);
$cmdstr = substr($outstr, $lbracket + 1, $rbracket - $lbracket - 1);
// Let's start the class
$serial = new PhpSerial();
// First we must specify the device. This works on both linux and windows (if
// your linux serial device is /dev/ttyS0 for COM1, etc)
$serial->deviceSet("/dev/ttyAMA0");
// We can change the baud rate, parity, length, stop bits, flow control
$serial->confBaudRate(9600);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl("none");
// Then we need to open it
do {
    $serial->deviceOpen();
} while (!$serial->_ckOpened());
$serial->_exec("stty -F /dev/ttyAMA0 -isig", $out);
$serial->_exec("stty -F /dev/ttyAMA0 -icanon", $out);