예제 #1
0
def get_voltage(id):
    """Get the voltage.

    :param string id: The ID of the voltage type to get (core, sdram_c, etc).
    :returns: The voltage.
    :rtype: int, long
    :raises: raspy.invalid_operation_exception.InvalidOperationException if
    invalid command ("measure_volts") or response.
    """
    cmd = "/opt/vc/bin/vcgencmd measure_volts " + id
    result = exec_utils.execute_command(cmd)
    if result is not None:
        val = -1
        separators = ["\\\[", "\\\=", "\\\V", "\\\]"]
        # noinspection PyTypeChecker
        for i, line in enumerate(result):
            parts = re.split('|'.join(map(re.escape, separators)), line)
            try:
                val = float(parts[1])
            except ValueError:
                val = -1

        return val

    raise InvalidOperationException("Invalid command or response.")
예제 #2
0
    def state(self, pwr_state):
        """Set the state of the power component.

        :param int pwr_state: The state to set.
        :raises: raspy.object_disposed_exception.ObjectDisposedException if
        this instance has been disposed.
        :raises: raspy.io.invalid_pin_mode_exception.InvalidPinModeException if
        the pin being used to control this device is not configure as an
        output.
        :raises: raspy.invalid_operation_exception.InvalidOperationException if
        an invalid state is specified.
        """
        if self.is_disposed:
            raise ObjectDisposedException("GpioPowerComponent")

        if self.__output.mode != pin_mode.OUT:
            msg = "Pins in use by power components MUST be configured as "
            msg += "outputs."
            raise InvalidPinModeException(msg, self.__output)

        if pwr_state == power_state.OFF:
            self.__output.write(self.__offState)
            pwr.PowerInterface.state.fset(self, pwr_state)
        elif pwr_state == power_state.ON:
            self.__output.write(self.__onState)
            pwr.PowerInterface.state.fset(self, pwr_state)
        else:
            bad_state = power_utils.get_power_state_name(pwr_state)
            msg = "Cannot set power state: " + bad_state
            raise InvalidOperationException(msg)
예제 #3
0
def get_cpu_temperature():
    """Get the CPU temperature.

    :returns: The CPU temperature.
    :rtype: int, long
    :raises: raspy.invalid_operation_exception.InvalidOperationException if
    invalid command ("measure_temp") or response.
    """
    # CPU temperature is in the form:
    # pi@mypi$ /opt/vc/bin/vcgencmd measure_temp
    # temp=42.3'C
    # Support for this was added around firmware version 3357xx per info
    # at http://www.raspberrypi.org/phpBB3/viewtopic.php?p=169909#p169909
    result = exec_utils.execute_command("/opt/vc/bin/vcgencmd measure_temp")
    if result is not None:
        val = -1
        separators = ["\\\[", "\\\=", "\\\]", "\\\'"]
        # noinspection PyTypeChecker
        for i, line in enumerate(result):
            parts = re.split('|'.join(map(re.escape, separators)), line)
            try:
                val = float(parts[1])
            except ValueError:
                val = -1

        return val

    raise InvalidOperationException("Invalid command or response.")
예제 #4
0
def get_cpu_info(target):
    """Get information about the CPU.

    Returns the value from the specified target field.

    :param string target: The target attribute to the value of.
    :returns: The value of the specified CPU attribute.
    :rtype: string
    :raises: raspy.invalid_operation_exception.InvalidOperationException if
    the specified target is invalid (unknown).
    """
    global __cpuInfo
    if __cpuInfo is None:
        __cpuInfo = []
        result = exec_utils.execute_command("cat /proc/cpuinfo")
        if result is not None:
            # noinspection PyTypeChecker
            for key, val in enumerate(result):
                line = val
                parts = line.split(":")
                if len(parts) >= 2:
                    tpart0 = string_utils.trim(parts[0])
                    tpart1 = string_utils.trim(parts[1])
                    if (not string_utils.is_null_or_empty(tpart0)
                            and not string_utils.is_null_or_empty(tpart1)):
                        # noinspection PyTypeChecker
                        __cpuInfo[tpart0] = tpart1

    if target in __cpuInfo:
        # noinspection PyTypeChecker
        return __cpuInfo[target]

    raise InvalidOperationException("Invalid target: " + target)
예제 #5
0
    def pwm(self, val):
        """Get the PWM (pulse-width modulation) value.

        :param int val: The PWM value.
        :raises: raspy.invalid_operation_exception.InvalidOperationException
        if setting a PWM value on a pin that is not configured as PWM.
        """
        if self.mode == pin_mode.PWM:
            err_msg = "Cannot set PWM value on a pin not configured for PWM."
            raise InvalidOperationException(err_msg)

        if val < 0:
            val = 0

        if val > 1023:
            val = 1023

        if self.__pwm != val:
            self.__pwm = val
            if not self.__isPWM:
                cmd = "gpio mode " + str(self.inner_pin) + " pwm"
                exec_utils.execute_command(cmd)

            cmd = "gpio pwm " + str(self.inner_pin) + " " + str(self.__pwm)
            exec_utils.execute_command(cmd)
예제 #6
0
    def set_timeout_delay(self, delay, unit):
        """Get the timeout delay.

        :param int delay: The timeout delay.
        :param int unit: The time unit of measure for the timeout.
        :raises: raspy.invalid_operation_exception.InvalidOperationException if
        the fireplace is turned off.
        """
        if self.is_off:
            msg = "Cannot set timeout when the fireplace is off."
            raise InvalidOperationException(msg)

        self.__timeoutDelay = delay
        self.__timeoutUnit = unit
        self.cancel_timeout()
        if self.__timeoutDelay > 0:
            wait_time = datetime.timedelta()
            if unit == time_unit.DAYS:
                wait_time = datetime.timedelta(days=delay)
            elif unit == time_unit.HOURS:
                wait_time = datetime.timedelta(hours=delay)
            elif unit == time_unit.MINUTES:
                wait_time = datetime.timedelta(minutes=delay)
            elif unit == time_unit.SECONDS:
                wait_time = datetime.timedelta(seconds=delay)
            elif unit == time_unit.MILLISECONDS:
                wait_time = datetime.timedelta(milliseconds=delay)

            kill_delay = datetime.timedelta(
                milliseconds=wait_time.total_seconds())
            kill_delay += datetime.timedelta(seconds=1)
            sec = kill_delay.total_seconds()
            self.__killTimer = threading.Timer(sec, self._cancel_timeout_task)
            self.__killTimer.start()
            self._start_cancel_task()
예제 #7
0
    def decrease(self, steps=0):
        """Decrease the wiper's value by the specified number of steps.

        It is not an error if the wiper hits or already hit the lower
        boundary (0). In such situations, the wiper sticks to the lower
        boundary or doesn't change.

        :param int steps: The number of steps to decrease by. If not
        specified or zero, then defaults to 1.
        :raises: raspy.io.io_exception.IOException if communication with the
        device failed.
        """
        if self.__currentValue == 0:
            return

        if steps < 0:
            msg = "Only positive integer values are permitted."
            raise IllegalArgumentException(msg)

        if self.non_volatile_mode != microchip_pot_non_volatile_mode.VOLATILE_ONLY:
            msg = "Decrease is only permitted on volatile-only wipers."
            raise InvalidOperationException(msg)

        # Check bounds:
        actual_steps = steps
        if steps > self.__currentValue:
            actual_steps = self.__currentValue

        new_val = self.__currentValue - actual_steps
        if new_val == 0 or steps > 5:
            self.__currentValue = new_val
        else:
            chan = device_control_channel.value_of(self.__channel)
            self.__controller.decrease(chan, actual_steps)
            self.__currentValue = new_val
예제 #8
0
    def poll(self):
        """Start a pin poll cycle.

        This will monitor the pin and check for state changes. If a state
        change is detected, the raspy.io.Gpio.EVENT_GPIO_STATE_CHANGED event
        will be emitted. The poll cycle runs asynchronously until stopped by
        the cancel_poll() method or when this object instance is disposed.

        :raises: raspy.object_disposed_exception.ObjectDisposedException if
        this instance has been disposed.
        :raises: raspy.invalid_operation_exception.InvalidOperationException
        if the poll thread is already running.
        """
        if self.is_disposed:
            raise ObjectDisposedException("PiFaceGpioDigital")

        if self.__pollRunning:
            raise InvalidOperationException("Poll thread already running.")

        self.__stopEvent.clear()
        self.__pollThread = threading.Thread(target=self.__background_poll)
        self.__pollThread.name = "PiFaceGpioPoller"
        self.__pollThread.daemon = True
        self.__pollThread.start()
        self.__pollRunning = True
예제 #9
0
파일: lcd.py 프로젝트: cyrusbuilt/RasPy
    def _validate_row_index(self, row=0):
        """Validate the index of the specified row.

        :param int row: The index of the row to validate.
        :raises: raspy.invalid_operation_exception.InvalidOperationException if
        the row index is invalid for the display.
        """
        if row >= self.row_count or row < 0:
            raise InvalidOperationException("Invalid row index.")
예제 #10
0
파일: lcd.py 프로젝트: cyrusbuilt/RasPy
    def _validate_column_index(self, column=0):
        """Validate the index of the specified column.

        :param int column: The index of the column to validate.
        :raises: raspy.invalid_operation_exception.InvalidOperationException if
        the column index is invalid for the display.
        """
        if column >= self.column_count or column < 0:
            raise InvalidOperationException("Invalid column index.")
예제 #11
0
    def _get_non_volatile_value(self):
        """Get the non-volatile wiper's value.

        :returns: The non-volatile wiper's value.
        :rtype: int
        :raises: raspy.invalid_operation_exception.InvalidOperationException if
        this device is not capable of non-volatile wipers.
        """
        if self.is_non_volatile_wiper_capable:
            msg = "This device is not capable of non-volatile wipers."
            raise InvalidOperationException(msg)
        chan = device_control_channel.value_of(self.__channel)
        return self.__controller.get_value(chan, True)
예제 #12
0
    def _set_non_volatile_mode(self, mode):
        """Set the non-volatility mode.

        :param int mode: The way non-volatile reads or writes are done.
        :raises: raspy.invalid_operation_exception.InvalidOperationException if
        this device is not capable of non-volatile wipers.
        """
        vol_only = microchip_pot_non_volatile_mode.VOLATILE_ONLY
        if (not self.is_non_volatile_wiper_capable
                and self.__nonVolMode != vol_only):
            msg = "This device is not capable of non-volatile wipers."
            msg += "You *must* use microchip_pot_non_volatile_mode.VOLATILE_ONLY"
            raise InvalidOperationException(msg)
        self.__nonVolMode = mode
예제 #13
0
    def write_bytes(self, address, buf):
        """Write a list of bytes to the specified device address.

        Currently, RPi drivers do not allow writing more than 3 bytes at a
        time. As such, if any list of greater than 3 bytes is provided, an
        exception is thrown.

        :param int address: The address of the target device.
        :param list buf: A list of bytes to write to the bus.
        :raises: raspy.object_disposed_exception.ObjectDisposedException if
        this instance has been disposed.

        :raises: raspy.invalid_operation_exception.InvalidOperationException if
        a connection to the I2C bus has not yet been opened.

        :raises: raspy.illegal_argument_exception.IllegalArgumentException if
        the buffer contains more than 3 bytes or if the specified buffer
        parameter is not a list.

        :raises: raspy.io.io_exception.IOException if an error occurs while
        writing the buffer contents to the I2C bus or if only a partial
        write succeeds.
        """
        if self.is_disposed:
            raise ObjectDisposedException("I2CBus")

        if not self.__isOpen:
            raise InvalidOperationException("No open connection to write to.")

        if isinstance(buf, list):
            if len(buf) > 3:
                # TODO we only do this to keep parity with the JS and C#
                # ports. They each have their own underlying native
                # implementations. SMBus2 itself is capable of writing
                # much more than 3 bytes. We should change this as soon
                # as we can get the other ports to support more.
                msg = "Cannot write more than 3 bytes at a time."
                raise IllegalArgumentException(msg)
        else:
            msg = "The specified buf param value is not a list."
            raise IllegalArgumentException(msg)

        try:
            trans = i2c_msg.write(address, buf)
            self.__bus.i2c_rdwr(trans)
        except OSError or IOError:
            msg = "Error writing to address '" + str(address)
            msg += "': I2C transaction failed."
            raise IOException(msg)
예제 #14
0
    def turn_off(self):
        """Turn the light off.

        :raises: raspy.object_disposed_exception.ObjectDisposedException if
        this instance has been disposed.
        """
        if self.is_disposed:
            raise ObjectDisposedException("LedComponent")

        if self.__pin.mode != pin_mode.OUT:
            msg = "Pin is not configured as an output pin."
            raise InvalidOperationException(msg)

        if self.__pin.state != OFF_STATE:
            self.__pin.write(pin_state.LOW)
            evt = LightStateChangeEvent(False)
            Led.on_light_state_changed(self, evt)
예제 #15
0
    def pulse(self, millis):
        """Pulse the pin output for the specified number of milliseconds.

        :param int, long millis: The number of milliseconds to wait between
        states.
        :raises: raspy.object_disposed_exception.ObjectDisposedException if
        this instance has been disposed.
        """
        if self.mode == pin_mode.IN:
            err_msg = "You cannot pulse a pin set as an input"
            raise InvalidOperationException(err_msg)

        pin_addr = self.inner_pin.value
        self.__write(self.inner_pin, pin_state.HIGH)
        evt = PinStateChangeEvent(self.state, pin_state.HIGH, pin_addr)
        self.on_pin_state_change(evt)
        gpio.Gpio.pulse(self, millis)
        self.__write(self.inner_pin, pin_state.LOW)
        evt = PinStateChangeEvent(self.state, pin_state.LOW, pin_addr)
        self.on_pin_state_change(evt)
예제 #16
0
def get_os_firmware_date():
    """Get the OS firmware date.

    :returns: The OS firmware date.
    :rtype: string
    :raises: raspy.invalid_operation_exception.InvalidOperationException if
    an unexpected response is received.
    """
    results = exec_utils.execute_command("/opt/vc/bin/vcgencmd version")
    val = string_utils.EMPTY
    if results is not None:
        # noinspection PyTypeChecker
        for key, value in enumerate(results):
            # We are intentionally only getting the first line.
            val = value
            break

    if not string_utils.is_null_or_empty(val):
        return val

    raise InvalidOperationException("Invalid command or response.")
예제 #17
0
    def poll(self):
        """Poll the input pin status every 500ms until stopped.

        :raises: raspy.object_disposed_exception.ObjectDisposedException if
        this instance has been disposed.
        :raises: raspy.invalid_operation_exception.InvalidOperationException
        if the underlying pin is not an input pin.
        """
        if self.is_disposed:
            raise ObjectDisposedException("MotionSensorComponent")

        if self.pin.mode != pin_mode.IN:
            msg = "The specified pin is not configured as an input pin, which"
            msg += " is required to read sensor data."
            raise InvalidOperationException(msg)

        self.__stopEvent.clear()
        self.__isPolling = True
        self.__pollThread = threading.Thread(target=self._execute_poll)
        self.__pollThread.name = "MotionSensorComponentPollThread"
        self.__pollThread.daemon = True
        self.__pollThread.start()
예제 #18
0
def get_os_firmware_build():
    """Get the OS firmware build.

    :returns: the OS firmware build.
    :rtype: string
    :raises: raspy.invalid_operation_exception.InvalidOperationException if
    an unexpected response is received.
    """
    results = exec_utils.execute_command("/opt/vc/bin/vcgencmd version")
    val = string_utils.EMPTY
    if results is not None:
        # noinspection PyTypeChecker
        for key, val in enumerate(results):
            line = val
            if string_utils.starts_with(line, "version "):
                val = line
                break

    if not string_utils.is_null_or_empty(val):
        return val[8:]

    raise InvalidOperationException("Invalid command or response")
예제 #19
0
    def increase(self, steps=0):
        """Increase the wiper's value bye the specified number of steps.

        It is not an error if the wiper hits or already hit the upper
        boundary. In such situations, the wiper sticks to the upper boundary
        or doesn't change.
        :param int steps: How many steps to increase. If not specified or
        zero, then defaults to 1. If the current value is equal to the max
        value, then nothing happens. If steps is less than zero, then an
        exception is thrown.
        :raises: raspy.io.io_exception.IOException if communication with the
        device failed.
        """
        max_val = self.max_value
        if self.__currentValue == max_val:
            return

        if steps < 0:
            msg = "Only positive integer values are permitted."
            raise IllegalArgumentException(msg)

        vol_only = microchip_pot_non_volatile_mode.VOLATILE_ONLY
        if self.non_volatile_mode != vol_only:
            msg = "Increase is only permitted for volatile-only wipers."
            raise InvalidOperationException(msg)

        # Check bounds.
        actual_steps = steps
        if (steps + self.__currentValue) > max_val:
            actual_steps = max_val - self.__currentValue

        new_val = self.__currentValue + actual_steps
        if new_val == max_val or steps > 5:
            self.__currentValue = new_val
        else:
            chan = device_control_channel.value_of(self.__channel)
            self.__controller.increase(chan, actual_steps)
            self.__currentValue = new_val
예제 #20
0
    def poll(self):
        """Start a button state poll cycle.

        This will monitor the button state in a poll loop on a separate thread
        and fire events when the button state changes.

        :raises: raspy.object_disposed_exception.ObjectDisposedException if
        this instance has been disposed.
        :raises: raspy.invalid_operation_exception.InvalidOperationException
        if the poll thread is already running.
        """
        if self.is_disposed:
            raise ObjectDisposedException("ButtonComponent")

        if self.__pollRunning:
            raise InvalidOperationException("Poll thread already running.")

        self.__stopEvent.clear()
        self.__pollRunning = True
        self.__pollThread = threading.Thread(target=self._execute_poll)
        self.__pollThread.name = "ButtonComponentPollThread"
        self.__pollThread.daemon = True
        self.__pollThread.start()
예제 #21
0
    def read_bytes(self, address, count):
        """Read bytes from the device at the specified address.

        :param int address: The address of the device to read from.
        :param int count: The number of bytes to read.
        :returns: The bytes read.
        :rtype: list
        :raises: raspy.object_disposed_exception.ObjectDisposedException if
        this instance has been disposed.

        :raises: raspy.invalid_operation_exception.InvalidOperationException if
        a connection to the I2C bus has not yet been opened.

        :raises: raspy.io.io_exception.IOException if an error occurs while
        writing the buffer contents to the I2C bus or if only a partial
        write succeeds.
        """
        if self.is_disposed:
            return

        if not self.__isOpen:
            raise InvalidOperationException("No open connection to read from.")

        buf = []
        msg = "Error reading from address '" + str(address)
        msg += "': I2C transaction failed."
        try:
            trans = i2c_msg.read(address, count)
            self.__bus.i2c_rdwr(trans)
            buf = list(trans)
        except OSError or IOError:
            raise IOException(msg)

        if len(buf) <= 0:
            raise IOException(msg)

        return buf
예제 #22
0
    def poll(self):
        """Poll the switch status.

        :raises: ObjectDisposedException if this instance has been disposed.
        :raises: InvalidOperationException if this switch is attached to a
        pin that has not been configured as an input.
        """
        if self.is_disposed:
            raise ObjectDisposedException("SwitchComponent")

        if self.__pin.mode != pin_mode.IN:
            msg = "The pin this switch is attached to must be configured"
            msg += " as an input."
            raise InvalidOperationException(msg)

        if self.__isPolling:
            return

        self.__stopEvent.clear()
        self.__isPolling = True
        self.__pollThread = threading.Thread(target=self._execute_poll)
        self.__pollThread.name = "MomentarySwitchComponentPollThread"
        self.__pollThread.daemon = True
        self.__pollThread.start()