php-linux-gpio/lib/Device/Device.php

143 lines
2.9 KiB
PHP

<?php
/*
* Copyright (C) 2014, NoccyLabs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
namespace NoccyLabs\Gpio\Device;
use NoccyLabs\Gpio\GpioPin;
abstract class Device
{
protected $name;
protected $description;
protected $pins = array();
public function __construct()
{
$this->configure();
}
protected function configure()
{
// call on ->addGpioPin etc here
}
public function setGpio(Gpio $gpio=null)
{
$this->gpio = $gpio;
}
public function getGpio()
{
return $this->gpio;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function setDescription($description)
{
$this->description = $description;
return $this;
}
public function getDescription()
{
return $this->description;
}
public function addPin($name, $description=null)
{
$this->pins[$name] = null;
return $this;
}
/**
* Get all allocated pins
*
*/
public function getPins()
{
return $this->pins;
}
/**
* Get a pin by the name specified when allocating it
*
*/
public function getPin($name)
{
return $this->pins[$name];
}
public function setPin($pin_name, $pin)
{
if (array_key_exists($pin_name, $this->pins)) {
$pin->setLabel($this->name.".".$pin_name);
$this->pins[$pin_name] = $pin;
return $this;
}
throw new \Exception();
}
/**
* Get a pin as a property from its name
*
*/
public function __get($pin_name)
{
return $this->getPin($pin_name);
}
public function __set($pin_name, GpioPin $pin)
{
$this->setPin($pin_name, $pin);
}
protected function delayMillis($ms)
{
usleep($ms*1000);
}
protected function delayMicros($us)
{
usleep($us);
}
protected function shiftOut(GpioPin $pdata, GpioPin $pclk, $byte)
{
for ($bit = 0; $bit < 8; $bit++) {
$bval = 1<<$bit;
$pclk->setValue(0);
$pdata->setValue(($byte & $bval) == $bval);
$pclk->setValue(1);
}
}
}