<?php


class MiMic_LPC1769_Peripheral
{

	public function __construct($i_mcu,$i_phl,$i_opt)
	{
		if(is_null($i_phl)){
			throw new MiMicException();
		}
		$this->_mcu=$i_mcu;

		$this->_phl=$i_phl;

		//オプション設定するならする。

		if(!is_null($i_opt)){
			$this->setOpt($i_opt);
		}
	}

	private static $_PCLKSEL=array(0x400FC1A8,0x400FC1AC);

	const _PCONP=0x400FC0C4;

	private $_phl=null;
	private $_mcu=null;
	private $_cache_pclk=0;

	public function BCF_setOpt($i_opt,&$i_db)
	{
		$bc="";
		//pconp
		if(isset($i_opt['power'])){
			if(is_null($this->_phl[2])){
				throw new MiMicException("The pin does not support PCONP.");
			}
			//pinselAddrを得る
			$bc.=MiMic_LPC1769::BCF_setBit(self::_PCONP,0x00000001,$i_opt['power'],$this->_phl[2],$i_db);
		}
		//clock
		if(isset($i_opt['clock'])){
			if(is_null($this->_phl[0])){
				throw new MiMicException("The pin does not support PCLKSEL.");
			}
			//キャッシュ更新
			$this->_cache_pclk=$i_opt['clock'];
			$bc.=MiMic_LPC1769::BCF_setBit(self::$_PCLKSEL[$this->_phl[0]],0x00000003,$i_opt['clock'],$this->_phl[1],$i_db);
		}
		return $bc;

	}

	public function setOpt($i_opt)
	{
		$db=array();
		$bc=$this->BCF_setOpt($i_opt,$db);
		if(count($bc)==0){
			throw new MiMicException("i_opt is empty or invalid.");
		}
		//MiMicBCを生成して実行
		$this->_mcu->callMiMicWithCheck($bc.LPC1769::_BCF_END,$db);
		return;
	}

	public function getPCLK()
	{
		//倍率変換テーブル
		$m=array(4,1,2,0);
		$t=$m[$this->_cache_pclk];
		$p=$this->_mcu->getClockInfo();
		if($t==0){
			if($this->_phl==MiMic_LPC1769::$PHL['CAN1'] || $this->_phl==MiMic_LPC1769::$PHL['CAN2']){
				$r=$p['cclk']/6;
			}else{
				$r=$p['cclk']/8;
			}
		}else{
			$r=$p['cclk']/$t;
		}
		
		return $r;
	}

}



