Newer
Older
smart-home-server / server / ControlScripts / SpotlightsScope.php
<?php

namespace ControlScripts;

use \SHServ\Entities\Device;

class SpotlightsScope extends \SHServ\Middleware\ControlScripts implements \SHServ\Implements\ControlScriptsInterface {
	public function register_events_handlers(): void {
		$this -> backdoor_btns_handlers();
	}

	public function register_actions_scripts(): void {
		$this -> add_action_script([
			"alias" => "spotlights_on",
			"name" => "All Spotlights On",
			"description" => "Включить все прожекторы",
			"author" => "Eugene Sukhodolskiy"
		], function($params) {
			return $this -> all_spotlight_switch(true);
		});

		$this -> add_action_script([
			"alias" => "spotlights_off",
			"name" => "All Spotlights Off",
			"description" => "Выключить все прожекторы",
			"author" => "Eugene Sukhodolskiy"
		], function($params) {
			return $this -> all_spotlight_switch(false);
		});
	}

	public function register_regular_scripts(): void {
		$this -> add_regular_script([
			"alias" => "spotlights_by_time",
			"name" => "Spotlights by Time",
			"description" => "Управление уличными прожекторами по времени",
			"author" => "Eugene Sukhodolskiy"
		], function () {
			$tz = new \DateTimeZone('Europe/Kyiv');

			$now = new \DateTime('now', $tz);
			$limit = new \DateTime('9:00', $tz);

			if ($now >= $limit) {
				$this -> all_spotlight_switch(false);
			}
		});
	}

	// ACTIONS
	
	protected function all_spotlight_switch(Bool $state = false): Array {
		$aliases = [
			"spotlight_main_back_1", 
			"spotlight_main_back_2", 
			"spotlight_main_front_1"
		];

		$results = [];

		foreach($aliases as $alias) { 
			$relay_api = $this -> devices() -> by_alias($alias) -> device_api();
			$result = false;

			if($relay_api instanceof \SHServ\Tools\DeviceAPI\Relay) {
				$status = $relay_api -> get_status();

				if(isset($status["channels"][0]["state"]) and $status["channels"][0]["state"] != ($state ? "on" : "off")) {
					$result = $relay_api -> set_state($state);
				}
			}

			$results[$alias] = $result;
		}

		return [
			"devices" => $results
		];
	}

	// EVENTS HANDLERS
	
	protected function backdoor_btns_handlers() {
		$this -> add_event_handler("button@buttons_backdoor(0).press", function(Device $btns_block, Array $data) {
			$relay_api = $this -> devices() -> by_alias("spotlight_main_front_1") -> device_api();

			if($relay_api instanceof \SHServ\Tools\DeviceAPI\Relay) {
				$relay_api -> toggle_channel(0);
				$relay_channels = ($relay_api -> get_status())["channels"];

				$btns_block_api = $btns_block -> device_api();
				if($btns_block_api instanceof \SHServ\Tools\DeviceAPI\Button) {
					$btns_block_api -> set_channel_state(
						$relay_channels[0]["state"] == "on" ? "enabled" : "disabled", 
						$data["channel"]
					);
				}
			}
		});
	}
}