91 lines
2.4 KiB
PHP
91 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Service;
|
|
|
|
use Mosquitto\Client as MosquittoClient;
|
|
use App\Entity\JobOrder;
|
|
use Redis;
|
|
|
|
class MQTTClient
|
|
{
|
|
const PREFIX = 'motolite.control.';
|
|
const RIDER_PREFIX = 'motorider_';
|
|
const REDIS_KEY = 'events';
|
|
|
|
// protected $mclient;
|
|
protected $redis;
|
|
|
|
public function __construct($ip_address, $port, $cert)
|
|
{
|
|
// we use redis now
|
|
// we have an mqtt server listening on redis and sending to mqtt
|
|
$this->redis = new Redis();
|
|
$this->redis->connect('127.0.0.1', 6379);
|
|
|
|
/*
|
|
error_log("connecting to mqtt server - $ip_address : $port");
|
|
error_log("using $cert");
|
|
$this->mclient = new MosquittoClient();
|
|
$this->mclient->setTlsCertificates($cert);
|
|
$this->mclient->setTlsOptions(MosquittoClient::SSL_VERIFY_NONE, 'tlsv1');
|
|
$this->mclient->connect($ip_address, $port);
|
|
*/
|
|
}
|
|
|
|
public function __destruct()
|
|
{
|
|
// $this->mclient->disconnect();
|
|
}
|
|
|
|
public function publish($channel, $message)
|
|
{
|
|
// $this->mclient->publish($channel, $message);
|
|
|
|
$data = $channel . '|' . $message;
|
|
$this->redis->lpush(self::REDIS_KEY, $data);
|
|
}
|
|
|
|
public function sendEvent(JobOrder $job_order, $payload)
|
|
{
|
|
error_log('sending mqtt event: ');
|
|
error_log(print_r($payload, true));
|
|
|
|
$sessions = $job_order->getCustomer()->getMobileSessions();
|
|
if (count($sessions) == 0)
|
|
{
|
|
error_log("no sessions to send mqtt event to");
|
|
return;
|
|
}
|
|
|
|
// send to every customer session
|
|
foreach ($sessions as $sess)
|
|
{
|
|
$phone_num = $sess->getPhoneNumber();
|
|
$channel = self::PREFIX . $phone_num;
|
|
$this->publish($channel, json_encode($payload));
|
|
|
|
error_log('sent to ' . $channel);
|
|
}
|
|
}
|
|
|
|
public function sendRiderEvent(JobOrder $job_order, $payload)
|
|
{
|
|
// check if a rider is available
|
|
$rider = $job_order->getRider();
|
|
if ($rider == null)
|
|
return;
|
|
|
|
// check if rider has sessions
|
|
$sessions = $rider->getSessions();
|
|
if (count($sessions) == 0)
|
|
return;
|
|
|
|
// send to every rider session
|
|
foreach ($sessions as $sess)
|
|
{
|
|
$sess_id = $sess->getID();
|
|
$channel = self::RIDER_PREFIX . $sess_id;
|
|
$this->publish($channel, json_encode($payload));
|
|
}
|
|
}
|
|
}
|