<?php

namespace App\Console\Commands;

use App\Http\Controllers\Auth\SwooleCommandController;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class alarm extends Command
{
    public $ws;
    private $token = 'zxc123456789ZXC';
    public $time = 10;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoolealarm {action?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'swoolealarm';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $action = $this->argument('action');
        switch ($action) {
            case 'close':
                break;
            default:
                $this->start();
                break;
        }

    }

    //开启WebSocket
    public function start()
    {
        $url = config('public.swoolwebsocketurl');
        $por = config('public.swoolwebsocketurlpor');
        $this->ws = new \swoole_websocket_server('0.0.0.0', 9601,SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL); //创建一个端口
        $this->ws->set(array(
            'reactor_num' => 2, //reactor线程数
            'worker_num' => 4,    //worker进程数
            'backlog' => 128,   //Listen队列长度
            'max_request' => 10,//最大连接
            'daemonize'=>0,//守护进程
            'ssl_cert_file' => base_path() . config('app.ssl_cert_file'),
            'ssl_key_file'  => base_path() . config('app.ssl_key_file'),
        ));

        $this->ws->on('open', function ($ws, $request) {
//            //链接成功
//            $userdata =  new SwooleCommandController();
//            $this->ws->push($request->fd,'11',1);
        });

        //监听WebSocket消息事件
        $this->ws->on('message', function ($ws, $frame) {
            $userdata =  new SwooleCommandController();
            $this->ws->push($frame->fd,$userdata->alarm($frame->data),1);
        });
        $this->ws->on('request', function ($request, $response,$from_id,$fd) {
        });
        //监听WebSocket连接关闭事件
        $this->ws->on('close', function ($ws, $fd) {
            echo "client:{$fd} is closed\n";
            swoole_timer_clear($this->time);
        });

        $this->ws->start();
    }
}
