Browse Source

CHG: new find box service with Async calls using generics
UPD: bump to version 1.9.20

Giancarlo Voci 7 years ago
parent
commit
2a1b00a5d2

+ 1 - 1
cfg/config.bin

@@ -1 +1 @@
-eJyFkV9v2jAUxd/vp4jytGlq4hCg3ZClhWAgbYhR/iC2CkUhGIia2Cxx2FrEd5/JOu1xlixdXfno/M7x86EU26xsNrAiYeTRAFvGwEDgJDH1qTPBelPnpg6u486JhrU4TAgkHm4Lc18LLhnfmTAh42SGe0ACl068YIb1JJ7ePegw92ZzX90Y75UHg0cnNNivU1EzfLnIomIfPn6yrYE9RAhdrzCJAqxXr82P8stRNBKXIs/K2zQ6iVpi20bD0W7Ls4phUZUFf9Fht20bVuNaCKnmU9Y0WJwYrwq+g4WzTse+FzylsbcgaURcbCPUrUMSh9/SKQ3TqZP4MbaQCrHCsm4ZwEhbZvIIYyciSehj848XRF5MAmdBMF3c+beFT2c0dZMopgsSqkBf3xXXq6k4mGzMosoOrDFLcRDGiR/Ac2mQ3mRJ/L/3rewUCiZiJcul9vNY5EctbxspKlZreak0GuPZtmTwF6LDe8eFZ5eGxNhvN7dAtdi1uSwEh65Z63PPsIYPhoUMq4+gq3eA+n2786vPyiAmUQwv7BW76N+xrP59H/VsNLiHruzv9eHt5fxY0yceRC5f8tmb3V6cIZtHwXp1bkBxTL1gMqbriIQrzyUbiHxClrcvUZYIljRU/ffsPvwGWErJmw==
+eJyFkV1v2jAUhu/Pr4i42jQ1cUigbJGlhWAgbYhZvsRWIRSCgaiJTfMBpYj/vpB12kUvZsnS0ZHf8z7n9dMuE+s4K5cQEc+3qYtVuScjMMOAOtQc4U5ZJEoHLNOaEglLgRcSCG1cp8q2ELxifKPAiAzDCe4CcS06st0J7oTB+G7Qgak9mTrNDfC28WDwYHoyez2kBcOXS5Xm7NPnL5ra0/oIoesVRr6LO/m5fMm+7UVZ4UwkcXarjIMoKqxpqG9s1jzOGRZ5lvLnDmzWdckKXAhRNfUhLkssDoznKd/AzFysPBJ4P1dj6q3GZugEWEUNbYSromYAhjSPqz0MTZ+EnoOVP0PBtwPimjOC6ezOuTUcOqErK/QDOiNeQ/79XXG9Ko0hq0olzeMdK5VM7IR84DuwLequbrIw+N/7umoVDYzPMpZU0mmfJnspqctK5KyQkqzRSIzH64zBX4gW7x0XnizqEXm7Xt4WKsSmTqpUcDDaDNWvXVntD2QVyaqO4EMPQZttD+m61jIUx8Y0IH4AxjM7Ywv9O6qq3+uoq6HePRht1r+K3dvz8aGgj9z1LT7nkzetvph9NvXdRXQs4eOIXg91VV1HOrQTnCgLdTZXt/EgMh9P233a3e9+nF+Og/h84hO1WW9su6MhXfjEi2yLLGFOveYju5oOvwHpNtgs

+ 37 - 0
cfg/config.ini

@@ -0,0 +1,37 @@
+[globals]
+VERSION=1.5.0
+AUTOLOAD="src/"
+CACHE = TRUE
+UI=ui/frontend/
+DEBUG=2
+ENCODING="UTF-8"
+HIGHLIGHT=false
+JAR.expire={{time()+31536000}}
+DSN="mysql:host=localhost;port=3306;dbname=omlink"
+dbuser=root
+dbpass=openmind
+MAX_RETRY_FOR_FAULT=10
+DEV=true
+
+; Path
+BASEURL=/omlink
+SITENAME=OM-Link
+LOGO_CUSTOMER={{@BASEURL}}/assets/images/logo.png
+ICON_LOGOUT={{@BASEURL}}/assets/images/logout.png
+
+; Select which customer class enable
+CUSTOMERNAME=omlink
+
+[CORE.fb]
+; Production
+;host=192.168.10.140
+host=192.168.10.10
+port=50443
+; Server TEST
+;key=C0000000000011474023057
+;pass=ZrgzkvJrOKnNSCnPnGz3u{A6eHSNXVvs
+key=C0000000000011550214404
+pass=LVlU4eP1fa8VAKwfhi2hgQyqv8aywnG1
+
+[FINDBOXSERVICE]
+PORT=1234

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
 {
 	"name": "OM-Link",
 	"name": "OM-Link",
-	"version": "1.9.7",
+	"version": "1.9.20",
 	"private": true,
 	"private": true,
 	"description": "OM-Link Engine",
 	"description": "OM-Link Engine",
 	"author": "Open Mind",
 	"author": "Open Mind",

+ 51 - 0
src/Modules/Blank/Pages.php

@@ -8,15 +8,66 @@
 
 
 namespace Modules\Blank;
 namespace Modules\Blank;
 
 
+use Base;
+use OpenMind\FindBox\QueueCommand;
+use OpenMind\System\QueueSystem;
 use OpenMind\Web\Controller;
 use OpenMind\Web\Controller;
 use Template;
 use Template;
 
 
 class Pages extends Controller
 class Pages extends Controller
 {
 {
+
+	/**
+	 * @param Base $f3
+	 */
 	public function HelloWorld($f3)
 	public function HelloWorld($f3)
 	{
 	{
+
+		$this->BlinkOFF('0113C333');
+		$this->BlinkOFF('0113C371');
+		$this->BlinkOFF('0113C330');
+		$this->BlinkOFF('0113C374');
+
+		$this->BlinkON('0113C333');
+		$this->BlinkON('0113C371');
+
+		$this->BlinkON('0113C330');
+		$this->BlinkON('0113C374');
+		$this->BlinkOFF('0113C333');
+		$this->BlinkOFF('0113C371');
+
+		$this->BlinkON('0113C337');
+		$this->BlinkON('0113C2FE');
+		$this->BlinkON('0113C377');
+		$this->BlinkON('0113C2FB');
+
+
+		$this->BlinkOFF('0113C330');
+		$this->BlinkOFF('0113C374');
+		$this->BlinkOFF('0113C337');
+		$this->BlinkOFF('0113C2FE');
+		$this->BlinkOFF('0113C377');
+		$this->BlinkOFF('0113C2FB');
+
+
 		$f3->set('MESSAGE', 'Hello World');
 		$f3->set('MESSAGE', 'Hello World');
 		$f3->set('CONTENT', 'message.tpl');
 		$f3->set('CONTENT', 'message.tpl');
 		echo Template::instance()->render('masterpage.tpl');
 		echo Template::instance()->render('masterpage.tpl');
 	}
 	}
+
+	public function BlinkOFF(string $labelID)
+	{
+		$qs = new QueueSystem();
+		$cmd = new QueueCommand($labelID);
+		$cmd->setToBlinkOff();
+		$qs->send($cmd);
+	}
+
+	public function BlinkON(string $labelID)
+	{
+		$qs = new QueueSystem();
+		$cmd = new QueueCommand($labelID);
+		$cmd->setLeds(2, 1, 1000, 300, 1);
+		$qs->send($cmd);
+	}
 }
 }

+ 27 - 0
src/OpenMind/FindBox/FindBoxCoreSystem.php

@@ -111,6 +111,33 @@ class FindBoxCoreSystem
 			"value" => $val);
 			"value" => $val);
 	}
 	}
 
 
+	public function AsyncCallAPI(string $URI, string $Parameters, bool $skipResponse = false)
+	{
+		$bodyJSON = null;
+		$auth = "Authorization: Basic " . base64_encode("{$this->Key}:{$this->Pass}") . "\r\n";
+
+		$streamfbOS = @stream_socket_client("tcp://{$this->Host}:{$this->Port}", $errno, $errstr, 1);
+		if (!$streamfbOS) {
+			return $this->returnCode($errno, $errstr);
+		} else {
+			stream_set_blocking($streamfbOS, false);
+			//$requestText = "{$method} {$URI}{$Parameters} HTTP/1.0\r\nHost: {$this->Host}\r\n{$auth}Accept: */*\r\nConnection: close\r\n\r\n";
+			$requestBodyLength = strlen($Parameters);
+			$requestText = "POST {$URI} HTTP/1.0\r\nHost: {$this->Host}\r\n{$auth}Accept: */*\r\nContent-Type: application/json\r\nContent-Length: {$requestBodyLength}\r\n\r\n{$Parameters}\r\n";
+			fwrite($streamfbOS, $requestText);
+			if (!$skipResponse) {
+				while ('' == $r = stream_get_contents($streamfbOS))
+					yield $r;
+				list(, $bodyJSON) = explode("\r\n\r\n", $r, 2);
+			}
+			fclose($streamfbOS);
+		}
+
+		$bodyJSON = ($bodyJSON == null) ? "{}" : $bodyJSON;
+
+		yield $this->returnCode(0, $bodyJSON);
+	}
+
 	public function BlinkUnassigned()
 	public function BlinkUnassigned()
 	{
 	{
 		$URI = "/1.0.0/index.php/smartesl.blink_unassigned/2.0.0/";
 		$URI = "/1.0.0/index.php/smartesl.blink_unassigned/2.0.0/";

+ 129 - 52
src/OpenMind/FindBox/FindBoxService.php

@@ -8,19 +8,96 @@
 
 
 namespace OpenMind\FindBox;
 namespace OpenMind\FindBox;
 
 
+use Base;
 use DB\SQL;
 use DB\SQL;
 use Exception;
 use Exception;
-use F3;
 use Log;
 use Log;
 use OpenMind\System\QueueSystem;
 use OpenMind\System\QueueSystem;
+use OpenMind\System\System;
+
+class AsyncJobClass
+{
+	/** @var integer $retryForFault */
+	public $retryForFault;
+	/** @var SmartESL $esl */
+	private $esl;
+	/** @var \Generator $blinkGenerator */
+	private $blinkGenerator;
+
+	/** @var array|null ledParams */
+	private $ledParams;
+
+	/** @var bool $blinkoff */
+	private $blinkoff = false;
+
+	/**
+	 * AsyncJobClass constructor.
+	 *
+	 * @param FindBoxCoreSystem $fb
+	 * @param string $labelID
+	 * @param array|null $ledParams if null, the blink become blinkOFF
+	 */
+	public function __construct(FindBoxCoreSystem $fb, string $labelID, array $ledParams = null)
+	{
+		global $f3;
+
+		$this->esl = new SmartESL($fb, [$labelID]);
+		$this->ledParams = $ledParams;
+		$this->retryForFault = $f3->get('MAX_RETRY_FOR_FAULT');
+	}
+
+	public function BlinkON()
+	{
+		$this->blinkGenerator =
+			$this->esl->AsyncBlinkSpecial(
+				$this->ledParams['pattern'],
+				$this->ledParams['repeat'],
+				$this->ledParams['iter_time'],
+				$this->ledParams['iterations'],
+				$this->ledParams['color']
+			);
+	}
+
+	public function BlinkOFF()
+	{
+		$this->blinkoff = true;
+		$this->blinkGenerator = $this->esl->AsyncBlinkOff();
+	}
+
+	/**
+	 * @return bool
+	 */
+	public function isBlinkoff(): bool
+	{
+		return $this->blinkoff;
+	}
+
+	public function GetCurrentValue()
+	{
+		return $this->blinkGenerator->current();
+	}
+
+	public function Next()
+	{
+		$this->blinkGenerator->next();
+	}
+}
 
 
 class FindBoxService
 class FindBoxService
 {
 {
 	/** @var SQL $dbHandle */
 	/** @var SQL $dbHandle */
 	private $dbHandle;
 	private $dbHandle;
+
+	/** @var FindBoxCoreSystem|null findBoxCore */
 	private $findBoxCore = null;
 	private $findBoxCore = null;
-	private $labelToBlink;
+
+	/** @var Log $ServiceLogger */
 	private $ServiceLogger;
 	private $ServiceLogger;
+
+	/** @var array $labelToBlink */
+	private $labelToBlink;
+
+	/** @var QueueSystem $qs_Server */
 	private $qs_Server;
 	private $qs_Server;
 
 
 	public function __construct()
 	public function __construct()
@@ -45,15 +122,18 @@ class FindBoxService
 	}
 	}
 
 
 	/**
 	/**
-	 * Called from php spawn process. This script end after MAX_BLINK_TIME
+	 * Called from php spawn process.
 	 *
 	 *
-	 * @param F3 $f3
+	 * @param Base $f3
 	 */
 	 */
 	public function Main($f3)
 	public function Main($f3)
 	{
 	{
 		$this->ServiceLogger->write("Starting FindBoxService main loop", 'd/m/Y H:i:s');
 		$this->ServiceLogger->write("Starting FindBoxService main loop", 'd/m/Y H:i:s');
 		$this->ServiceLogger->write("Opening socket listen {$f3->get('FINDBOXSERVICE.PORT')}", 'd/m/Y H:i:s');
 		$this->ServiceLogger->write("Opening socket listen {$f3->get('FINDBOXSERVICE.PORT')}", 'd/m/Y H:i:s');
 
 
+		/** @var AsyncJobClass[] $jobs */
+		$jobs = [];
+
 		while (true) {
 		while (true) {
 
 
 			$this->getCurrentQueue();
 			$this->getCurrentQueue();
@@ -64,47 +144,50 @@ class FindBoxService
 					case QueueCommand::$Q_BLINK_OFF:
 					case QueueCommand::$Q_BLINK_OFF:
 						$this->ServiceLogger->write("BlinkOff for label {$label->id} requested", 'd/m/Y H:i:s');
 						$this->ServiceLogger->write("BlinkOff for label {$label->id} requested", 'd/m/Y H:i:s');
 
 
-						$esl = new SmartESL($this->findBoxCore, [$label->id]);
-						$err = $esl->BlinkOff();
+						// Rimuove il JOB se esiste
+						$asyncBlinkOFF = new AsyncJobClass($this->findBoxCore, $label->id, NULL);
+						$asyncBlinkOFF->BlinkOFF();
+						$jobs[$label->id] = $asyncBlinkOFF;
 
 
-						if ($this->ManageBlinkFaults($label->id, $err))
-							unset($this->labelToBlink[$labelId]);
+						unset($this->labelToBlink[$label->id]);
 
 
 						break;
 						break;
 
 
 					case QueueCommand::$Q_BLINK_ON:
 					case QueueCommand::$Q_BLINK_ON:
-						// Priority 1
-						// ----------
-						// Force exit and blink off if run time script > MAX_BLINK_TIME_SEC
-						$now = time() - $label->tsFirstBlink;
-						if ($now > $f3->get('MAX_BLINK_TIME_SEC')) {
-							$this->ServiceLogger->write("Stop label {$label->id} for timeout", 'd/m/Y H:i:s');
-							$esl = new SmartESL($this->findBoxCore, [$label->id]);
-							$esl->BlinkOff();
-							unset($this->labelToBlink[$labelId]);
-							continue;
-						}
-
-						// Priority 2
-						// ----------
-						// Restart blink if blink is ended
-						$blinkEndTime = time() - $label->tsLastLongBlink;
-						/** @var QueueCommand $label */
-						$calcDuration = $label->getBlinkDuration();
-						if ($blinkEndTime > $calcDuration) {
-							$this->ServiceLogger->write("Auto restart blinking for label $label->id\n", 'd/m/Y H:i:s');
-
-							$esl = new SmartESL($this->findBoxCore, [$label->id]);
-							$ledParams = $label->params;
-
-							$err = $esl->BlinkSpecial($ledParams['pattern'], $ledParams['repeat'], $ledParams['iter_time'], $ledParams['iterations'], $ledParams['color']);
-
-							$this->ManageBlinkFaults($label->id, $err);
-
-						}
+						$asyncBlink = new AsyncJobClass($this->findBoxCore, $label->id, $label->params);
+						$asyncBlink->BlinkON();
+						$jobs[$label->id] = $asyncBlink;
+
+						unset($this->labelToBlink[$label->id]);
+
 						break;
 						break;
 				}
 				}
 			}
 			}
+
+			// Async check on JOBS
+			foreach($jobs as $labelID => $asyncBlink) {
+
+				$err = $asyncBlink->GetCurrentValue();  // Fa scattare il generator e ricava il valore
+
+				// Response RESTful ricevuta da Findbox Core?
+				if (is_array($err)) {
+
+					if ($this->ManageBlinkFaults($asyncBlink, $labelID, $err)) {
+						// Rimuove il JOB
+						unset($jobs[$labelID]);
+					} else {
+						// Restart job With errors
+						if ($jobs[$labelID]->isBlinkoff())
+							$jobs[$labelID]->BlinkOFF();
+						else
+							$jobs[$labelID]->BlinkON();
+					}
+
+				} else
+					$asyncBlink->Next();
+
+			}
+
 		}
 		}
 
 
 		return;
 		return;
@@ -125,7 +208,6 @@ class FindBoxService
 				case QueueCommand::$Q_BLINK_ON:
 				case QueueCommand::$Q_BLINK_ON:
 				case QueueCommand::$Q_BLINK_OFF:
 				case QueueCommand::$Q_BLINK_OFF:
 					$this->labelToBlink[$qCommand->id] = $qCommand;
 					$this->labelToBlink[$qCommand->id] = $qCommand;
-					$this->labelToBlink[$qCommand->id]->retryForFault = $f3->get('MAX_RETRY_FOR_FAULT');
 					break;
 					break;
 				case QueueCommand::$Q_DISPLAY:
 				case QueueCommand::$Q_DISPLAY:
 					$this->ServiceLogger->write("Change display for label {$qCommand->id} requested", 'd/m/Y H:i:s');
 					$this->ServiceLogger->write("Change display for label {$qCommand->id} requested", 'd/m/Y H:i:s');
@@ -144,7 +226,7 @@ class FindBoxService
 	 */
 	 */
 	public function saveProduct($label)
 	public function saveProduct($label)
 	{
 	{
-		if ($label->operation == Q_SAVEPRODUCT) {
+		if ($label->operation == QueueCommand::$Q_SAVEPRODUCT) {
 			$this->findBoxCore->SaveProducts($label->id, $label->description, $label->params['dataFields']);
 			$this->findBoxCore->SaveProducts($label->id, $label->description, $label->params['dataFields']);
 			$this->ServiceLogger->write("Save product {$label->id}", 'd/m/Y H:i:s');
 			$this->ServiceLogger->write("Save product {$label->id}", 'd/m/Y H:i:s');
 			return true;
 			return true;
@@ -157,26 +239,21 @@ class FindBoxService
 	 * @param $fbError
 	 * @param $fbError
 	 * @return bool true if no error, false if error
 	 * @return bool true if no error, false if error
 	 */
 	 */
-	private function ManageBlinkFaults($labelId, $fbError): bool
+	private function ManageBlinkFaults(AsyncJobClass &$job, $labelId, $fbError): bool
 	{
 	{
-		global $f3;
 		$labelResponses = $this->findBoxCore->getLabelsFromResponse($fbError);
 		$labelResponses = $this->findBoxCore->getLabelsFromResponse($fbError);
-		$label = &$this->labelToBlink[$labelId];
 
 
-		if ($labelResponses && isset($labelResponses[$label->id]) && $labelResponses[$label->id]) { // Label exists and is true, mean that's all OK, no error
-			$label->retryForFault = $f3->get('MAX_RETRY_FOR_FAULT');
-			$label->tsLastLongBlink = time() + 2;
+		if ($labelResponses && isset($labelResponses[$labelId]) && $labelResponses[$labelId]) { // Label exists and is true, mean that's all OK, no error
 			return true;
 			return true;
 		}
 		}
 
 
 		// Ho finito il numero di tentativi massimi?
 		// Ho finito il numero di tentativi massimi?
-		if ($label->retryForFault < 0) {  // Rimuovo dalla coda l'etichetta
-			$this->ServiceLogger->write("Label {$label->id} fatal error. Removing from queue", 'd/m/Y H:i:s');
-			unset($this->labelToBlink[$labelId]);
-		} else {                          // Riprovo al prossimo ciclo
-			$this->ServiceLogger->write("Label {$label->id} blink error. Try next cycle...", 'd/m/Y H:i:s');
-			$label->tsLastLongBlink = 0;
-			$label->retryForFault--;
+		if ($job->retryForFault < 0) {  // Rimuovo dalla coda l'etichetta
+			$this->ServiceLogger->write("Label {$labelId} fatal error. Removing from queue", 'd/m/Y H:i:s');
+			return true;
+		} else {                        // Riprovo al prossimo ciclo
+			$this->ServiceLogger->write("Label {$labelId} blink error. Try next cycle...", 'd/m/Y H:i:s');
+			$job->retryForFault--;
 		}
 		}
 
 
 		return false; // Default return value
 		return false; // Default return value

+ 6 - 10
src/OpenMind/FindBox/QueueCommand.php

@@ -10,24 +10,20 @@ namespace OpenMind\FindBox;
 
 
 class QueueCommand
 class QueueCommand
 {
 {
+	static public $Q_BLINK_ON = 1;
+	static public $Q_BLINK_OFF = 2;
+	static public $Q_SAVEPRODUCT = 3;
+	static public $Q_DISPLAY = 4;
+
 	public $id;
 	public $id;
 	public $operation;
 	public $operation;
 	public $description;
 	public $description;
 	public $params;
 	public $params;
-	public $tsFirstBlink;
-	public $tsLastLongBlink;
-
-	static public $Q_BLINK_ON = 1;
-	static public $Q_BLINK_OFF = 2;
-	static public $Q_SAVEPRODUCT = 3;
-	static public $Q_DISPLAY =4;
 
 
 	public function __construct(string $labelID)
 	public function __construct(string $labelID)
 	{
 	{
 		$this->id = $labelID;
 		$this->id = $labelID;
 		$this->params = null;
 		$this->params = null;
-		$this->tsLastLongBlink = time() - 3600;
-		$this->tsFirstBlink = time();
 	}
 	}
 
 
 	/**
 	/**
@@ -83,7 +79,7 @@ class QueueCommand
 	 */
 	 */
 	public function getBlinkDuration(): int
 	public function getBlinkDuration(): int
 	{
 	{
-		return (($this->params['iter_time'] / 1000) * ($this->params['iterations'] - 1)) * $this->params['repeat'];
+		return ((($this->params['iter_time'] / 1000) * ($this->params['iterations'])) * $this->params['repeat']);
 	}
 	}
 
 
 	/**
 	/**

+ 17 - 0
src/OpenMind/FindBox/SmartESL.php

@@ -74,6 +74,23 @@ class SmartESL
 		return $this->core->CallAPI($URI, $uriParams);
 		return $this->core->CallAPI($URI, $uriParams);
 	}
 	}
 
 
+	public function AsyncBlinkSpecial(int $pattern, int $repeat, int $iter_time, int $iterations, int $ledColor = 0)
+	{
+
+		$uriParams = json_encode(array_merge(
+			array($this->labels),
+			array($pattern, $ledColor, $repeat, $iter_time, $iterations, 1)));
+
+		$URI = "/1.0.0/index.php/smartesl.blink_special/2.0.0/";
+		return $this->core->AsyncCallAPI($URI, $uriParams);
+	}
+
+	public function AsyncBlinkOff()
+	{
+		$URI = "/1.0.0/index.php/smartesl.blink_special/2.0.0/";
+		return $this->core->AsyncCallAPI($URI, "[[\"{$this->labels[0]}\"],0,0,0,0,0,1]");
+	}
+
 	public function getData()
 	public function getData()
 	{
 	{
 		return $this->labelProperties[$this->labels[0]]['data'];
 		return $this->labelProperties[$this->labels[0]]['data'];