Difference between revisions of "Fritzbox-java-api"

From BITPlan Wiki
Jump to navigation Jump to search
Line 21: Line 21:
 
</source>
 
</source>
 
= Code Example =
 
= Code Example =
see https://github.com/WolfgangFahl/fritzbox-java-api/blob/master/src/main/java/com/github/kaklakariada/fritzbox/TestDriver.java
+
see https://github.com/BITPlan/com.bitplan.fritzbox/blob/master/src/main/java/com/bitplan/fritzbox/CmdLine.java
 
<source lang='java'>
 
<source lang='java'>
  final Config config = ConfigService.readConfig();
+
  /**
 +
  * handle the command line command
 +
  */
 +
  public void doCommand() throws Exception {
 +
    if (fritzbox==null)
 +
      fritzbox = FritzboxImpl.readFromProperties();
  
     LOG.info("Logging in to '{}' with username '{}'", config.baseUrl,
+
     if (fritzbox==null) {
        config.username);
+
      String msg=String.format("no %s found\nYou might want to create one see http://wiki.bitplan.com/index.php/Fritzbox-java-api#Configuration_File",FritzboxImpl.getPropertyFile().getPath());
     final HomeAutomation homeAutomation = HomeAutomation.connect(config);
+
      error(msg);
 +
      return;
 +
    }
 +
    if (debug) {
 +
      LOGGER.log(Level.INFO,String.format("Logging in to %s with username %s", fritzbox.getUrl(),
 +
          fritzbox.getUsername()));
 +
    }
 +
    FritzBoxSession session=fritzbox.login();
 +
     final HomeAutomation homeAutomation = new HomeAutomationImpl(session);
  
     final DeviceList devices = homeAutomation.getDeviceListInfos();
+
     final DeviceList deviceList = homeAutomation.getDeviceListInfos();
     LOG.info("Found {} devices", devices.getDevices().size());
+
     if (debug) {
    for (final Device device : devices.getDevices()) {
+
      LOGGER.log(Level.INFO,String.format("Found %s devices", deviceList.devices.size()));
      LOG.info("\t{}", device);
+
      for (final Device device : deviceList.devices) {
 +
        LOGGER.log(Level.INFO,String.format("\t%s", device));
 +
      }
 
     }
 
     }
  
 
     final List<String> ids = homeAutomation.getSwitchList();
 
     final List<String> ids = homeAutomation.getSwitchList();
     LOG.info("Found {} device ids: {}", ids.size(), ids);
+
     if (debug) {
 +
      LOGGER.log(Level.INFO,String.format("Found %3d device ids: %s", ids.size(), ids));
 +
    }
  
     if (devices.getDevices().isEmpty()) {
+
     if (deviceList.devices.isEmpty()) {
       homeAutomation.logout();
+
       session.logout();
 
       return;
 
       return;
 
     }
 
     }
  
     for (final String ain : ids) {
+
    if (listDevices) {
       testHomeAutomation(homeAutomation, ain);
+
      show("%20s | %10s | %25s | %s", "Name", "By", "Product", "Identifier");
       // testEnergyStats(homeAutomation.getSession(), ain);
+
      show("%21s+%12s+%27s+%s", dash(21), dash(12), dash(27), dash(25));
 +
      for (final Device device : deviceList.devices) {
 +
        show("%20s | %10s | %25s | %s", device.name,
 +
            device.manufacturer, device.productname,
 +
            device.identifier);
 +
      }
 +
    }
 +
    final Map<String, String> ainByName = new HashMap<>();
 +
    for (final Device device : deviceList.devices) {
 +
      ainByName.put(device.name, device.getAin());
 +
    }
 +
    /**
 +
    * loop over all devices to be read
 +
    */
 +
     for (final String readDevice : readDevices) {
 +
      // devices can be specified by name or id
 +
      String ain = readDevice;
 +
      // check if a name was given
 +
      if (ainByName.containsKey(ain)) {
 +
        // get the ain for the name
 +
        ain = ainByName.get(ain);
 +
       }
 +
      readSwitch(homeAutomation, ain);
 +
    }
 +
 
 +
    /**
 +
    * loop over all devices to be set
 +
    */
 +
    if (setDevices.size() % 2 != 0) {
 +
      usage("set needs pairs of name=on/off");
 +
    }
 +
    for (int i = 0; i < setDevices.size(); i += 2) {
 +
      final String name = setDevices.get(i);
 +
      final String powerState = setDevices.get(i + 1);
 +
       // check if a name was given
 +
      String ain = name;
 +
      if (ainByName.containsKey(ain)) {
 +
        // get the ain for the name
 +
        ain = ainByName.get(ain);
 +
      }
 +
      boolean newState = false;
 +
      switch (powerState) {
 +
      case "on":
 +
        newState = true;
 +
        break;
 +
      case "off":
 +
        newState = false;
 +
        break;
 +
      default:
 +
        usage(String.format(
 +
            "%s is not a valid powerState it needs to be on or off",
 +
            powerState));
 +
      }
 +
      show("switching %s %s", name, powerState);
 +
      homeAutomation.setSwitchOnOff(ain, newState);
 +
    }
 +
   
 +
  }
 
}
 
}
 
</source>
 
</source>
 +
 
= CmdLine =
 
= CmdLine =
 
== Help / Usage ==
 
== Help / Usage ==

Revision as of 13:49, 4 August 2018

OsProject
id  
state  
owner  
title  Java API for Fritzbox
url  https://github.com/BITPlan/com.bitplan.fritzbox
version  0.0.1
description  
date  
since  
until  

API

Unit tests

The unit tests can be run with:

mvn test

If you did not setup your configuration file yet there will be a warning: You might want to set your application properties in $HOME.fritzbox/application.properties When the application properties are set more tests are run. E.g. one test should show "Logged in with session id ..."

Configuration File

You might want to set your application properties in $HOME/.fritzbox/application.properties

fritzbox.url=http://fritz.box:443
fritzbox.username=user
fritzbox.password=secret

Code Example

see https://github.com/BITPlan/com.bitplan.fritzbox/blob/master/src/main/java/com/bitplan/fritzbox/CmdLine.java

 /**
   * handle the command line command
   */
  public void doCommand() throws Exception {
    if (fritzbox==null)
      fritzbox = FritzboxImpl.readFromProperties();

    if (fritzbox==null) {
      String msg=String.format("no %s found\nYou might want to create one see http://wiki.bitplan.com/index.php/Fritzbox-java-api#Configuration_File",FritzboxImpl.getPropertyFile().getPath());
      error(msg);
      return;
    }
    if (debug) {
      LOGGER.log(Level.INFO,String.format("Logging in to %s with username %s", fritzbox.getUrl(),
          fritzbox.getUsername()));
    }
    FritzBoxSession session=fritzbox.login();
    final HomeAutomation homeAutomation = new HomeAutomationImpl(session);

    final DeviceList deviceList = homeAutomation.getDeviceListInfos();
    if (debug) {
      LOGGER.log(Level.INFO,String.format("Found %s devices", deviceList.devices.size()));
      for (final Device device : deviceList.devices) {
        LOGGER.log(Level.INFO,String.format("\t%s", device));
      }
    }

    final List<String> ids = homeAutomation.getSwitchList();
    if (debug) {
      LOGGER.log(Level.INFO,String.format("Found %3d device ids: %s", ids.size(), ids));
    }

    if (deviceList.devices.isEmpty()) {
      session.logout();
      return;
    }

    if (listDevices) {
      show("%20s | %10s | %25s | %s", "Name", "By", "Product", "Identifier");
      show("%21s+%12s+%27s+%s", dash(21), dash(12), dash(27), dash(25));
      for (final Device device : deviceList.devices) {
        show("%20s | %10s | %25s | %s", device.name,
            device.manufacturer, device.productname,
            device.identifier);
      }
    }
    final Map<String, String> ainByName = new HashMap<>();
    for (final Device device : deviceList.devices) {
      ainByName.put(device.name, device.getAin());
    }
    /**
     * loop over all devices to be read
     */
    for (final String readDevice : readDevices) {
      // devices can be specified by name or id
      String ain = readDevice;
      // check if a name was given
      if (ainByName.containsKey(ain)) {
        // get the ain for the name
        ain = ainByName.get(ain);
      }
      readSwitch(homeAutomation, ain);
    }

    /**
     * loop over all devices to be set
     */
    if (setDevices.size() % 2 != 0) {
      usage("set needs pairs of name=on/off");
    }
    for (int i = 0; i < setDevices.size(); i += 2) {
      final String name = setDevices.get(i);
      final String powerState = setDevices.get(i + 1);
      // check if a name was given
      String ain = name;
      if (ainByName.containsKey(ain)) {
        // get the ain for the name
        ain = ainByName.get(ain);
      }
      boolean newState = false;
      switch (powerState) {
      case "on":
        newState = true;
        break;
      case "off":
        newState = false;
        break;
      default:
        usage(String.format(
            "%s is not a valid powerState it needs to be on or off",
            powerState));
      }
      show("switching %s %s", name, powerState);
      homeAutomation.setSwitchOnOff(ain, newState);
    }
    
  }
}

CmdLine

Help / Usage

java -jar fritzbox-java.jar -h

Help
FritzBox Java API Command Line Version: 0.0.1

github: https://github.com/BITPlan/com.bitplan.fritzbox

  usage: java -jar fritzbox.jar
 -d (--debug)         : debug
                        create additional debug output if this switch is used
                        (Vorgabe: false)
 -h (--help)          : help
                        show this usage (Vorgabe: true)
 -l (--list)          : list
                        list devices (Vorgabe: false)
 -r (--read) STRING[] : read
                        read the given devices
 -s (--set) STRING[]  : set
                        set the given devices to the givnen states e.g. main off
 -v (--version)       : showVersion
                        show current version if this switch is used (Vorgabe:
                        false)

List devices

java -jar fritzbox.jar -l
                Name |         By |         Product | Identifier
---------------------+------------+-----------------+-------------------------
            Aquarium |        AVM |  FRITZ!DECT 200 | 08761 0033476
          Wohnzimmer |        AVM |  FRITZ!DECT 200 | 08761 0092893

read devices

java -jar fritzbox.jar -r Aquarium Wohnzimmer
 name: Aquarium
   id: 087610033476 
alive: true
   on: false
 uses:     0     W
 used:   940,882 kWh
 temp:    25,0   °C

 name: Wohnzimmer
   id: 087610092893 
alive: true
   on: true
 uses:     1     W
 used:    35,510 kWh
 temp:    24,5   °C

switch devices on / off

java -jar fritzbox.jar -s Aquarium off  Wohnzimmer on
switching Aquarium off
switching Wohnzimmer on

Links

History

and was used at BITPlan internally for a while until we got unhappy with the license and the details of the implementation. Therefore we started a new implementation "from scratch".

C# version

The code at:

is a starting point. It reads the same application.properties and gets a session id to work with.