Difference between revisions of "Fritzbox-java-api"

From BITPlan Wiki
Jump to navigation Jump to search
 
(14 intermediate revisions by the same user not shown)
Line 1: Line 1:
* https://github.com/WolfgangFahl/fritzbox-java-api is a fork of
+
{{OsProject
* https://github.com/kaklakariada/fritzbox-java-api
+
|id=com.bitplan.fritzbox
 +
|owner=BITPlan
 +
|title=Java API for Fritzbox
 +
|url=https://github.com/BITPlan/com.bitplan.fritzbox
 +
|version=0.0.5
 +
|date=2018/08/24
 +
}}
 +
 
 
= API =
 
= API =
see https://avm.de/fileadmin/user_upload/Global/Service/Schnittstellen/AHA-HTTP-Interface.pdf
+
* see https://avm.de/fileadmin/user_upload/Global/Service/Schnittstellen/AHA-HTTP-Interface.pdf
see https://stackoverflow.com/tags/fritzbox/info (with Links to Implementations)
+
* see https://stackoverflow.com/tags/fritzbox/info (with Links to Implementations)
 
 
= C# version =
 
The code at:
 
* https://github.com/WolfgangFahl/fritz-csharp-api
 
is a starting point. It reads the same application.properties and gets a session id to work with.
 
  
 
= Unit tests =
 
= Unit tests =
Line 15: Line 17:
 
mvn test
 
mvn test
 
</source>
 
</source>
If you did not setup your configuration file yet there will be a warning:
+
If you did not setup your configuration file yet the test will run against a mocked FritzBox.
'''You might want to set your application properties in $HOME.fritzbox/application.properties
+
When the application properties are set you might want to change the test parameters according to your environment.
'''
+
 
When the application properties are set more tests are run. E.g. one test should show "Logged in with session id ..."
 
 
= Configuration File =
 
= Configuration File =
 
You might want to set your application properties in $HOME/.fritzbox/application.properties
 
You might want to set your application properties in $HOME/.fritzbox/application.properties
Line 27: Line 28:
 
</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 ==
 
<source lang='bash'>
 
<source lang='bash'>
java -jar fritzbox-java-api-0.4.2.jar -h
+
java -jar fritzbox-java.jar -h
  
 
Help
 
Help
FritzBox Java API Command Line Version: 0.4.2
+
FritzBox Java API Command Line Version: 0.0.1
  
github: https://github.com/kaklakariada/fritzbox-java-api
+
github: https://github.com/BITPlan/com.bitplan.fritzbox
  
 
   usage: java -jar fritzbox.jar
 
   usage: java -jar fritzbox.jar
Line 81: Line 157:
  
 
</source>
 
</source>
 +
 
== List devices  ==
 
== List devices  ==
 
<source lang='bash'>
 
<source lang='bash'>
java -jar fritzbox-java-api-0.4.2.jar -l
+
java -jar fritzbox.jar -l
 
                 Name |        By |        Product | Identifier
 
                 Name |        By |        Product | Identifier
 
---------------------+------------+-----------------+-------------------------
 
---------------------+------------+-----------------+-------------------------
Line 92: Line 169:
 
== read devices ==
 
== read devices ==
 
<source lang='bash'>
 
<source lang='bash'>
java -jar fritzbox-java-api-0.4.2.jar -r Aquarium Wohnzimmer
+
java -jar fritzbox.jar -r Aquarium Wohnzimmer
 
  name: Aquarium
 
  name: Aquarium
 
   id: 087610033476  
 
   id: 087610033476  
Line 109: Line 186:
 
  temp:    24,5  °C
 
  temp:    24,5  °C
 
</source>
 
</source>
== set devices ==
+
 
 +
== switch devices on / off ==
 
<source lang='bash'>
 
<source lang='bash'>
java -jar fritzbox-java-api-0.4.2.jar -s Aquarium off  Wohnzimmer on
+
java -jar fritzbox.jar -s Aquarium off  Wohnzimmer on
 
switching Aquarium off
 
switching Aquarium off
 
switching Wohnzimmer on
 
switching Wohnzimmer on
Line 119: Line 197:
 
* https://www.pcwelt.de/ratgeber/Dect-Funksteckdosen-10022547.html
 
* https://www.pcwelt.de/ratgeber/Dect-Funksteckdosen-10022547.html
 
* https://wiki.ubuntuusers.de/FritzBox/Skripte/
 
* https://wiki.ubuntuusers.de/FritzBox/Skripte/
 +
* https://github.com/andig/fritzapi
 +
 +
= History =
 +
* https://github.com/WolfgangFahl/fritzbox-java-api was a fork of
 +
* https://github.com/kaklakariada/fritzbox-java-api
 +
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:
 +
* https://github.com/WolfgangFahl/fritz-csharp-api
 +
is a starting point. It reads the same application.properties and gets a session id to work with.
 +
[[Category:frontend]]

Latest revision as of 12:04, 19 August 2019

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

API

Unit tests

The unit tests can be run with:

mvn test

If you did not setup your configuration file yet the test will run against a mocked FritzBox. When the application properties are set you might want to change the test parameters according to your environment.

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.