def main(self, args): warnings.simplefilter('ignore') try: from gpiozero import pi_info except ImportError: formatter = self.parser._get_formatter() formatter.add_text( "Unable to initialize GPIO Zero. This usually means that you " "are not running %(prog)s on a Raspberry Pi. If you still wish " "to run %(prog)s, set the GPIOZERO_PIN_FACTORY environment " "variable to 'mock' and retry, or refer to the Remote GPIO " "section of the manual* to configure your environment to " "remotely access your Pi.") formatter.add_text( "* https://gpiozero.readthedocs.io/en/latest/remote_gpio.html") sys.stderr.write(formatter.format_help()) else: if args.revision == '': try: pi_info().pprint(color=args.color) except IOError: raise IOError('This device is not a Raspberry Pi') else: pi_info(args.revision).pprint(color=args.color) formatter = self.parser._get_formatter() formatter.add_text( "For further information, please refer to https://pinout.xyz/") sys.stdout.write('\n') sys.stdout.write(formatter.format_help())
def main(self, args): warnings.simplefilter('ignore') try: from gpiozero import pi_info except ImportError: formatter = self.parser._get_formatter() formatter.add_text( "Unable to initialize GPIO Zero. This usually means that you " "are not running %(prog)s on a Raspberry Pi. If you still wish " "to run %(prog)s, set the GPIOZERO_PIN_FACTORY environment " "variable to 'mock' and retry, or refer to the Remote GPIO " "section of the manual* to configure your environment to " "remotely access your Pi." ) formatter.add_text( "* https://gpiozero.readthedocs.io/en/latest/remote_gpio.html" ) sys.stderr.write(formatter.format_help()) else: if args.revision == '': try: pi_info().pprint(color=args.color) except IOError: raise IOError('This device is not a Raspberry Pi') else: pi_info(args.revision).pprint(color=args.color) formatter = self.parser._get_formatter() formatter.add_text( "For further information, please refer to https://pinout.xyz/" ) sys.stdout.write('\n') sys.stdout.write(formatter.format_help())
def _gpio_bcm_to_board(self, pin): if gpiozero.pi_info().headers['J8'].rows == 20: # This is a 40 pin Pi pin_to_gpio = self._pin_to_gpio_rev3 else: # This is a 26 pin Pi pin_to_gpio = self._pin_to_gpio_rev2 return pin_to_gpio.index(pin)
def update_function(self): '''update function for pi_dash providing basic system information This plugin displays system information for this raspberry pi and requires that the user running this plugin has access to the GPIO group. Args: self(`namespace`) Returns: tuple: (is_updated(bool), data(dict), priority(int)) %U''' logging.debug( f'## {constants.name} v{constants.version} update_function ##') data = constants.data failure = False, data, self.max_priority try: pi_temp = gpiozero.CPUTemperature() pi_load = gpiozero.LoadAverage() pi_disk = gpiozero.DiskUsage() pi_info = gpiozero.pi_info() except gpiozero.GPIOZeroError as e: logging.warning(f'error getting gpio data: {e}') logging.warning(f'returning: {failure}') return failure img_path = Path(constants.img_path) logging.debug(f'using images stored in: {img_path}') try: hostname = socket.gethostname() except Exception as e: logging.warning(f'error getting hostname: {e}') hostname = 'Unknown' try: data = { 'temp': f'{int(pi_temp.temperature)}C', 'temp_icon': img_path / 'Thermometer_icon.png', 'load': f'{pi_load.load_average}', 'cpu_icon': img_path / 'CPU_icon.png', 'disk_use': f'{int(pi_disk.usage)}%', 'disk_icon': img_path / 'SSD_icon.png', 'pi_model': f'Pi {pi_info.model} rev {pi_info.revision}', 'pi_logo': img_path / 'pi_logo.png', 'hostname': hostname } except Exception as e: logging.warning(f'failed to read GPIO data: {e}') logging.waringin(f'returning: {failure}') return failure return True, data, self.max_priority
print_columns_words) from pibooth.states import StateMachine from pibooth.plugins import hookspecs, load_plugins from pibooth.view import PtbWindow from pibooth.config import PiConfigParser, PiConfigMenu from pibooth import camera from pibooth.fonts import get_available_fonts from pibooth.printer import PRINTER_TASKS_UPDATED, PtbPrinter from gpiozero import Device, LEDBoard, Button, pi_info from gpiozero.exc import BadPinFactory, PinFactoryFallback from warnings import filterwarnings # Set the default pin factory to a mock factory if pibooth is not started a Raspberry Pi try: filterwarnings("ignore", category=PinFactoryFallback) gpio_info = "on Raspberry pi {0}".format(pi_info().model) except BadPinFactory: from gpiozero.pins.mock import MockFactory Device.pin_factory = MockFactory() gpio_info = "without physical GPIO, fallback to GPIO mock" BUTTON_DOWN = pygame.USEREVENT + 1 class PiApplication(object): def __init__(self, config): self._config = config # Clean directory where pictures are saved savedir = config.getpath('GENERAL', 'directory') if not osp.isdir(savedir):
from pibooth.counters import Counters from pibooth.utils import (LOGGER, PoolingTimer, configure_logging, get_crash_message, set_logging_level, print_columns_words) from pibooth.states import StateMachine from pibooth.plugins import create_plugin_manager, load_plugins, list_plugin_names from pibooth.view import PtbWindow from pibooth.config import PiConfigParser, PiConfigMenu from pibooth import camera from pibooth.fonts import get_available_fonts from pibooth.printer import PRINTER_TASKS_UPDATED, Printer # Set the default pin factory to a mock factory if pibooth is not started a Raspberry Pi try: filterwarnings("ignore", category=PinFactoryFallback) GPIO_INFO = "on Raspberry pi {0}".format(pi_info().model) except BadPinFactory: from gpiozero.pins.mock import MockFactory Device.pin_factory = MockFactory() GPIO_INFO = "without physical GPIO, fallback to GPIO mock" BUTTONDOWN = pygame.USEREVENT + 1 class PiApplication(object): def __init__(self, config, plugin_manager): self._pm = plugin_manager self._config = config # Create directories where pictures are saved for savedir in config.gettuple('GENERAL', 'directory', 'path'):
def callback(): value = pin.state print("{} value is {}".format(pin.number, value)) [pin.drive_high, pin.drive_low][value]() return callback def create_update(pin, waffle): def update(): waffle.color = 'blue' if pin.state else 'white' return update pi = pi_info() gpio = pi.headers['J8'].pins app = App("GPIO Zero", layout="grid", width=200, height=710) for n, pin in gpio.items(): col_1 = n % 2 x = 0 if col_1 else 3 y = ceil(n / 2) - 1 align = 'right' if col_1 else 'left' Text(app, str(pin.function), grid=[x, y], align=align) x = 1 if col_1 else 2 color = { '5V': 'red', '3V3': 'orange', 'GND': 'black',
properties = {} # find all network interfaces for i in psutil.net_if_addrs(): for k in psutil.net_if_addrs()[i]: family, address, netmask, broadcast, ptp = k if family == 2: properties[i] = address if 'lo' in properties: properties.pop('lo') properties["hostname"] = platform.node() mem = psutil.virtual_memory() properties["megabytesMemoryFree"] = int(mem.available / (1024 * 1024)) disk = psutil.disk_usage('/') properties["megabytesDiskUsed"] = int(disk.used / (1024 * 1024)) properties['percentCPUUtilization'] = psutil.cpu_percent(interval=3) properties['cpuTemperature'] = get_rpi_cpu_temperature() properties["hardware"] = "Raspberry Pi Model {} V{}".format( gpiozero.pi_info().model, gpiozero.pi_info().pcb_revision) myAWSIoTMQTTClient.publish(iot_thing_topic(args.thingName), iot_payload('reported', properties), 1) myAWSIoTMQTTClient.disconnect()
# defining your plugin as a template plugin, settings and asset plugin. Feel free to add or remove mixins # as necessary. # # Take a look at the documentation on what other plugin mixins are available. import octoprint.plugin from octoprint_queue.queue import PrintQueue, QueueItem from gpiozero import Button, LED, pi_info from flask import jsonify, request, redirect, url_for from pprint import pformat import json import os try: pi_info() IS_PI = True except: IS_PI = False class QueuePlugin(octoprint.plugin.AssetPlugin, octoprint.plugin.BlueprintPlugin, octoprint.plugin.SettingsPlugin, octoprint.plugin.EventHandlerPlugin, octoprint.plugin.TemplatePlugin): def get_settings_defaults(self): return {'button_pin': 21, 'led_pin': 3} def initialize(self): self.q = PrintQueue([], 0, 'stopped')
from gpiozero import pi_info piBoardInfo = pi_info('a020d3') # 3B+ assert (piBoardInfo.model == '3B+')
def get_pi_info(host, port): factory = PiGPIOFactory(host=host, port=port) Device.pin_factory = factory return '{0:full}'.format(pi_info())
switches.append(button) button.when_held, button.when_released = event_held, event_released logging.info( 'Configured the switch button ({0}) at {1}'.format( button.label, button.pin)) else: # assumes only 'push' and 'switch' types push_buttons.append(button) button.when_pressed, button.when_released = event_pressed, event_released logging.info('Configured the push button ({0}) at {1}'.format( button.label, button.pin)) if args['buzzer']: # buzzer is activated by any push button buzzer, buzzer.source = Buzzer( args['buzzer']), any_values(*push_buttons) logging.info('Configured a buzzer at {}'.format(buzzer.pin)) print( 'The button box is now turned ON. To close it, release the power button or press Ctrl+C.' ) logging.info('The button box is ON and waiting for user input') pause() except KeyboardInterrupt: end(msg='Received a signal to stop.', status=1) except GPIOZeroError as err: end(msg='GPIOZero error: {}'.format(err), status=1) if __name__ == '__main__': args = cli_args() print('{0:full}'.format(pi_info())) if args['info'] else main()