コード例 #1
0
ファイル: node.py プロジェクト: just-escape/justrelax
    def __init__(self, config=..., *args, **kwargs):
        self.config = config if config is not ... else {}

        self._name = self.config.get('name', 'default_name')
        self._default_publication_channel = self.config.get('default_publication_channel', 'default_channel')
        self._subscriptions = self.config.get('subscriptions', [])

        rpi_detected = False
        try:
            with open('/proc/cpuinfo', 'r') as f:
                rpi_detected = any(['Raspberry Pi' in line for line in f.readlines()])
        except Exception:
            pass

        if not rpi_detected:
            logger.warning("The detected platform is not a raspberry pi: mocking gpiozero library pin interfaces")
            Device.pin_factory = MockFactory()
            Device.pin_factory.pin_class = MockPWMPin

        serials = self.config.get('serials', [])
        self._serials = {}
        for serial in serials:
            port = serial['port']
            baud_rate = serial.get('baud_rate', 9600)
            buffering_interval = serial.get('buffering_interval', 0.1)
            self._serials[serial['port']] = Serial(port, baud_rate, buffering_interval)
            self._serials[serial['port']].process_event = self.process_event  # magic

        self._first_connection = False

        EventFilterMixin.__init__(self)
        Node.__init__(self, *args, **kwargs)
コード例 #2
0
 def __init__(self, pin, state_manager, **kwargs):
     Device.pin_factory = MockFactory()
     # btn = GPIOButton(pin, **kwargs)
     self.btn_pin = Device.pin_factory.pin(pin)
     self._drive_low = True
     super().__init__(pin, state_manager, **kwargs)
     signal.signal(signal.SIGINT, self.handle_interrupt)
コード例 #3
0
ファイル: raspi.py プロジェクト: meik99/CoffeeToGO
 def __init__(self, pin_number=17):
     self.pin_number = pin_number
     try:
         self.pin = LED(self.pin_number)
     except Exception as e:
         logging.error(e)
         self.pin = LED(self.pin_number, pin_factory=MockFactory())
コード例 #4
0
class Command(BaseCommand):
    help = 'Handle I/O'
    # Set the default pin factory to a mock factory
    Device.pin_factory = MockFactory()

    led = LED(17)

    drive_white_led(17)

    def dispatch(self, running):
        print(running.content_type)
        if running is None:
            self.stdout.write('none')
        elif (running.content_type == 'api | alarm'):
            self.stdout.write('alarm')
        elif (running.content_type == 'api | color'):
            self.stdout.write('color')

    def handle(self, *args, **options):
        self.stdout.write('foo')
        try:
            running = Running.objects.first()
            self.dispatch(running)
        except ObjectDoesNotExist:
            self.dispatch(None)
コード例 #5
0
    def __init__(self):
        self.testMode = platform == "win32" or platform == "win64"
        self.pollIntervalSec = 0.5
        self.verifyIntervalSec = 0.1
        self.currentPollIntervalSec = 10

        self.powerGpio = 24
        self.waterGpio = 23

        if platform == "win32" or platform == "win64":
            Device.pin_factory = MockFactory()

        self.powerClient = PowerClient(self.powerGpio)
        self.waterClient = WaterClient(self.waterGpio)
        self.kasaClient = KasaClient("Laundry Machine")
        self.serverClient = ServerClient(self.testMode)

        self.currentState = "on"
        self.machineIsRunning = False
        self.connected = False
        self.currentLastPollTime = 0
        self.numConsecutiveChanges = 0

        if platform == "win32" or platform == "win64":
            self.powerPin = Device.pin_factory.pin(self.powerGpio)
            self.waterPin = Device.pin_factory.pin(self.waterGpio)
            self.waterPin.drive_high()
            time.sleep(1.5)
            t = Timer(5.0, self.setWaterPin, [0])
            t.start()
コード例 #6
0
def test_oled_interface_oled(setup_test):
    cf = """
    [camera]
    tmv_root = "."
    interval = 60
    [interface.mode_button]
        button = 20 
    [interface.speed_button]
        button = 16
    [interface]
    screen = "OLEDScreen"
    """

    def _init_display_emulated(self):
        """ Enumlate a screen : write to GIF instead of physical screen"""
        self._gif = ''.join(
            random.choices(string.ascii_uppercase + string.digits,
                           k=3)) + ".gif"
        self._display = gifanim(filename=self._gif,
                                duration=0.1,
                                max_frames=100,
                                mode="1")

    if not running_on_pi():
        # mock GPIO
        tmv.interface.screen.OLEDScreen._init_display = _init_display_emulated
        from gpiozero import Device
        from gpiozero.pins.mock import MockFactory
        Device.pin_factory = MockFactory()

    interface = Interface()
    interface.configs(cf)

    for i in range(10):
        sleep(.1)

    # test paging, mode and speed buttons
    assert interface.screen.page == 1
    press(interface.screen.key_right)
    assert interface.screen.page == 2
    press(interface.screen.key_left)
    assert interface.screen.page == 1

    modefile = Path("camera-mode")
    assert not modefile.exists()
    assert interface.mode_button.value == AUTO
    press(interface.mode_button.button)  # video
    press(interface.mode_button.button)  # ON
    assert interface.mode_button.value == ON
    assert modefile.exists()
    speedfile = Path("camera-speed")
    assert not speedfile.exists()
    assert interface.speed_button.value == MEDIUM
    press(interface.speed_button.button)
    assert interface.speed_button.value == FAST
    assert speedfile.exists()

    if not running_on_pi() and show_images:
        interface.screen._display.write_animation()
        subprocess.run(["gnome-open", interface.screen._gif])
コード例 #7
0
 def mock_gpio(self):
     import os
     if os.name == 'nt':
         print('Mocking GPIOs')
         from gpiozero import Device
         from gpiozero.pins.mock import MockFactory
         Device.pin_factory = MockFactory()
コード例 #8
0
ファイル: control.py プロジェクト: turvas/metering
def init_system():
    """initial setup steps"""
    global nps_export_fn, relays, activityLED
    # global sem.schedule_html_fn, sem.schedule_fn, sem.prices_fn,

    logger("init control module..")

    sem.set_dir_path()
    nps_export_fn = sem.dirpath + nps_export_fn  # prepend dir to original name
    sem.schedule_html_fn = sem.dirpath + sem.schedule_html_fn
    sem.prices_fn = sem.dirpath + sem.prices_fn
    sem.schedule_fn = sem.dirpath + sem.schedule_fn

    if os.name == 'posix':
        os.system('echo none | sudo tee /sys/class/leds/led0/trigger')
    else:  # windows for dev
        Device.pin_factory = MockFactory(
        )  # Set the default pin factory to a mock factory

    for load in loads:
        relay = LED(load["gpioPin"])  # init output objects for relays
        relays.append(relay)

    # powerLED = LED(35)  # /sys/class/leds/led1
    activityLED = LED(
        16
    )  # /sys/class/leds/led0   #16 on original Pi 1, todo-3: make dynamic based on Pi version
コード例 #9
0
    def _connectPins(cls):
        """Creates gpiozero objects for components based on pins specified at class level"""
        if not Pins.pins_initialized:
            logger.debug("Connecting Pins")
            if IS_RASPBERRY_PI:
                logger.info(W1ThermSensor.get_available_sensors())
                cls.adc = ADS1115()
  
                cls.tempsensors = [W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, id) for id in Pins.TEMP_SENSOR_IDS]
                for sensor in cls.tempsensors:
                    logger.info(f'Sensor ID: {sensor.id}')
                cls.servo = Ax12()
            else:
                cls.adc = None
                cls.servoconnection = None
                cls.tempsensors = None

            try:
                # this little bit of weirdness is a consequence of gpiozero's fake pin code being goofy

                cls.pwmPinFactory = Device.pin_factory
                if not IS_RASPBERRY_PI:
                    Device.pin_factory = MockFactory()
                    cls.pwmPinFactory = MockFactory(pin_class=MockPWMPin)

                cls.heatingElements = [
                    PWMOutputDevice(n, pin_factory=cls.pwmPinFactory)
                    for n in Pins.heatingElementGPIOs]
                cls.ballValves = [OutputDevice(n) for n in Pins.ballValveGPIOs]
                for index, valve in enumerate(cls.ballValves):
                    if (index >4):
                        valve.close()
                cls.airPump = OutputDevice(Pins.airPumpGPIO)
                cls.airPump.close()
                cls.pumps = [PWMOutputDevice(n, pin_factory=cls.pwmPinFactory)
                    for n in Pins.pumpGPIOs]
                for pump in cls.pumps:
                    pump.toggle()
                logger.debug(f'Pump states: {[x.value for x in cls.pumps]}')
                cls.heatingElementSwitch = OutputDevice(Pins.heatingElementSwitchGPIO)

                cls.GPZeroComponents = (
                        cls.ballValves + cls.heatingElements + cls.pumps
                )

            except GPIOPinInUse as e:
                print(e)
コード例 #10
0
 def test_look_for_motion(self):
     Device.pin_factory = MockFactory()
     test_pir = PirSensor(4)
     pin = Device.pin_factory.pin(4)
     self.assertEqual(test_pir.look_for_motion(), None)
     pin.drive_high()
     sleep(0.5)  #give time for state switch
     self.assertNotEqual(test_pir.look_for_motion(), None)
コード例 #11
0
def mock_factory(request):
    save_factory = Device.pin_factory
    Device.pin_factory = MockFactory()
    yield Device.pin_factory

    if Device.pin_factory is not None:
        Device.pin_factory.reset()
        Device.pin_factory = save_factory
コード例 #12
0
ファイル: divert.py プロジェクト: javierin/solar-logger
def activate(load):
    if (config.loads[load]["state"] != 1):
        if config.diverters_io[load][0] == "gpio":
            gpiozero.Device.pin_factory = MockFactory(
            )  ######### disable for actual use

            relay = LED(config.diverters_io[load][1])
            relay.on()
        print("turning on ", load)
コード例 #13
0
def build_power_detector() -> InputDevice:
    """ Creates a device for detecting power activity """
    is_dev = get_config('dev_mode')

    if is_dev:
        Device.pin_factory = MockFactory()

    power_pin = get_config('device.power_pin')
    return InputDevice(power_pin)
コード例 #14
0
def mock_factory(request):
    save_factory = Device.pin_factory
    Device.pin_factory = MockFactory()
    yield Device.pin_factory
    # This reset() may seem redundant given we're re-constructing the factory
    # for each function that requires it but MockFactory (via LocalFactory)
    # stores some info at the class level which reset() clears.
    if Device.pin_factory is not None:
        Device.pin_factory.reset()
    Device.pin_factory = save_factory
コード例 #15
0
ファイル: config.py プロジェクト: corka149/pump_light
def build_led() -> LED:
    """ Builds the LED for showing activities """
    is_dev = get_config('dev_mode')

    if is_dev:
        _LOG.info('dev mode active')
        Device.pin_factory = MockFactory()

    led_pin = get_config('device.light_pin')
    return LED(led_pin)
コード例 #16
0
ファイル: __init__.py プロジェクト: meik99/Saufbot3000-Server
    def __init__(self, factory=MockFactory()):
        if len(PUMPS) != 8:
            LOGGER.warning(Warning().wrong_pump_count(8, len(PUMPS)))

        Device.pin_factory = factory

        self.pumps = []

        for pump_pin in PUMPS:
            self.pumps.append(LED(pump_pin))
コード例 #17
0
def pin_factory(request):
    try:
        factory = pkg_resources.load_entry_point('gpiozero',
                                                 'gpiozero_pin_factories',
                                                 request.param)()
    except Exception as e:
        pytest.skip("skipped factory %s: %s" % (request.param, str(e)))
    else:
        Device.pin_factory = factory
        yield factory
        Device.pin_factory = MockFactory()
コード例 #18
0
    def connectToPin(self, withclass, pin, *args, mock=None, **kwargs):
        global globalMockFactory

        from gpiozero import Device
        import gpiozero

        kwargs = kwargs.copy()
        # Rename because this was very confusing
        if "pull" in kwargs:
            kwargs['pull_up'] = kwargs['pull']
            del kwargs['pull']

        if mock:
            if self.realGpio:
                try:
                    self.realGpio.close()
                except:
                    pass
                self.realGpio = None

            if not self.fakeGpio:
                from gpiozero.pins.mock import MockFactory
                if not globalMockFactory:
                    globalMockFactory = MockFactory()
                if not globalMockFactory:
                    raise RuntimeError("problem")
                self.fakeGpio = withclass(pin,
                                          *args,
                                          **kwargs,
                                          pin_factory=globalMockFactory)
            self.gpio = self.fakeGpio
        else:
            if self.fakeGpio:
                try:
                    self.fakeGpio.close()
                except:
                    pass
                self.fakeGpio = None
            try:
                if not self.realGpio:
                    self.gpio = withclass(pin, *args, **kwargs)
                self.realGpio = self.gpio

            except gpiozero.exc.BadPinFactory:
                global alreadySentMockWarning
                if not alreadySentMockWarning:
                    messagebus.postMessage(
                        "/system/notifications/warnings",
                        "No real GPIO found, using mock pins")

                # Redo in mock mode
                self.connectToPin(withclass, pin, *args, mock=True, **kwargs)
                alreadySentMockWarning = True
コード例 #19
0
def get_fan_controller_pin():
    pin_factory = None

    if 'linux' not in platform:
        from gpiozero.pins.mock import MockFactory
        config.logger.info('not running on pi, will use mock gpio pins')
        pin_factory = MockFactory()
        return OutputDevice(pin=config.FC_GPIO_PIN, pin_factory=pin_factory)

    return PWMOutputDevice(pin=config.FC_GPIO_PIN,
                           frequency=config.FC_PWM_FREQ_HZ,
                           pin_factory=pin_factory)
コード例 #20
0
    def setUp(self):
        self.__patcher = patch('camguard.raspi_gpio_sensor.LED', spec=True)
        self.__led_mock = self.__patcher.start()

        Device.pin_factory = MockFactory()
        self.__sensor_settings_mock = create_autospec(spec=RaspiGpioSensorSettings, spec_set=True)
        type(self.__sensor_settings_mock).gpio_pin_number = PropertyMock(return_value=13)
        type(self.__sensor_settings_mock).queue_length = PropertyMock(return_value=1)
        type(self.__sensor_settings_mock).sample_rate = PropertyMock(return_value=10.0)
        type(self.__sensor_settings_mock).threshold = PropertyMock(return_value=0.5)
        type(self.__sensor_settings_mock).led_gpio_pin_number = PropertyMock(return_value=16)
        self.sut = RaspiGpioSensor(self.__sensor_settings_mock)
コード例 #21
0
ファイル: mraa_led.py プロジェクト: NebraLtd/hm-config
    def __init__(self,
                 pin_number=None,
                 *,
                 active_high=True,
                 initial_value=False):
        super().__init__(pin_number,
                         active_high=active_high,
                         initial_value=initial_value,
                         pin_factory=MockFactory())

        LOGGER.info("Initializing mraa LED on pin %s" % pin_number)

        self.mraa_pin = init_mraa_pin(pin_number, True)
コード例 #22
0
    def __init__(self, host, port, name, channel, environment, node_params, *args, **kwargs):
        self.host = host
        self.port = port
        self.name = name

        self.factory = JustSockClientFactory(self, name, channel)

        self.node_params = node_params

        if environment != "rpi":
            Device.pin_factory = MockFactory()
            Device.pin_factory.pin_class = MockPWMPin

        super(JustSockClientService, self).__init__(host, port, self.factory, *args, **kwargs)
コード例 #23
0
 def test__init__(self):
     Device.pin_factory = MockFactory()
     test_controller = Controller()
     self.assertIsNotNone(test_controller.com_handler)
     self.assertIsNotNone(test_controller.pir)
     test_controller.com_handler = MagicMock()
     test_controller.pir = MagicMock()
     test_controller.com_handler.send_payload = MagicMock(return_value=1)
     test_controller.pir.look_for_motion = MagicMock(
         return_value="TestMessage")
     test_controller.run()
     self.assertEqual(test_controller.payload, "TestMessage")
     test_controller.pir.look_for_motion = MagicMock(return_value="")
     test_controller.run()
     self.assertEqual(test_controller.payload, "")
コード例 #24
0
ファイル: __init__.py プロジェクト: bkryza/OctoPrint-GPIO
 def update_pin_bindings(self):
     bindings = self._settings.get(["bindings"])
     self._logger.error(str(bindings))
     for gpio in bindings:
         pin = int(gpio["gpio"])
         if gpio["type"][0] == "OUTPUT":
             self._logger.error(
                 "Binding DigitalOutputDevice to pin {pin}".format(pin=pin))
             self.pins[pin] = DigitalOutputDevice(pin,
                                  active_high=True,
                                  initial_value=True,
                                  pin_factory=MockFactory())
         if gpio["type"][0] == "INPUT":
             self._logger.error(
                 "Binding Button to pin {pin}".format(pin=pin))
             self.pins[pin] = Button(pin,
                                     active_state=None,
                                     pull_up=True,
                                     bounce_time=0.01,
                                     pin_factory=MockFactory())
         if gpio["type"][0] == "PWM":
             self._logger.error("Binding PWM to pin {pin}".format(pin=pin))
             self.pins[pin] = PWMOutputDevice(pin,
                                  active_high=True,
                                  initial_value=0.0,
                                  frequency=100,
                                  pin_factory=MockFactory())
         if gpio["type"][0] == "SERVO":
             self._logger.error(
                 "Binding Servo to pin {pin}".format(pin=pin))
             self.pins[pin] = Servo(pin,
                                    initial_value=0.0,
                                    min_pulse_width=1 / 1000,
                                    max_pulse_width=2 / 1000,
                                    frame_width=20 / 1000,
                                    pin_factory=MockFactory())
コード例 #25
0
    def simulate_windows(self):
        from gpiozero.pins.mock import MockFactory
        Device.pin_factory = MockFactory()
        if platform.system() == "Windows":
            def simulate():
                print("Running on Windows - Mock Pins generated")
                pins = [Device.pin_factory.pin(x) for x in self.input_pins]
                pins[0].drive_high()
                while 1:
                    for pin in pins[1:]:
                        pin.drive_high()
                        sleep(0.01)
                        pin.drive_low()
                        sleep(0.99)

            simulator = Thread(target=simulate)
            simulator.start()
コード例 #26
0
ファイル: mock.py プロジェクト: nocarryr/tallypi
def mock_gpio():
    import gpiozero
    from gpiozero import Device
    from gpiozero.pins.mock import MockFactory, MockPWMPin

    class LoggingMockPWMPin(MockPWMPin):
        def _set_state(self, value):
            super()._set_state(value)
            logger.debug(f'{self}._set_state({value})')

        def _set_frequency(self, value):
            super()._set_frequency(value)
            if value is not None:
                logger.debug(f'{self}._set_frequency({value})')

    Device.pin_factory = MockFactory()
    Device.pin_factory.pin_class = LoggingMockPWMPin
    return gpiozero
コード例 #27
0
ファイル: knihaui.py プロジェクト: ahosna/Pi0AudioBook
def setup_buttons(dev=False):
    if dev:
        Device.pin_factory = MockFactory()

    global btn_next
    global btn_prev
    global btn_play
    btn_next = Button(BTN_NEXT, bounce_time=BOUNCE_TIME, hold_time=HOLD_TIME)
    btn_next.when_released = next_released
    btn_next.when_held = next_held

    btn_prev = Button(BTN_PREV, bounce_time=BOUNCE_TIME, hold_time=HOLD_TIME)
    btn_prev.when_released = prev_released
    btn_prev.when_held = prev_held

    btn_play = Button(BTN_PLAY, bounce_time=BOUNCE_TIME, hold_time=HOLD_TIME)
    btn_play.when_released = play_released
    btn_play.when_held = play_held
コード例 #28
0
ファイル: mqtt-button.py プロジェクト: lindhe/iot
def main(topic: str, pressed_msg: str, released_msg: str, hostname: str,
         gpio_pin: int, mocked: bool, inverted: bool):
    """ GPIO initialization and registering signal event handlers. """
    pin_factory = MockFactory() if mocked else None
    button = Button(gpio_pin, pin_factory=pin_factory)
    if inverted:
        pressed_msg, released_msg = released_msg, pressed_msg

    def pressed_handler():
        event(topic=topic, event=pressed_msg, hostname=hostname)

    def released_handler():
        event(topic=topic, event=released_msg, hostname=hostname)

    button.when_pressed = pressed_handler
    button.when_released = released_handler

    print("Button is ready!")
    pause()
コード例 #29
0
class TestBasicos(unittest.TestCase):
    # Set the default pin factory to a mock factory
    Device.pin_factory = MockFactory()

    def test_right(self):
        with LED(20) as left, LED(21) as right:
            steering = Steering(left, right)
            self.assertEqual(right, steering.right)

    def test_left(self):
        with LED(20) as left, LED(21) as right:
            steering = Steering(left, right)
            self.assertEqual(left, steering.left)

    def test_get_status(self):
        with LED(20) as left, LED(21) as right:
            steering = Steering(left, right)
            left.on()
            self.assertEqual(1, left.value)
            self.assertEqual(1, steering.status())

    def test_straight(self):
        with LED(20) as left, LED(21) as right:
            steering = Steering(left, right)
            left.on()
            right.off()
            self.assertEqual(True, steering.straight())
            self.assertEqual(0, left.value)

    def test_turn_left(self):
        with LED(20) as left, LED(21) as right:
            steering = Steering(left, right)
            right.off()
            left.on()
            self.assertEqual(left.is_active, steering.turn_left().is_active)

    def test_turn_right(self):
        with LED(20) as left, LED(21) as right:
            steering = Steering(left, right)
            left.off()
            right.on()
            self.assertEqual(right.is_active, steering.turn_right().is_active)
コード例 #30
0
def check_module_status():
    '''
    Check all connections are working and return back report in message.
    This will be called daily at an set time during the day as a standard
    report helping with maintenance.
    os.getenv('ENVIRONMENT')


    # Set the default pin factory to a mock factory

    # Construct a couple of devices attached to mock pins 16 and 17, and link the
    # devices
    led = LED(17)
    btn = Button(16)
    led.source = btn

    # Here the button isn't "pushed" so the LED's value should be False
    print(led.value)

    # Get a reference to mock pin 16 (used by the button)
    btn_pin = Device.pin_factory.pin(16)

    # Drive the pin low (this is what would happen electrically when the button is
    # pushed)
    btn_pin.drive_low()
    sleep(0.1) # give source some time to re-read the button state
    print(led.value)

    btn_pin.drive_high()
    sleep(0.1)
    print(led.value)

    '''

    if os.getenv('ENVIRONMENT') == "DEV":
        Device.pin_factory = MockFactory()

    led = LED(17)
    print(led.value)

    checking_device_msg = "Everything is connected and working"
    return checking_device_msg