Exemplo n.º 1
0
  // default constructor
  public PiFaceBase(byte spiAddress, SpiChannel spiChannel) throws IOException {

    // create Pi-Face GPIO provider
    gpioProvider = new PiFaceGpioProvider(spiAddress, spiChannel);

    // provision gpio input pins for the Pi-Face board
    inputPins =
        new GpioPinDigitalInput[] {
          gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_00),
          gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_01),
          gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_02),
          gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_03),
          gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_04),
          gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_05),
          gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_06),
          gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_07)
        };

    // provision gpio output pins for the Pi-Face board
    outputPins =
        new GpioPinDigitalOutput[] {
          gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_00),
          gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_01),
          gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_02),
          gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_03),
          gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_04),
          gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_05),
          gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_06),
          gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_07)
        };

    // create relay components for the first two output pins on the Pi-Face board
    relays =
        new Relay[] {new GpioRelayComponent(outputPins[0]), new GpioRelayComponent(outputPins[1])};

    // create switch components for the first four input pins on the Pi-Face board
    switches =
        new Switch[] {
          new GpioSwitchComponent(inputPins[0], PinState.HIGH, PinState.LOW),
          new GpioSwitchComponent(inputPins[1], PinState.HIGH, PinState.LOW),
          new GpioSwitchComponent(inputPins[2], PinState.HIGH, PinState.LOW),
          new GpioSwitchComponent(inputPins[3], PinState.HIGH, PinState.LOW)
        };

    // create LED components for the eight output pins on the Pi-Face board
    leds =
        new LED[] {
          new GpioLEDComponent(outputPins[0]),
          new GpioLEDComponent(outputPins[1]),
          new GpioLEDComponent(outputPins[2]),
          new GpioLEDComponent(outputPins[3]),
          new GpioLEDComponent(outputPins[4]),
          new GpioLEDComponent(outputPins[5]),
          new GpioLEDComponent(outputPins[6]),
          new GpioLEDComponent(outputPins[7])
        };
  }
Exemplo n.º 2
0
  public static void main(String args[]) throws InterruptedException {
    System.out.println("<--Pi4J--> GPIO Listen Example ... started.");

    // create gpio controller
    final GpioController gpio = GpioFactory.getInstance();

    // provision gpio pin #02 as an input pin with its internal pull down resistor enabled
    final GpioPinDigitalInput myButton =
        gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN);

    // create and register gpio pin listener
    myButton.addListener(
        new GpioPinListenerDigital() {
          @Override
          public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
            // display pin state on console
            System.out.println(
                " --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
          }
        });

    System.out.println(
        " ... complete the GPIO #02 circuit and see the listener feedback here in the console.");

    // keep program running until user aborts (CTRL-C)
    for (; ; ) {
      Thread.sleep(500);
    }

    // stop all GPIO activity/threads by shutting down the GPIO controller
    // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
    // gpio.shutdown();   <--- implement this method call if you wish to terminate the Pi4J GPIO
    // controller
  }
Exemplo n.º 3
0
  public static void main(String[] args) throws InterruptedException {

    System.out.println("<--Pi4J--> GPIO Trigger Example ... started.");

    // create gpio controller
    final GpioController gpio = GpioFactory.getInstance();

    // provision gpio pin #02 as an input pin with its internal pull down resistor enabled
    final GpioPinDigitalInput myButton =
        gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN);

    System.out.println(" ... complete the GPIO #02 circuit and see the triggers take effect.");

    // setup gpio pins #04, #05, #06 as an output pins and make sure they are all LOW at startup
    GpioPinDigitalOutput myLed[] = {
      gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "LED #1", PinState.LOW),
      gpio.provisionDigitalOutputPin(RaspiPin.GPIO_05, "LED #2", PinState.LOW),
      gpio.provisionDigitalOutputPin(RaspiPin.GPIO_06, "LED #3", PinState.LOW)
    };

    // create a gpio control trigger on the input pin ; when the input goes HIGH, also set gpio pin
    // #04 to HIGH
    myButton.addTrigger(new GpioSetStateTrigger(PinState.HIGH, myLed[0], PinState.HIGH));

    // create a gpio control trigger on the input pin ; when the input goes LOW, also set gpio pin
    // #04 to LOW
    myButton.addTrigger(new GpioSetStateTrigger(PinState.LOW, myLed[0], PinState.LOW));

    // create a gpio synchronization trigger on the input pin; when the input changes, also set gpio
    // pin #05 to same state
    myButton.addTrigger(new GpioSyncStateTrigger(myLed[1]));

    // create a gpio pulse trigger on the input pin; when the input goes HIGH, also pulse gpio pin
    // #06 to the HIGH state for 1 second
    myButton.addTrigger(new GpioPulseStateTrigger(PinState.HIGH, myLed[2], 1000));

    // create a gpio callback trigger on gpio pin#4; when #4 changes state, perform a callback
    // invocation on the user defined 'Callable' class instance
    myButton.addTrigger(
        new GpioCallbackTrigger(
            new Callable<Void>() {
              public Void call() throws Exception {
                System.out.println(" --> GPIO TRIGGER CALLBACK RECEIVED ");
                return null;
              }
            }));

    // keep program running until user aborts (CTRL-C)
    for (; ; ) {
      Thread.sleep(500);
    }

    // stop all GPIO activity/threads by shutting down the GPIO controller
    // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
    // gpio.shutdown();   <--- implement this method call if you wish to terminate the Pi4J GPIO
    // controller
  }
Exemplo n.º 4
0
  @Before
  public void setup() {
    // create a mock gpio provider and controller
    provider = MockGpioFactory.getMockProvider();
    gpio = MockGpioFactory.getInstance();

    // provision pins for testing
    inputPin = gpio.provisionDigitalInputPin(MockPin.DIGITAL_INPUT_PIN, "digitalInputPin");
    outputPin = gpio.provisionDigitalOutputPin(MockPin.DIGITAL_OUTPUT_PIN, "digitalOutputPin");

    // create triggers
    triggerHigh = new GpioSetStateTrigger(PinState.HIGH, outputPin, PinState.HIGH);
    triggerLow = new GpioSetStateTrigger(PinState.LOW, outputPin, PinState.LOW);

    // add triggers to input pin
    inputPin.addTrigger(triggerHigh);
    inputPin.addTrigger(triggerLow);
  }
  public LelandPrototype() {
    fonaClient = this;
    data = new LevelMaterial[NB_CHANNELS];
    for (int i = 0; i < data.length; i++) {
      data[i] =
          new LevelMaterial<Float, SevenADCChannelsManager.Material>(
              0f, SevenADCChannelsManager.Material.UNKNOWN);
    }

    oilThicknessValues = new ArrayList<Double>(windowWidth);

    final GpioPinDigitalInput resetButton =
        gpio.provisionDigitalInputPin(RESET_PI, PinPullResistance.PULL_DOWN);
    resetButton.addListener(
        new GpioPinListenerDigital() {
          @Override
          public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
            if (event.getState().isHigh()) onButtonPressed();
          }
        });
  }
  @BeforeClass
  public static void setup() {
    // create a mock gpio provider and controller
    provider = MockGpioFactory.getMockProvider();
    gpio = MockGpioFactory.getInstance();

    // provision pins for testing
    inputPin = gpio.provisionDigitalInputPin(MockPin.DIGITAL_INPUT_PIN, "digitalInputPin");

    // create trigger
    trigger =
        new GpioCallbackTrigger(
            new Callable<Void>() {
              @Override
              public Void call() throws Exception {
                callbackCounter++;
                return null;
              }
            });

    // add trigger to input pin
    inputPin.addTrigger(trigger);
  }
Exemplo n.º 7
0
 @Override
 public GpioPinDigitalInput provisionDigitalInputPin(Pin pin) {
   return delegate.provisionDigitalInputPin(pin);
 }
Exemplo n.º 8
0
 public GpioPinDigitalInput getInputPin(Integer pinNumber, PinPullResistance ppr) {
   switch (pinNumber) {
     case 0:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_00, ppr);
     case 1:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_01, ppr);
     case 2:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, ppr);
     case 3:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_03, ppr);
     case 4:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_04, ppr);
     case 5:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_05, ppr);
     case 6:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_06, ppr);
     case 7:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_07, ppr);
     case 8:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_08, ppr);
     case 9:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_09, ppr);
     case 10:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_10, ppr);
     case 11:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_11, ppr);
     case 12:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_12, ppr);
     case 13:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_13, ppr);
     case 14:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_14, ppr);
     case 15:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_15, ppr);
     case 16:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_16, ppr);
     case 17:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_17, ppr);
     case 18:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_18, ppr);
     case 19:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_19, ppr);
     case 20:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_20, ppr);
     case 21:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_21, ppr);
     case 22:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_22, ppr);
     case 23:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_23, ppr);
     case 24:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_24, ppr);
     case 25:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_25, ppr);
     case 26:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_26, ppr);
     case 27:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_27, ppr);
     case 28:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_28, ppr);
     case 29:
       return gpio.provisionDigitalInputPin(RaspiPin.GPIO_29, ppr);
     default:
       return null;
   }
 }
Exemplo n.º 9
0
 public RCSwitchReceiver(Pin receiverPin) {
   final GpioController gpio = GpioFactory.getInstance();
   this.receiverPin = gpio.provisionDigitalInputPin(receiverPin);
   this.receiverPin.addListener(new ReceiverListener());
 }
Exemplo n.º 10
0
  public static void main(String[] args) throws InterruptedException {

    // START SNIPPET: usage-create-controller-snippet
    // create gpio controller instance
    final GpioController gpio = GpioFactory.getInstance();
    // END SNIPPET: usage-create-controller-snippet

    // START SNIPPET: usage-provision-input-pin-snippet
    // provision gpio pin #02 as an input pin with its internal pull down resistor enabled
    // (configure pin edge to both rising and falling to get notified for HIGH and LOW state
    // changes)
    GpioPinDigitalInput myButton =
        gpio.provisionDigitalInputPin(
            RaspiPin.GPIO_02, // PIN NUMBER
            "MyButton", // PIN FRIENDLY NAME (optional)
            PinPullResistance.PULL_DOWN); // PIN RESISTANCE (optional)

    // END SNIPPET: usage-provision-input-pin-snippet
    // START SNIPPET: usage-provision-output-pin-snippet
    // provision gpio pins #04 as an output pin and make sure is is set to LOW at startup
    GpioPinDigitalOutput myLed =
        gpio.provisionDigitalOutputPin(
            RaspiPin.GPIO_04, // PIN NUMBER
            "My LED", // PIN FRIENDLY NAME (optional)
            PinState.LOW); // PIN STARTUP STATE (optional)
    // END SNIPPET: usage-provision-output-pin-snippet

    // START SNIPPET: usage-shutdown-pin-snippet
    // configure the pin shutdown behavior; these settings will be
    // automatically applied to the pin when the application is terminated
    // ensure that the LED is turned OFF when the application is shutdown
    myLed.setShutdownOptions(true, PinState.LOW, PinPullResistance.OFF);
    // END SNIPPET: usage-shutdown-pin-snippet

    // START SNIPPET: usage-control-pin-snippet
    // explicitly set a state on the pin object
    myLed.setState(PinState.HIGH);

    // use convenience wrapper method to set state on the pin object
    myLed.low();
    myLed.high();

    // use toggle method to apply inverse state on the pin object
    myLed.toggle();

    // use pulse method to set the pin to the HIGH state for
    // an explicit length of time in milliseconds
    myLed.pulse(1000);
    // END SNIPPET: usage-control-pin-snippet

    // START SNIPPET: usage-read-pin-snippet
    // get explicit state enumeration for the GPIO pin associated with the button
    PinState myButtonState = myButton.getState();

    // use convenience wrapper method to interrogate the button state
    boolean buttonPressed = myButton.isHigh();
    // END SNIPPET: usage-read-pin-snippet

    // START SNIPPET: usage-register-listener-snippet
    // create and register gpio pin listener
    myButton.addListener(new GpioUsageExampleListener());
    // END SNIPPET: usage-register-listener-snippet

    // START SNIPPET: usage-trigger-snippet
    // create a gpio synchronization trigger on the input pin
    // when the input state changes, also set LED controlling gpio pin to same state
    myButton.addTrigger(new GpioSyncStateTrigger(myLed));
    // END SNIPPET: usage-trigger-snippet

    // keep program running until user aborts (CTRL-C)
    while (true) {
      Thread.sleep(500);
    }

    // stop all GPIO activity/threads by shutting down the GPIO controller
    // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
    // gpio.shutdown();   <--- implement this method call if you wish to terminate the Pi4J GPIO
    // controller
  }
Exemplo n.º 11
0
  /**
   * [ARGUMENT/OPTION "--pin (#)" | "-p (#)" ] This example program accepts an optional argument for
   * specifying the GPIO pin (by number) to use with this GPIO listener example. If no argument is
   * provided, then GPIO #1 will be used. -- EXAMPLE: "--pin 4" or "-p 0".
   *
   * <p>[ARGUMENT/OPTION "--pull (up|down|off)" | "-l (up|down|off)" | "--up" | "--down" ] This
   * example program accepts an optional argument for specifying pin pull resistance. Supported
   * values: "up|down" (or simply "1|0"). If no value is specified in the command argument, then the
   * pin pull resistance will be set to PULL_UP by default. -- EXAMPLES: "--pull up", "-pull down",
   * "--pull off", "--up", "--down", "-pull 0", "--pull 1", "-l up", "-l down".
   *
   * @param args
   * @throws InterruptedException
   * @throws PlatformAlreadyAssignedException
   */
  public static void main(String[] args)
      throws InterruptedException, PlatformAlreadyAssignedException {

    // ####################################################################
    //
    // since we are not using the default Raspberry Pi platform, we should
    // explicitly assign the platform as the BananaPro platform.
    //
    // ####################################################################
    PlatformManager.setPlatform(Platform.BANANAPRO);

    // create Pi4J console wrapper/helper
    // (This is a utility class to abstract some of the boilerplate code)
    final Console console = new Console();

    // print program title/header
    console.title("<-- The Pi4J Project -->", "GPIO Input Example");

    // allow for user to exit program using CTRL-C
    console.promptForExit();

    // create gpio controller
    final GpioController gpio = GpioFactory.getInstance();

    // ####################################################################
    //
    // When provisioning a pin, use the BananaProPin class.
    //
    // ####################################################################

    // by default we will use gpio pin #01; however, if an argument
    // has been provided, then lookup the pin by address
    Pin pin =
        CommandArgumentParser.getPin(
            BananaProPin.class, // pin provider class to obtain pin instance from
            BananaProPin.GPIO_01, // default pin if no pin argument found
            args); // argument array to search in

    // by default we will use gpio pin PULL-UP; however, if an argument
    // has been provided, then use the specified pull resistance
    PinPullResistance pull =
        CommandArgumentParser.getPinPullResistance(
            PinPullResistance.PULL_UP, // default pin pull resistance if no pull argument found
            args); // argument array to search in

    // provision gpio pin as an input pin
    final GpioPinDigitalInput input = gpio.provisionDigitalInputPin(pin, "MyInput", pull);

    // set shutdown state for this pin: unexport the pin
    input.setShutdownOptions(true);

    // prompt user that we are ready
    console.println("Successfully provisioned [" + pin + "] with PULL resistance = [" + pull + "]");
    console.emptyLine();
    console.box("The GPIO input pin states will be displayed below.");
    console.emptyLine();

    // display pin state
    console.emptyLine();
    console.println(
        " ["
            + input.toString()
            + "] digital state is: "
            + ConsoleColor.conditional(
                input.getState().isHigh(), // conditional expression
                ConsoleColor.GREEN, // positive conditional color
                ConsoleColor.RED, // negative conditional color
                input.getState()));
    console.emptyLine();

    // stop all GPIO activity/threads by shutting down the GPIO controller
    // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
    gpio.shutdown();
  }
Exemplo n.º 12
0
 @Override
 public GpioPinDigitalInput provisionDigitalInputPin(Pin pin, PinPullResistance resistance) {
   return delegate.provisionDigitalInputPin(pin, resistance);
 }
Exemplo n.º 13
0
 @Override
 public GpioPinDigitalInput provisionDigitalInputPin(
     GpioProvider provider, Pin pin, String name, PinPullResistance resistance) {
   return delegate.provisionDigitalInputPin(provider, pin, name, resistance);
 }
Exemplo n.º 14
0
  public static void main(String args[]) throws InterruptedException {

    System.out.println("<--Pi4J--> GPIO Listen Example ... started.");

    // create gpio controller
    final GpioController gpio = GpioFactory.getInstance();

    // provision gpio pin #02 as an input pin with its internal pull down resistor enabled
    final GpioPinDigitalInput myButton =
        gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN);

    // create custom Olimex GPIO provider
    final OlimexAVRIOGpioProvider olimexProvider =
        new OlimexAVRIOGpioProvider(Serial.DEFAULT_COM_PORT);

    // provision gpio input pin #01 from Olimex
    final GpioPinDigitalInput myInput =
        gpio.provisionDigitalInputPin(olimexProvider, OlimexAVRIOPin.IN_01);

    // create gpio pin listener
    GpioPinListenerDigital listener =
        new GpioPinListenerDigital() {
          @Override
          public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
            // display pin state on console
            System.out.println(
                " --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
          }
        };

    // register gpio pin listener for each input pin
    myButton.addListener(listener);
    myInput.addListener(listener);

    // setup gpio pins #04, #05, #06 as an output pins and make sure they are all LOW at startup
    GpioPinDigitalOutput myRelays[] = {
      gpio.provisionDigitalOutputPin(
          olimexProvider, OlimexAVRIOPin.RELAY_01, "RELAY #1", PinState.LOW),
      gpio.provisionDigitalOutputPin(
          olimexProvider, OlimexAVRIOPin.RELAY_02, "RELAY #2", PinState.LOW),
      gpio.provisionDigitalOutputPin(
          olimexProvider, OlimexAVRIOPin.RELAY_03, "RELAY #3", PinState.LOW),
      gpio.provisionDigitalOutputPin(
          olimexProvider, OlimexAVRIOPin.RELAY_04, "RELAY #4", PinState.LOW)
    };

    // create a gpio control trigger on the input pin ; when the input goes HIGH, also set gpio pin
    // #04 to HIGH
    myButton.addTrigger(new GpioSetStateTrigger(PinState.HIGH, myRelays[0], PinState.HIGH));

    // create a gpio control trigger on the input pin ; when the input goes LOW, also set gpio pin
    // #04 to LOW
    myButton.addTrigger(new GpioSetStateTrigger(PinState.LOW, myRelays[0], PinState.LOW));

    // create a gpio synchronization trigger on the input pin; when the input changes, also set gpio
    // pin #05 to same state
    myButton.addTrigger(new GpioSyncStateTrigger(myRelays[1]));

    // create a gpio synchronization trigger on the input pin; when the input changes, also set gpio
    // pin #05 to same state
    myButton.addTrigger(new GpioSyncStateTrigger(myRelays[2]));

    // create a gpio pulse trigger on the input pin; when the input goes HIGH, also pulse gpio pin
    // #06 to the HIGH state for 1 second
    myButton.addTrigger(new GpioPulseStateTrigger(PinState.HIGH, myRelays[3], 1000));

    System.out.println(
        " ... complete the GPIO #02 circuit and see the listener feedback here in the console.");

    // keep program running until user aborts (CTRL-C)
    // or we reach 60 seconds
    for (int seconds = 0; seconds < 60; seconds++) {
      Thread.sleep(1000);
    }

    System.out.println(" ... exiting program.");

    // stop all GPIO activity/threads by shutting down the GPIO controller
    // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
    gpio.shutdown();
  }
Exemplo n.º 15
0
 @Override
 public GpioPinDigitalInput provisionDigitalInputPin(Pin pin, String name) {
   return delegate.provisionDigitalInputPin(pin, name);
 }
Exemplo n.º 16
0
public class SocketServer {

  private ServerSocket serverSocket;
  public static final int SERVERPORT = 6000;

  // ================
  // Commands
  // ================
  private static String LIGHT_ON = "light_on";
  private static String LIGHT_OFF = "light_off";
  private static String DOOR_OPEN = "door_open";
  private static String DOOR_CLOSE = "door_close";

  // ================
  // GPIO block
  // ================
  final GpioController gpio = GpioFactory.getInstance();
  final GpioPinDigitalOutput lightPin =
      gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "MyLED", PinState.LOW);
  final GpioPinDigitalInput myButton =
      gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN);

  Socket socket = null;
  GpioCallbackTrigger doorRingTrigger;

  public SocketServer() {
    try {
      initializeSoftPWM();
      System.out.println("Waiting for connect ...");
      createSocket();
      System.out.println("Device is connected");
      createDoorBell();
      createCommandReader();
      // Wait until user stops the application
      Scanner scanIn = new Scanner(System.in);
      String nextLine = "";
      while (true) {
        nextLine = scanIn.nextLine();
        if (nextLine.equals("!exit")) {
          System.exit(0);
        }
        ;
      }
    } catch (SocketException e) {
      System.out.println(String.format("Socket connect is broken: \n %s", e.getMessage()));
      System.exit(0);
    } catch (IOException e) {
      System.out.println(String.format("Something wrong: \n %s", e.getMessage()));
      System.exit(0);
    }
  }

  private void createSocket() throws IOException, SocketException {
    serverSocket = new ServerSocket(SERVERPORT);
    socket = serverSocket.accept();
    socket.setKeepAlive(true);
  }

  private void initializeSoftPWM() {
    Gpio.wiringPiSetup();
    SoftPwm.softPwmCreate(26, 0, 100);
  }

  private void createCommandReader() {
    new Thread(new CommandReader()).start();
  }

  private class CommandReader implements Runnable {

    public void run() {
      try {
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while (true) {
          String read = input.readLine();
          if (read != null && !read.isEmpty()) {
            System.out.println(String.format("Message: '%s' was received", read));
            reactToCommand(read);
          }
        }
      } catch (IOException e) {
        System.out.println(String.format("Cannot create input stream: \n %s", e.getMessage()));
      }
    }
  }

  private void createDoorBell() {
    new Thread(new DoorRingListener()).start();
  }

  private class DoorRingListener implements Runnable {

    public void run() {
      try {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        doorRingTrigger = creareDoorRingTrigger(out);
        myButton.addTrigger(doorRingTrigger);
      } catch (IOException e) {
        System.out.println(String.format("Cannot create output stream: \n %s", e.getMessage()));
      }
    }
  }

  private GpioCallbackTrigger creareDoorRingTrigger(final PrintWriter out) {
    return new GpioCallbackTrigger(
        new Callable<Void>() {
          public Void call() throws Exception {
            myButton.removeAllTriggers();
            System.out.println("Someone comes to home");
            sendNotificationToClient(out);
            try {
              Thread.sleep(500);
            } catch (InterruptedException e) {
            }
            myButton.addTrigger(doorRingTrigger);
            return null;
          }
        });
  }

  private void sendNotificationToClient(PrintWriter out) {
    out.println("Someone comes to home");
    out.flush();
  }

  private void reactToCommand(String read) {
    if (read.equalsIgnoreCase(LIGHT_ON)) {
      turnLightOn();
    } else if (read.equalsIgnoreCase(LIGHT_OFF)) {
      turnLightOff();
    } else if (read.equalsIgnoreCase(DOOR_OPEN)) {
      openDoor();
    } else if (read.equalsIgnoreCase(DOOR_CLOSE)) {
      closeDoor();
    }
  }

  private void closeDoor() {
    SoftPwm.softPwmWrite(26, 5);
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    SoftPwm.softPwmWrite(26, 00);
  }

  private void openDoor() {
    SoftPwm.softPwmWrite(26, 45);
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    SoftPwm.softPwmWrite(26, 00);
  }

  private void turnLightOff() {
    lightPin.low();
    System.out.println(String.format("Light was turned off"));
  }

  private void turnLightOn() {
    lightPin.high();
    System.out.println(String.format("Light was turned on"));
  }

  public static void main(String[] args) {
    new SocketServer();
  }
}
Exemplo n.º 17
0
/*
 *
 * Essa classe foi criada a partir do exemplo em python do endereço abaixo
 * https://www.modmypi.com/blog/hc-sr04-ultrasonic-range-sensor-on-the-raspberry-pi
 *
 *
 */
public class HCSR04 {

  GpioController gpio = GpioFactory.getInstance();

  // Configura os pinos
  GpioPinDigitalOutput trigger =
      gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "trigger", PinState.LOW);
  GpioPinDigitalInput echo =
      gpio.provisionDigitalInputPin(RaspiPin.GPIO_05, "echo", PinPullResistance.PULL_DOWN);

  public long getDistancia() {
    System.out.println("Medição de distância em progresso...");

    this.trigger.low();

    System.out.println("Aguardando tempo do pino...");
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    // Iniciando a leitura
    System.out.println("Iniciando a leitura");
    try {

      // Envia o sinal no pino Trigger
      // Coloca o trigger em HIGH por 10uS (8 ultrasound bursts at 40 kHz)
      this.trigger.high();
      TimeUnit.MICROSECONDS.sleep(10);
      this.trigger.low();

      // Escuta o pino de ECHO
      // O sensor emitirá uma onda sonora que ao encontrar um obstáculo
      // rebaterá de volta em direção ao módulo, sendo que o neste tempo
      // de emissão e recebimento do sinal o pino ECHO ficará em nivel alto.
      // Logo o calcula da distância pode ser feito de acordo com o tempo em
      // que o pino ECHO permaneceu em nível alto após o pino Trigger ter
      // sido colocado em nível alto.
      long inicio = 0;
      long fim = 0;

      while (this.echo.isLow()) {
        inicio = System.nanoTime();
      }
      while (this.echo.isHigh()) {
        fim = System.nanoTime();
      }

      // Calcula a diferença entre "fim" e "inicio"
      long duracao_pulso = fim - inicio;

      // Calcula distância
      long distancia = 17150 * duracao_pulso;

      // Round
      distancia = Math.round(distancia);

      System.out.println("Distancia: " + distancia);

      return distancia;

    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return 0;
  }
}
  public static void main(String args[]) throws InterruptedException, IOException {

    System.out.println("<--Pi4J--> PiFace (MCP23017) GPIO Example ... started.");

    // create gpio controller
    final GpioController gpio = GpioFactory.getInstance();

    // create custom PiFace GPIO provider
    final PiFaceGpioProvider gpioProvider =
        new PiFaceGpioProvider(PiFaceGpioProvider.DEFAULT_ADDRESS, SpiChannel.CS0);

    // provision gpio input pins from PiFaceGpioProvider
    GpioPinDigitalInput myInputs[] = {
      gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_00),
      gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_01),
      gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_02),
      gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_03),
      gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_04),
      gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_05),
      gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_06),
      gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_07)
    };

    // create and register gpio pin listener
    gpio.addListener(
        new GpioPinListenerDigital() {
          @Override
          public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
            // display pin state on console
            System.out.println(
                " --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
          }
        },
        myInputs);

    // provision gpio output pins and make sure they are all LOW at startup
    GpioPinDigitalOutput myOutputs[] = {
      gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_00),
      gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_01),
      gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_02),
      gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_03),
      gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_04),
      gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_05),
      gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_06),
      gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_07),
    };

    // keep program running for 20 seconds
    for (int count = 0; count < 10; count++) {
      gpio.setState(true, myOutputs);
      Thread.sleep(1000);
      gpio.setState(false, myOutputs);
      Thread.sleep(1000);
    }

    // stop all GPIO activity/threads by shutting down the GPIO controller
    // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
    gpio.shutdown();

    System.out.println("Exiting PiFaceGpioExample");
  }
  /**
   * @param args --none-
   * @throws InterruptedException
   */
  public static void main(String[] args) throws InterruptedException {

    // create Pi4J console wrapper/helper
    // (This is a utility class to abstract some of the boilerplate code)
    final Console console = new Console();

    // print program title/header
    console.title("<-- The Pi4J Project -->", "IFTTT Maker Channel Trigger Example");

    // allow for user to exit program using CTRL-C
    console.promptForExit();

    // create gpio controller
    final GpioController gpio = GpioFactory.getInstance();

    // provision gpio pin as an input pin
    final GpioPinDigitalInput input =
        gpio.provisionDigitalInputPin(RaspiPin.GPIO_00, "MyInputPin", PinPullResistance.PULL_DOWN);

    // provide 500ms of pin debounce protection
    input.setDebounce(500);
    ;

    // -----------------------------------------
    // Add the IFTTT Maker Channel Trigger
    // (This is where the magic happens)
    // -----------------------------------------
    input.addTrigger(
        new IFTTTMakerChannelTrigger(
            IFTTT_MAKER_CHANNEL_API_KEY, // <<-- PROVIDE YOUR ACCOUNT SPECIFIC IFTTT MAKER CHANNEL
                                         // API KEY
            IFTTT_MAKER_CHANNEL_EVENT_NAME, // <<-- PROVIDE THE IFTTT MAKER CHANNEL EVENT NAME
                                            // (defined in your IFTTTT recipe)
            PinState.HIGH, // <<-- OPTIONALLY DEFINE A SPECIFIC STATE TO TRIGGER ON

            // OPTIONALLY REGISTER A TRIGGER CALLBACK LISTENER
            // (Note: this callback parameter is not required for basic functionality)
            new IFTTTMakerChannelTriggerListener() {
              @Override
              public boolean onTriggered(IFTTTMakerChannelTriggerEvent event) {

                // The IFTTT Maker Channel API accepts three value parameters (value1, value2, and
                // value3)
                // By default, Pi4J applies the following values to each:
                //
                // "value1" = {pin-name}
                // "value2" = {pin-state-value} (as an Integer; 0==LOW, 1==HIGH)
                // "value3" = {json-payload}  Example:
                // {
                //    "pin": {
                //        "name": "MyInputPin",
                //        "address": "0",
                //        "provider": "RaspberryPi GPIO Provider",
                //        "mode": "input",
                //        "direction": "IN",
                //        "pull": "down"
                //    },
                //    "state": {
                //        "name": "HIGH",
                //        "value": "1",
                //        "is-high": "true",
                //        "is-low": "false"
                //    },
                //    "timestamp": "2016-04-15T17:32:49.666-0400"
                // }
                //
                // However, you can override any of these defaults in your callback listener by
                // applying new string values via the 'setValueX()' methods on the event object.
                //
                // Example:
                if (event.getValue2().equals("1")) {
                  event.setValue2("ON");
                } else {
                  event.setValue2("OFF");
                }

                // display event trigger details on screen
                console.println(" --> IFTTT MAKER CHANNEL EVENT TRIGGER");
                console.println("     - GPIO PIN            : " + event.getPin());
                console.println("     - PIN STATE           : " + event.getState());
                console.println("     - IFTTT EVENT NAME    : " + event.getEventName());
                console.println("     - IFTTT EVENT VALUE 1 : " + event.getValue1());
                console.println("     - IFTTT EVENT VALUE 2 : " + event.getValue2());
                console.println("     - IFTTT EVENT VALUE 3 : " + event.getValue3());
                console.emptyLine();

                // MAKE SURE TO RETURN 'true' TO CONTINUE WITH THE IFTTT MAKER CHANNEL API CALL
                // (you can optionally return 'false' if you want to abort the IFTTT API call)
                return true;
              }
            }));

    // set shutdown state for this pin: unexport the pin
    input.setShutdownOptions(true);

    // prompt user that we are ready
    console.println(
        "Successfully provisioned ["
            + input
            + "] with PULL resistance = ["
            + input.getPullResistance()
            + "]");
    console.emptyLine();

    // wait for user to exit by pressing CTRL-C
    console.waitForExit();

    // stop all GPIO activity/threads by shutting down the GPIO controller
    // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
    gpio.shutdown();
  }