server.php 5.9 KB
<?php
require_once __DIR__ . '/simplewind/vendor/autoload.php';
require_once __DIR__ . '/simplewind/vendor/workerman/workerman/Autoloader.php';

use Workerman\Lib\Timer;
use Workerman\Worker;

//定义心跳时间
define('HEARTBEAT_TIME', 60);
global $worker;
//创建一个监听端口
$worker = new Worker("tcp://114.215.223.17:5001");
// 启动1个进程对外提供服务
$worker->count = 1;

// 新增加一个属性,用来保存uid到connection的映射
$worker->uidConnections = array();







$worker->onWorkerStart = function ($worker) {
    global $db;

    global $worker;

    $db = new \Workerman\MySQL\Connection('rm-m5eblhc9o3515i25neo.mysql.rds.aliyuncs.com', '3306', 'db136s1ehvo1yn73', 'cxz307311SJK', 'fupai');
    //全局定时器
    Timer::add(1, function () use ($worker) {
        global $db;
        $time_now = time();
        foreach ($worker->connections as $connection) {
            // 有可能该connection还没收到过消息,则lastMessageTime设置为当前时间
            if (empty($connection->lastMessageTime)) {
                $connection->lastMessageTime = $time_now;
                continue;
            }
            // 上次通讯时间间隔大于心跳间隔,则认为客户端已经下线,关闭连接
            if ($time_now - $connection->lastMessageTime > HEARTBEAT_TIME) {
                $db->update('fp_light')->cols(array('status' => '2'))->where("number='$connection->uid'")->query();
            }
        }
    });

    // 开启一个内部端口,方便内部系统推送数据,Text协议格式 文本+换行符
    $inner_text_worker = new Worker('Text://114.215.223.17:5002');
    $inner_text_worker->onMessage = function ($connection, $buffer) {
        // $data数组格式,里面有uid,表示向那个uid的页面推送数据
        $data = json_decode($buffer, true);
        $uid = $data['uid'];
//        $connection->send($uid);
        // 通过workerman,向uid的页面推送数据
        $ret = sendMessageByUid($uid, $data['percent']);
        // 返回推送结果
        $connection->send($ret ? 'ok' : 'fail');
//        $connection->send($ret);
    };
    $inner_text_worker->listen();
};





//$worker->onConnect = function($connection)
//{
//    echo "new connection from ip " . $connection->getRemoteIp() . "\n";
//};
//
//$worker->onClose = function($connection)
//{
//    echo $connection->uid. "is exit" . "\n";
//};





// 当客户端发来数据时
$worker->onMessage = function ($connection, $data) use ($worker) {
    echo bin2hex($data)."\n";
    //记录最近的通讯信息
    $connection->lastMessageTime = time();
    //数据库资源
    global $db;
    //标记每个链接的uid
    if (!isset($connection->uid)) {
        // 没验证的话把第一个包当做uid(这里为了方便演示,没做真正的验证)
        $str=substr(bin2hex($data), 0, 6);
        $connection->uid =substr($str,4,2).substr($str,2,2).substr($str,0,2);
        /* 保存uid到connection的映射,这样可以方便的通过uid查找connection,
         * 实现针对特定uid推送数据
         */
        $worker->uidConnections[$connection->uid] = $connection;
        $re = $db->select('id')->from('fp_light')->where("number='$connection->uid'")->row();
        if (!$re) {
            $db->insert('fp_light')->cols(array(
                'number' => $connection->uid,))->query();
        } else {
                $db->update('fp_light')->cols(array('status' => '1'))->where("number='$connection->uid'")->query();
        }
    }
    //查询指令返回
    if (substr(bin2hex($data),2,2)=='03'){
        //设备状态
        if (substr(bin2hex($data),6,2)=='01'){
            $db->update('fp_light')->cols(array('status' => '1'))->where("number='$connection->uid'")->query();
        }else if(substr(bin2hex($data),6,2)=='02'){
            $db->update('fp_light')->cols(array('status' => '2'))->where("number='$connection->uid'")->query();
        }else{
            return false;
        }
        //点亮状态
        if (substr(bin2hex($data),10,2)=='00'){
            $db->update('fp_light')->cols(array('is_light' => '0'))->where("number='$connection->uid'")->query();
        }else if(substr(bin2hex($data),10,2)=='01'){
            $db->update('fp_light')->cols(array('is_light' => '1'))->where("number='$connection->uid'")->query();
        }else{
            return false;
        }
        //绑定状态
        if (substr(bin2hex($data),12,2)=='00'){
            $db->update('fp_light')->cols(array('is_blind' => '0'))->where("number='$connection->uid'")->query();
        }else if(substr(bin2hex($data),12,2)=='01'){
            $db->update('fp_light')->cols(array('is_blind' => '1'))->where("number='$connection->uid'")->query();
        }else{
            return false;
        }
        $name=substr(bin2hex($data),14);
        $name=substr($name,0,strpos($name, '00'));
        if(strlen($name)%2!=0){
            $name=$name.'0';
        }
        $arr=[];
        for($i=0;$i>=strlen($name);$i=$i+2){
            array_push($arr,'0X'.substr($name,$i,2));
        }
//        echo $arr;
        $str="";
        foreach ($arr as $k=>$v){
            if ($k<count($arr)-1) {
                $str .= chr($arr[$k]) . chr($arr[$k + 1]);
            }
        }
        $strr=iconv("GB2312", "UTF-8//IGNORE", $str)."\n";
        $db->update('fp_light')->cols(array('remark' => "$strr"))->where("number='$connection->uid'")->query();
    }
    //控制指令返回
    if (substr(bin2hex($data),2,4)=='10'){

    }
};


// 针对uid推送数据
function sendMessageByUid($uid, $message)
{
    global $worker;
    if (isset($worker->uidConnections[$uid])) {
        $connection = $worker->uidConnections[$uid];
        $str = '';
        for ($i = 0; $i < strlen($message); $i += 2) {
            $str .= chr(hexdec(substr($message, $i, 2)));
        }
        $connection->send($str);
        return true;
    }
//    echo $worker->uidConnections[$uid];
//    return $worker->uidConnections[$uid];
    return false;
}








Worker::runAll();