Newer
Older
smart-home-server / server / SHServ / Entities / Device.php
<?php

namespace SHServ\Entities;

use \SHServ\Entities\DeviceAuth;
use \SHServ\Tools\DeviceAPI\Base;

class Device extends \SHServ\Middleware\Entity {
	public static $table_name = "devices";
	protected static $fields = [
		"id", "alias", "name", "device_type", "device_name", "device_ip",
		"device_mac", "device_hard_id", "firmware_version", "connection_state", 
		"state", "description", "last_contact", "create_at", "update_at"
	];

	protected $device_auth;
	protected $device_api;

	public function __construct(Int $id, Array $data = []){
		parent::__construct(
			self::$table_name,
			$id,
			$data
		);	
	}

	public function remove() {
		$this -> state = "removed";
		return $this -> update();
	}

	public function get_auth(): DeviceAuth | null {
		if($this -> device_auth) {
			return $this -> device_auth;
		}

		$result = app() -> thin_builder -> select(
			DeviceAuth::$table_name, 
			DeviceAuth::get_fields(), 
			[ ["device_id", "=", $this -> id()] ]
		);

		if(!$result) {
			return null;
		}

		$this -> device_auth = new DeviceAuth($result[0]["id"], $result[0]);

		return $this -> device_auth ?? null;
	}

	public function get_device_api(): Base | null {
		if($this -> device_api) {
			return $this -> device_api;
		}

		$this -> device_api = new Base($this -> device_ip);

		if($this -> get_auth()) {
			$this -> device_api -> set_local_token($this -> get_auth() -> device_token);
		}

		return $this -> device_api ?? null;
	}

	public function set_device_token(String $token) {
		$this -> get_device_api() -> remote_set_token($token);
		if(!$this -> get_auth()) 
			return false;


		$this -> get_auth() -> device_token = $token;
		$this -> device_api -> set_local_token($token);
		return $this -> get_auth() -> update();
	}
}