diff --git a/server/ControlScripts/LightHubScope.php b/server/ControlScripts/LightHubScope.php index 27dde3e..f3c99f9 100644 --- a/server/ControlScripts/LightHubScope.php +++ b/server/ControlScripts/LightHubScope.php @@ -5,8 +5,24 @@ use \SHServ\Entities\Device; class LightHubScope extends \SHServ\Middleware\ControlScripts implements \SHServ\Implements\ControlScriptsInterface { + + protected $sync_map = [ + "connections" => [ + [ + ["type" => "relay", "alias" => "light_hub_1", "channel" => 1], + ["type" => "button", "alias" => "master_room_btns", "channel" => 0], + ], + + [ + ["type" => "relay", "alias" => "light_hub_1", "channel" => 2], + ["type" => "button", "alias" => "master_room_btns", "channel" => 1], + ], + ] + ]; public function register_events_handlers(): void { + $this -> on_online("master_room_btns"); + $this -> btns_click_handlers("master_room_btns"); } public function register_actions_scripts(): void { @@ -47,15 +63,52 @@ // ACTIONS protected function lamp_switch(String $relay_alias, int $channel): Array { - $relay_api= $this -> devices() -> by_alias($relay_alias) -> device_api(); + $relay_api = $this -> devices() -> by_alias($relay_alias) -> device_api(); $result = false; if($relay_api instanceof \SHServ\Tools\DeviceAPI\Relay) { $result = $relay_api -> toggle_channel($channel); + $this -> helper() -> sync_relay_to_btns($this -> sync_map, $relay_alias); } return [ "result" => $result ]; } + + protected function on_online($alias) { + $this -> add_event_handler("button@{$alias}.online", function(Device $btns_block, Array $data) { + $btns_block_api = $btns_block -> device_api(); + if($btns_block_api instanceof \SHServ\Tools\DeviceAPI\Button) { + $btns_block_api -> set_channel_state("mute", 2); + $btns_block_api -> set_channel_state("mute", 3); + } + + $this -> helper() -> sync_btn_channels($this -> sync_map, $btns_block -> alias); + }); + } + + protected function btns_click_handlers($alias): void { + $self = $this; + $buttons = $this -> helper() -> prepare_sync_map_by_alias($this -> sync_map, $alias); + foreach($buttons as $btn_channel => $entry) { + if($entry[0]["type"] != "relay") { + continue; + } + + $relay_alias = $entry[0]["alias"]; + $relay_channel = $entry[0]["channel"]; + + $this -> add_event_handler("button@{$alias}({$btn_channel}).press", function(Device $btns_block, Array $data) use ($self, $btn_channel, $relay_alias, $relay_channel) { + $btns_block_api = $btns_block -> device_api(); + $relay_api = $this -> devices() -> by_alias($relay_alias) -> device_api(); + + if($relay_api instanceof \SHServ\Tools\DeviceAPI\Relay and $btns_block_api instanceof \SHServ\Tools\DeviceAPI\Button) { + $relay_api -> toggle_channel($relay_channel); + $this -> helper() -> sync_relay_to_btns($this -> sync_map, $relay_alias); + } + }); + } + } + }