Driver for Infinera Groove G30

Change-Id: Id7710a7a4f68033ab9553f2d6ad160b96530d1a3
diff --git a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveModulationOpenConfig.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveModulationOpenConfig.java
new file mode 100644
index 0000000..0b7cde8
--- /dev/null
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveModulationOpenConfig.java
@@ -0,0 +1,451 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * This work was partially supported by EC H2020 project METRO-HAUL (761727).
+ */
+package org.onosproject.drivers.odtn;
+
+import org.apache.commons.configuration.HierarchicalConfiguration;
+import org.apache.commons.configuration.XMLConfiguration;
+import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
+import org.onlab.osgi.DefaultServiceDirectory;
+import org.onosproject.drivers.utilities.XmlConfigParser;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.ModulationScheme;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.ModulationConfig;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.netconf.DatastoreId;
+import org.onosproject.netconf.NetconfController;
+import org.onosproject.netconf.NetconfDevice;
+import org.onosproject.netconf.NetconfException;
+import org.onosproject.netconf.NetconfSession;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/*
+ * Driver Implementation of the ModulationConfig for OcNos standard open config based terminal devices.
+ */
+public class GrooveModulationOpenConfig<T> extends AbstractHandlerBehaviour implements ModulationConfig<T> {
+
+
+    private static final String RPC_TAG_NETCONF_BASE =
+            "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">";
+
+    private static final String RPC_CLOSE_TAG = "</rpc>";
+
+    private static final Logger log = LoggerFactory.getLogger(GrooveModulationOpenConfig.class);
+
+    private ComponentType state = ComponentType.DIRECTION;
+
+
+    enum BitRate {
+        GBPS_200(200),      // 200 Gbps
+        GBPS_100(100),        // 100 Gbps
+        GBPS_40(40),          // 40 Gbps
+        GBPS_10(10);          // 10 Gbps
+
+        private final long value;
+
+        public long getValue() {
+            return value;
+        }
+
+        BitRate(long value) {
+            this.value = value;
+        }
+    }
+
+    /**
+     * Returns the NetconfSession with the device for which the method was called.
+     *
+     * @param deviceId device indetifier
+     * @return The netconf session or null
+     */
+
+
+    private NetconfSession getNetconfSession(DeviceId deviceId) {
+        log.info("Inside getNetconfSession () method for device : {}", deviceId);
+        NetconfController controller = handler().get(NetconfController.class);
+        NetconfDevice ncdev = controller.getDevicesMap().get(deviceId);
+        if (ncdev == null) {
+            log.trace("No netconf device, returning null session");
+            return null;
+        }
+        return ncdev.getSession();
+    }
+
+    /*
+     *
+     * Get the deviceId for which the methods apply.
+     *
+     * @return The deviceId as contained in the handler data
+     */
+
+
+    private DeviceId did() {
+        return handler().data().deviceId();
+    }
+
+    /**
+     * Execute RPC request.
+     *
+     * @param session Netconf session
+     * @param message Netconf message in XML format
+     * @return XMLConfiguration object
+     */
+
+    private XMLConfiguration executeRpc(NetconfSession session, String message) {
+        try {
+            CompletableFuture<String> fut = session.rpc(message);
+            String rpcReply = fut.get();
+            XMLConfiguration xconf = (XMLConfiguration) XmlConfigParser.loadXmlString(rpcReply);
+            xconf.setExpressionEngine(new XPathExpressionEngine());
+            return xconf;
+        } catch (NetconfException ne) {
+            log.error("Exception on Netconf protocol: {}.", ne);
+        } catch (InterruptedException ie) {
+            log.error("Interrupted Exception: {}.", ie);
+        } catch (ExecutionException ee) {
+            log.error("Concurrent Exception while executing Netconf operation: {}.", ee);
+        }
+        return null;
+    }
+
+    /**
+     * Get the target Modulation Scheme on the component.
+     *
+     * @param port      the port
+     * @param component the port component
+     * @return ModulationScheme as per bitRate value
+     **/
+    @Override
+    public Optional<ModulationScheme> getModulationScheme(PortNumber port, T component) {
+        checkState(component);
+        return state.getModulationScheme(port, component);
+    }
+
+    /**
+     * Set the target Modulation Scheme on the component.
+     *
+     * @param port      the port
+     * @param component the port component
+     * @param bitRate   bit rate in bps
+     **/
+    @Override
+    public void setModulationScheme(PortNumber port, T component, long bitRate) {
+        checkState(component);
+        state.setModulationScheme(port, component, bitRate);
+    }
+
+
+    /*
+     *
+     * Set the ComponentType to invoke proper methods for different template T.
+     * @param component the component.
+     */
+    void checkState(Object component) {
+        String clsName = component.getClass().getName();
+        switch (clsName) {
+            case "org.onosproject.net.Direction":
+                state = ComponentType.DIRECTION;
+                break;
+            case "org.onosproject.net.OchSignal":
+                state = ComponentType.OCHSIGNAL;
+                break;
+            default:
+                log.error("Cannot parse the component type {}.", clsName);
+                log.info("The component content is {}.", component.toString());
+        }
+
+        state.groove = this;
+        log.info("Setting the state with clsName :{} ", clsName);
+    }
+
+    /*
+     *
+     * Component type.
+     */
+    enum ComponentType {
+
+        /*
+         *
+         * Direction.
+         */
+        DIRECTION() {
+            @Override
+            Optional<ModulationScheme> getModulationScheme(PortNumber port, Object component) {
+                return super.getModulationScheme(port, component);
+            }
+
+            @Override
+            void setModulationScheme(PortNumber port, Object component, long bitRate) {
+                log.info("Inside the enum setModulationScheme()");
+                super.setModulationScheme(port, component, bitRate);
+            }
+        },
+
+        /**
+         * OchSignal.
+         */
+        OCHSIGNAL() {
+            @Override
+            Optional<ModulationScheme> getModulationScheme(PortNumber port, Object component) {
+                return super.getModulationScheme(port, component);
+            }
+
+            @Override
+            void setModulationScheme(PortNumber port, Object component, long bitRate) {
+                super.setModulationScheme(port, component, bitRate);
+            }
+        };
+
+
+        GrooveModulationOpenConfig groove;
+
+        /*
+         * mirror method in the internal class.
+         * @param port port
+         * @param component component
+         * @return target modulation
+         */
+        Optional<ModulationScheme> getModulationScheme(PortNumber port, Object component) {
+            NetconfSession session = groove.getNetconfSession(groove.did());
+            checkNotNull(session);
+            String filter = createModulationFilter(groove, port);
+            StringBuilder rpcReq = new StringBuilder();
+            rpcReq.append(RPC_TAG_NETCONF_BASE)
+                    .append("<get-config>")
+                    .append("<source>")
+                    .append("<" + DatastoreId.RUNNING + "/>")
+                    .append("</source>")
+                    .append("<filter type='subtree'>")
+                    .append(filter)
+                    .append("</filter>")
+                    .append("</get-config>")
+                    .append(RPC_CLOSE_TAG);
+            XMLConfiguration xconf = groove.executeRpc(session, rpcReq.toString());
+            if (xconf == null) {
+                log.error("Error in executingRpc");
+                return Optional.empty();
+            }
+            try {
+                HierarchicalConfiguration config =
+                        xconf.configurationAt("data/components/component/optical-channel/config");
+
+                String operationalMode = String.valueOf(config.getString("operational-mode"));
+                /*Used for Internal Testing */
+                //String modulationScheme="DP16QAM";
+                ModulationScheme modulation;
+                if (operationalMode.equalsIgnoreCase("62") ||
+                        operationalMode.equalsIgnoreCase("68")) {
+                    modulation = ModulationScheme.DP_16QAM;
+                } else {
+                    modulation = ModulationScheme.DP_QPSK;
+                }
+                return Optional.of(modulation);
+            } catch (IllegalArgumentException e) {
+                log.error("Error in parsing config", e);
+                return Optional.empty();
+            }
+        }
+
+        /*
+         * mirror method in the internal class.
+         * @param port port
+         * @param component component
+         * @param power target value
+         */
+        void setModulationScheme(PortNumber port, Object component, long bitRate) {
+
+            ModulationScheme modulation = null;
+            if (bitRate <= BitRate.GBPS_100.value) {
+                modulation = ModulationScheme.DP_QPSK;
+            } else {
+                modulation = ModulationScheme.DP_16QAM;
+
+            }
+            // TODO: Groove doesn't support to change the modulation format via OpenConfig directly
+            //  without recommissioning the Optical Channel
+            // Workaround: use Groove native model via port-mode change
+            // String editConfig = modulationEditConfig(groove, port, component, bitRate, modulation.name());
+            String editConfig = groovePortModeEditConfig(groove, port, component, bitRate, modulation.name());
+
+            //setting the modulation by calling rpc
+            setModulationRpc(port, component, editConfig);
+
+        }
+
+        private static String createModulationFilter(GrooveModulationOpenConfig modulationConfig,
+                                                     PortNumber portNumber) {
+            String name = ocName(modulationConfig, portNumber);
+            StringBuilder sb = new StringBuilder("<components xmlns=\"http://openconfig.net/yang/platform\">");
+            sb.append("<component>").append("<name>").append(name).append("</name>");
+            sb.append("</component>").append("</components>");
+            return sb.toString();
+        }
+
+        /**
+         * Extract component name from portNumber's annotations.
+         *
+         * @param pc         modulation config instance
+         * @param portNumber the port number
+         * @return the component name
+         */
+
+
+        private static String ocName(GrooveModulationOpenConfig pc, PortNumber portNumber) {
+            DeviceService deviceService = DefaultServiceDirectory.getService(DeviceService.class);
+            DeviceId deviceId = pc.handler().data().deviceId();
+            return deviceService.getPort(deviceId, portNumber).annotations().value("oc-name");
+        }
+
+        /*
+         *
+         * Parse filtering string from port and component.
+         * @param portNumber Port Number
+         * @param component port component (optical-channel)
+         * @param bitRate bitRate in bps
+         * @return filtering string in xml format
+         */
+        private String modulationEditConfig(GrooveModulationOpenConfig modulationConfig, PortNumber portNumber,
+                                            Object component, long bitRate, String modulation) {
+            /*
+             <components xmlns="http://openconfig.net/yang/platform">
+               <component>
+                 <name>oc1/0</name>
+                 <config>
+                    <name>oc1/0</name>
+                 </config>
+                 <optical-channel xmlns="http://openconfig.net/yang/terminal-device">
+                   <config>
+                      <operational-mode>62</operational-mode>
+                   </config>
+                 </optical-channel>
+               </component>
+             </components>
+             */
+            String operationalMode = convertToGrooveOperationalMode(modulation);
+            if (component != null) {
+                // This is an edit-config operation.
+                String portName = ocName(modulationConfig, portNumber); //oc1/0
+                StringBuilder sb = new StringBuilder("<components xmlns=\"http://openconfig.net/yang/platform\">");
+                sb.append("<component>");
+                sb.append("<name>").append(portName).append("</name>");
+                sb.append("<config>");
+                sb.append("<name>").append(portName).append("</name>");
+                sb.append("</config>");
+                sb.append("<optical-channel xmlns=\"http://openconfig.net/yang/terminal-device\">")
+                        .append("<config>")
+                        .append("<operational-mode>")
+                        .append(operationalMode)
+                        .append("</operational-mode>")
+                        .append("</config>")
+                        .append("</optical-channel>");
+                sb.append("</component>");
+                sb.append("</components>");
+                return sb.toString();
+            } else {
+                log.error("Cannot process the component {}.", component.getClass());
+                return null;
+            }
+        }
+
+        /*
+         *
+         * Parse filtering string from port and component.
+         * @param portNumber Port Number
+         * @param component port component (optical-channel)
+         * @param bitRate bitRate in bps
+         * @return filtering string in xml format
+         */
+        private String groovePortModeEditConfig(GrooveModulationOpenConfig modulationConfig, PortNumber portNumber,
+                                                Object component, long bitRate, String modulation) {
+            if (component != null) {
+                // This is an edit-config operation.
+                String portMode = modulation.equals("DP_QPSK") ? "QPSK_100G" : "16QAM_200G";
+                String portName = ocName(modulationConfig, portNumber);
+                Pattern portPattern = Pattern.compile(".*-[1]-[1-9][0-4]?-L[1-2]$"); // e.g. TRANSCEIVER-1-1-L1
+                Matcher lineMatch = portPattern.matcher(portName);
+                lineMatch.find();
+                final String[] split = lineMatch.group(0).split("-");
+
+                return "<ne xmlns=\"http://coriant.com/yang/os/ne\">" +
+                        "        <shelf>" +
+                        "          <shelf-id>" + split[1] + "</shelf-id>" +
+                        "          <slot>" +
+                        "            <slot-id>" + split[2] + "</slot-id>" +
+                        "            <card>" +
+                        "              <port>" +
+                        "                <port-id>" + split[3].replace("L", "") + "</port-id>" +
+                        "                <port-mode>" + portMode + "</port-mode>" +
+                        "              </port>" +
+                        "            </card>" +
+                        "          </slot>" +
+                        "        </shelf>" +
+                        "      </ne>";
+            } else {
+                log.error("Cannot process the component {}.", component.getClass());
+                return null;
+            }
+        }
+
+
+        private String convertToGrooveOperationalMode(String modulation) {
+            if (modulation.equals(ModulationScheme.DP_QPSK.name())) {
+                return "22"; // Symbol rate 100G; modulation DP-QPSK; FEC mode SDFEC25
+            } else {
+                return "62"; // Symbol rate 200G; modulation DP-16QAM; FEC mode SDFEC25
+            }
+        }
+
+        private boolean setModulationRpc(PortNumber port, Object component, String editConfig) {
+            // NOTE: this doesn't work in current Groove version.
+            NetconfSession session = groove.getNetconfSession(groove.did());
+            checkNotNull(session);
+            boolean response = true;
+            StringBuilder rpcReq = new StringBuilder();
+            rpcReq.append(RPC_TAG_NETCONF_BASE)
+                    .append("<edit-config>")
+                    .append("<target><" + DatastoreId.RUNNING + "/></target>")
+                    .append("<config>")
+                    .append(editConfig)
+                    .append("</config>")
+                    .append("</edit-config>")
+                    .append(RPC_CLOSE_TAG);
+            log.info("RPC call for Setting Modulation : {}", rpcReq.toString());
+            XMLConfiguration xconf = groove.executeRpc(session, rpcReq.toString());
+            if (xconf == null) {
+                log.error("The <edit-config> operation to set target-modulation of Port({}:{}) is failed.",
+                        port.toString(), component.toString());
+            } else if (!xconf.getRoot().getChild(0).getName().equals("ok")) {
+                // The successful reply should be "<rpc-reply ...><ok /></rpc-reply>"
+                response = false;
+                log.error("The <edit-config> operation to set target-modulation of Port({}:{}) is failed.",
+                        port.toString(), component.toString());
+            }
+            return response;
+        }
+    }
+}
diff --git a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigDeviceDiscovery.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigDeviceDiscovery.java
new file mode 100644
index 0000000..eebbb85
--- /dev/null
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigDeviceDiscovery.java
@@ -0,0 +1,322 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * This work was partially supported by EC H2020 project METRO-HAUL (761727).
+ */
+
+package org.onosproject.drivers.odtn;
+
+import com.google.common.collect.ImmutableList;
+import org.apache.commons.configuration.HierarchicalConfiguration;
+import org.apache.commons.configuration.XMLConfiguration;
+import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
+import org.onlab.packet.ChassisId;
+import org.onosproject.drivers.utilities.XmlConfigParser;
+import org.onosproject.net.ChannelSpacing;
+import org.onosproject.net.DefaultAnnotations;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.OchSignal;
+import org.onosproject.net.OduSignalType;
+import org.onosproject.net.Port.Type;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.device.DefaultDeviceDescription;
+import org.onosproject.net.device.DefaultPortDescription;
+import org.onosproject.net.device.DefaultPortDescription.Builder;
+import org.onosproject.net.device.DeviceDescription;
+import org.onosproject.net.device.DeviceDescriptionDiscovery;
+import org.onosproject.net.device.PortDescription;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.net.optical.device.OchPortHelper;
+import org.onosproject.netconf.NetconfController;
+import org.onosproject.netconf.NetconfDevice;
+import org.onosproject.netconf.NetconfSession;
+import org.onosproject.odtn.behaviour.OdtnDeviceDescriptionDiscovery;
+import org.slf4j.Logger;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.CompletableFuture;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+
+/**
+ * Driver Implementation of the DeviceDescrption discovery for OpenConfig
+ * terminal devices.
+ *
+ */
+public class GrooveOpenConfigDeviceDiscovery
+        extends AbstractHandlerBehaviour
+        implements OdtnDeviceDescriptionDiscovery, DeviceDescriptionDiscovery {
+
+    private static final String RPC_TAG_NETCONF_BASE =
+            "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">";
+
+    private static final String RPC_CLOSE_TAG = "</rpc>";
+
+    private static final String OC_PLATFORM_TYPES_TRANSCEIVER =
+            "oc-platform-types:TRANSCEIVER";
+
+    private static final String OC_PLATFORM_TYPES_PORT =
+            "oc-platform-types:PORT";
+
+    private static final String OC_TRANSPORT_TYPES_OPTICAL_CHANNEL =
+            "oc-opt-types:OPTICAL_CHANNEL";
+
+    private static final Logger log = getLogger(GrooveOpenConfigDeviceDiscovery.class);
+
+
+    /**
+     * Returns the NetconfSession with the device for which the method was called.
+     *
+     * @param deviceId device indetifier
+     *
+     * @return The netconf session or null
+     */
+    private NetconfSession getNetconfSession(DeviceId deviceId) {
+        NetconfController controller = handler().get(NetconfController.class);
+        NetconfDevice ncdev = controller.getDevicesMap().get(deviceId);
+        if (ncdev == null) {
+            log.trace("No netconf device, returning null session");
+            return null;
+        }
+        return ncdev.getSession();
+    }
+
+
+    /**
+     * Get the deviceId for which the methods apply.
+     *
+     * @return The deviceId as contained in the handler data
+     */
+    private DeviceId did() {
+        return handler().data().deviceId();
+    }
+
+
+    /**
+     * Construct a String with a Netconf filtered get RPC Message.
+     *
+     * @param filter A valid XML tree with the filter to apply in the get
+     * @return a String containing the RPC XML Document
+     */
+    private String filteredGetBuilder(String filter) {
+        StringBuilder rpc = new StringBuilder(RPC_TAG_NETCONF_BASE);
+        rpc.append("<get>");
+        rpc.append("<filter type='subtree'>");
+        rpc.append(filter);
+        rpc.append("</filter>");
+        rpc.append("</get>");
+        rpc.append(RPC_CLOSE_TAG);
+        return rpc.toString();
+    }
+
+
+    /**
+     * Builds a request to get Device Components, config and operational data.
+     *
+     * @return A string with the Netconf RPC for a get with subtree rpcing based on
+     *    /components/
+     */
+    private String getTerminalDeviceBuilder() {
+        return filteredGetBuilder("<terminal-device xmlns='http://openconfig.net/yang/terminal-device'/>");
+    }
+
+
+    @Override
+    public DeviceDescription discoverDeviceDetails() {
+        return new DefaultDeviceDescription(handler().data().deviceId().uri(),
+                                            Device.Type.TERMINAL_DEVICE,
+                                            "Infinera",
+                                            "Groove",
+                                            "4.0.3",
+                                            "",
+                                            new ChassisId("1"));
+    }
+
+
+
+    /**
+     * Returns a list of PortDescriptions for the device.
+     *
+     * @return a list of descriptions.
+     *
+     * The RPC reply follows the following pattern:
+     * //CHECKSTYLE:OFF
+     * <pre>{@code
+     * <?xml version="1.0" encoding="UTF-8"?>
+     * <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="7">
+     * <data>
+     *   <components xmlns="http://openconfig.net/yang/platform">
+     *     <component>....
+     *     </component>
+     *     <component>....
+     *     </component>
+     *   </components>
+     * </data>
+     * </rpc-reply>
+     * }</pre>
+     * //CHECKSTYLE:ON
+     */
+    @Override
+    public List<PortDescription> discoverPortDetails() {
+        try {
+            NetconfSession session = getNetconfSession(did());
+            if (session == null) {
+                log.error("discoverPortDetails called with null session for {}", did());
+                return ImmutableList.of();
+            }
+
+            CompletableFuture<String> fut = session.rpc(getTerminalDeviceBuilder());
+            String rpcReply = fut.get();
+
+            XMLConfiguration xconf = (XMLConfiguration) XmlConfigParser.loadXmlString(rpcReply);
+            xconf.setExpressionEngine(new XPathExpressionEngine());
+
+            HierarchicalConfiguration logicalChannels = xconf.configurationAt("data/terminal-device/logical-channels");
+            return parseLogicalChannels(logicalChannels);
+        } catch (Exception e) {
+            log.error("Exception discoverPortDetails() {}", did(), e);
+            return ImmutableList.of();
+        }
+    }
+
+
+
+
+    /**
+     * Parses transceiver information from OpenConfig XML configuration.
+     *
+     * @param terminalDevice the XML document with components root.
+     * @return List of ports
+     *
+     * //CHECKSTYLE:OFFPlainTransceiver
+     * <pre>{@code
+     *   <components xmlns="http://openconfig.net/yang/platform">
+     *     <component>....
+     *     </component>
+     *     <component>....
+     *     </component>
+     *   </components>
+     * }</pre>
+     * //CHECKSTYLE:ON
+     */
+    protected List<PortDescription> parseLogicalChannels(HierarchicalConfiguration terminalDevice) {
+        return terminalDevice.configurationsAt("channel")
+                .stream()
+                .filter(channel -> !channel.getString("index", "unknown")
+                        .equals("unknown"))
+                .map(channel -> {
+                    try {
+                        // Pass the root document for cross-reference
+                        return parseLogicalChannel(channel);
+                    } catch (Exception e) {
+                        return null;
+                    }
+                })
+                .filter(Objects::nonNull)
+                .collect(Collectors.toList());
+    }
+
+
+    /**
+     * Parses a component XML doc into a PortDescription.
+     *
+     * @param channel subtree to parse. It must be a component ot type PORT.
+     *  case we need to check transceivers or optical channels.
+     *
+     * @return PortDescription or null if component does not have onos-index
+     */
+    private PortDescription parseLogicalChannel(HierarchicalConfiguration channel) {
+        HierarchicalConfiguration config = channel.configurationAt("config");
+        String logicalChannelIndex = config.getString("index");
+        String description = config.getString("description");
+        String rateClass = config.getString("rate-class");
+        Map<String, String> annotations = new HashMap<>();
+        annotations.put(OdtnDeviceDescriptionDiscovery.OC_LOGICAL_CHANNEL, logicalChannelIndex);
+        HierarchicalConfiguration assignment =
+                channel.configurationAt("logical-channel-assignments/assignment[index=1]/config");
+        annotations.put(OdtnDeviceDescriptionDiscovery.OC_NAME, assignment.getString("optical-channel"));
+
+        // Store all properties as port properties
+        Pattern clientPattern = Pattern.compile(".*-[1]-[1-9][0-4]?-C[3-9]$"); // e.g. 100GE-1-14-C3
+        Pattern linePattern = Pattern.compile(".*-[1]-[1-9][0-4]?-L[1-2]$"); // e.g. OTUC2-1-1-L2
+
+        Matcher clientMatch = clientPattern.matcher(description);
+        Matcher lineMatch = linePattern.matcher(description);
+
+        Pattern portSpeedPattern = Pattern.compile("TRIB_RATE_([0-9.]*)G");
+        Matcher portSpeedMatch = portSpeedPattern.matcher(rateClass);
+
+        Builder builder = DefaultPortDescription.builder();
+
+        Long speed = 0L;
+
+        if (portSpeedMatch.find()) {
+            speed = Long.parseLong(portSpeedMatch.group(1));
+            builder.portSpeed(speed * 1000);
+        }
+
+        if (clientMatch.find()) {
+            log.info("Parsing CLIENT port {} type {} rate {}", logicalChannelIndex, description, rateClass);
+            final String[] split = clientMatch.group(0).split("-");
+            Long portNum = (10000 * Long.parseLong(split[1])) +
+                    (100 * Long.parseLong(split[2])) +
+                    Long.parseLong(split[3].replace("C", ""));
+            String connectionId = "connection:" + portNum;
+
+            annotations.putIfAbsent(PORT_TYPE, OdtnPortType.CLIENT.value());
+            annotations.putIfAbsent(ONOS_PORT_INDEX, portNum.toString());
+            annotations.putIfAbsent(CONNECTION_ID, connectionId);
+
+            builder.withPortNumber(PortNumber.portNumber(portNum));
+            builder.type(Type.PACKET);
+
+            builder.annotations(DefaultAnnotations.builder().putAll(annotations).build());
+            return builder.build();
+
+        } else if (lineMatch.find()) {
+            log.info("Parsing LINE port {} type {} rate {}", logicalChannelIndex, description, rateClass);
+            final String[] split = lineMatch.group(0).split("-");
+            Long portNum = (10000 * Long.parseLong(split[1])) +
+                           (100 * Long.parseLong(split[2])) +
+                            Long.parseLong(split[3].replace("L", ""));
+            String connectionId = "connection:" + portNum;
+
+            annotations.putIfAbsent(PORT_TYPE, OdtnPortType.LINE.value());
+            annotations.putIfAbsent(ONOS_PORT_INDEX, portNum.toString());
+            annotations.putIfAbsent(CONNECTION_ID, connectionId);
+            OchSignal signalId = OchSignal.newDwdmSlot(ChannelSpacing.CHL_50GHZ, 1);
+
+            return OchPortHelper.ochPortDescription(
+                    PortNumber.portNumber(portNum),
+                    true,
+                    speed == 200 ? OduSignalType.ODUC2 : OduSignalType.ODU4,
+                    true,
+                    signalId,
+                    DefaultAnnotations.builder().putAll(annotations).build());
+
+        } else {
+            log.debug("Discarding component: {}", description);
+            return null;
+        }
+    }
+}
diff --git a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigDevicePowerConfig.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigDevicePowerConfig.java
new file mode 100644
index 0000000..d38345b
--- /dev/null
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigDevicePowerConfig.java
@@ -0,0 +1,440 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+
+ * This work was partially supported by EC H2020 project METRO-HAUL (761727).
+ */
+
+package org.onosproject.drivers.odtn;
+
+import com.google.common.collect.Range;
+import org.apache.commons.configuration.HierarchicalConfiguration;
+import org.apache.commons.configuration.XMLConfiguration;
+import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
+import org.onlab.osgi.DefaultServiceDirectory;
+import org.onosproject.drivers.utilities.XmlConfigParser;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.PowerConfig;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.netconf.NetconfController;
+import org.onosproject.netconf.NetconfDevice;
+import org.onosproject.netconf.NetconfException;
+import org.onosproject.netconf.NetconfSession;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Driver Implementation of the PowerConfig for OpenConfig terminal devices.
+ */
+public class GrooveOpenConfigDevicePowerConfig<T>
+        extends AbstractHandlerBehaviour implements PowerConfig<T> {
+    private static final String RPC_TAG_NETCONF_BASE =
+            "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">";
+
+    private static final String RPC_CLOSE_TAG = "</rpc>";
+
+    private static final long NO_POWER = -50;
+
+    private static final Logger log = getLogger(GrooveOpenConfigDevicePowerConfig.class);
+
+    private ComponentType state = ComponentType.DIRECTION;
+
+    /**
+     * Returns the NetconfSession with the device for which the method was called.
+     *
+     * @param deviceId device indetifier
+     * @return The netconf session or null
+     */
+    private NetconfSession getNetconfSession(DeviceId deviceId) {
+        NetconfController controller = handler().get(NetconfController.class);
+        NetconfDevice ncdev = controller.getDevicesMap().get(deviceId);
+        if (ncdev == null) {
+            log.trace("No netconf device, returning null session");
+            return null;
+        }
+        return ncdev.getSession();
+    }
+
+    /**
+     * Get the deviceId for which the methods apply.
+     *
+     * @return The deviceId as contained in the handler data
+     */
+    private DeviceId did() {
+        return handler().data().deviceId();
+    }
+
+    /**
+     * Execute RPC request.
+     *
+     * @param session Netconf session
+     * @param message Netconf message in XML format
+     * @return XMLConfiguration object
+     */
+    private XMLConfiguration executeRpc(NetconfSession session, String message) {
+        try {
+            CompletableFuture<String> fut = session.rpc(message);
+            String rpcReply = fut.get();
+            XMLConfiguration xconf = (XMLConfiguration) XmlConfigParser.loadXmlString(rpcReply);
+            xconf.setExpressionEngine(new XPathExpressionEngine());
+            return xconf;
+        } catch (NetconfException ne) {
+            log.error("Exception on Netconf protocol: {}.", ne);
+        } catch (InterruptedException ie) {
+            log.error("Interrupted Exception: {}.", ie);
+        } catch (ExecutionException ee) {
+            log.error("Concurrent Exception while executing Netconf operation: {}.", ee);
+        }
+        return null;
+    }
+
+    /**
+     * Get the target-output-power value on specific optical-channel.
+     *
+     * @param port      the port
+     * @param component the port component. It should be 'oc-name' in the Annotations of Port.
+     *                  'oc-name' could be mapped to '/component/name' in openconfig yang.
+     * @return target power value
+     */
+    @Override
+    public Optional<Double> getTargetPower(PortNumber port, T component) {
+        checkState(component);
+        return state.getTargetPower(port, component);
+    }
+
+    @Override
+    public void setTargetPower(PortNumber port, T component, double power) {
+        checkState(component);
+        state.setTargetPower(port, component, power);
+    }
+
+    @Override
+    public Optional<Double> currentPower(PortNumber port, T component) {
+        checkState(component);
+        return state.currentPower(port, component);
+    }
+
+    @Override
+    public Optional<Double> currentInputPower(PortNumber port, T component) {
+        checkState(component);
+        return state.currentInputPower(port, component);
+    }
+
+    @Override
+    public Optional<Range<Double>> getTargetPowerRange(PortNumber port, T component) {
+        checkState(component);
+        return state.getTargetPowerRange(port, component);
+    }
+
+    @Override
+    public Optional<Range<Double>> getInputPowerRange(PortNumber port, T component) {
+        checkState(component);
+        return state.getInputPowerRange(port, component);
+    }
+
+    @Override
+    public List<PortNumber> getPorts(T component) {
+        checkState(component);
+        return state.getPorts(component);
+    }
+
+
+    /**
+     * Set the ComponentType to invoke proper methods for different template T.
+     *
+     * @param component the component.
+     */
+    void checkState(Object component) {
+        String clsName = component.getClass().getName();
+        switch (clsName) {
+            case "org.onosproject.net.Direction":
+                state = ComponentType.DIRECTION;
+                break;
+            case "org.onosproject.net.OchSignal":
+                state = ComponentType.OCHSIGNAL;
+                break;
+            default:
+                log.error("Cannot parse the component type {}.", clsName);
+                log.info("The component content is {}.", component.toString());
+        }
+        state.groove = this;
+    }
+
+    /**
+     * Component type.
+     */
+    enum ComponentType {
+
+        /**
+         * Direction.
+         */
+        DIRECTION() {
+            @Override
+            public Optional<Double> getTargetPower(PortNumber port, Object component) {
+                return super.getTargetPower(port, component);
+            }
+
+            @Override
+            public void setTargetPower(PortNumber port, Object component, double power) {
+                super.setTargetPower(port, component, power);
+            }
+        },
+
+        /**
+         * OchSignal.
+         */
+        OCHSIGNAL() {
+            @Override
+            public Optional<Double> getTargetPower(PortNumber port, Object component) {
+                return super.getTargetPower(port, component);
+            }
+
+            @Override
+            public void setTargetPower(PortNumber port, Object component, double power) {
+                super.setTargetPower(port, component, power);
+            }
+        };
+
+
+        GrooveOpenConfigDevicePowerConfig groove;
+
+        /**
+         * mirror method in the internal class.
+         *
+         * @param port      port
+         * @param component component
+         * @return target power
+         */
+        Optional<Double> getTargetPower(PortNumber port, Object component) {
+            if (!isOpticalChannelInPort(port)) {
+                return Optional.empty();
+            }
+            NetconfSession session = groove.getNetconfSession(groove.did());
+            checkNotNull(session);
+            String filter = parsePort(groove, port, null, null);
+            StringBuilder rpcReq = new StringBuilder();
+            rpcReq.append(RPC_TAG_NETCONF_BASE)
+                    .append("<get>")
+                    .append("<filter type='subtree'>")
+                    .append(filter)
+                    .append("</filter>")
+                    .append("</get>")
+                    .append(RPC_CLOSE_TAG);
+            XMLConfiguration xconf = groove.executeRpc(session, rpcReq.toString());
+            try {
+                HierarchicalConfiguration config =
+                        xconf.configurationAt("data/components/component/optical-channel/config");
+                double power = Float.valueOf(config.getString("target-output-power")).doubleValue();
+                return Optional.of(power);
+            } catch (IllegalArgumentException e) {
+                return Optional.empty();
+            }
+        }
+
+        /**
+         * mirror method in the internal class.
+         *
+         * @param port      port
+         * @param component component
+         * @param power     target value
+         */
+        void setTargetPower(PortNumber port, Object component, double power) {
+            NetconfSession session = groove.getNetconfSession(groove.did());
+            checkNotNull(session);
+            String editConfig = parsePort(groove, port, null, power);
+            StringBuilder rpcReq = new StringBuilder();
+            rpcReq.append(RPC_TAG_NETCONF_BASE)
+                    .append("<edit-config>")
+                    .append("<target><running/></target>")
+                    .append("<config>")
+                    .append(editConfig)
+                    .append("</config>")
+                    .append("</edit-config>")
+                    .append(RPC_CLOSE_TAG);
+            XMLConfiguration xconf = groove.executeRpc(session, rpcReq.toString());
+            // The successful reply should be "<rpc-reply ...><ok /></rpc-reply>"
+            if (!xconf.getRoot().getChild(0).getName().equals("ok")) {
+                log.error("The <edit-config> operation to set target-output-power of Port({}:{}) is failed.",
+                          port.toString(), component.toString());
+            }
+        }
+
+        /**
+         * mirror method in the internal class.
+         *
+         * @param port      port
+         * @param component the component.
+         * @return current output power.
+         */
+        Optional<Double> currentPower(PortNumber port, Object component) {
+            if (!isOpticalChannelInPort(port)) {
+                return Optional.empty();
+            }
+
+            XMLConfiguration xconf = getOpticalChannelState(
+                    groove, port, "<output-power><instant/></output-power>");
+            try {
+                HierarchicalConfiguration config =
+                        xconf.configurationAt("data/components/component/optical-channel/state/output-power");
+                double currentPower = Float.valueOf(config.getString("instant")).doubleValue();
+                return Optional.of(currentPower);
+            } catch (IllegalArgumentException e) {
+                return Optional.empty();
+            }
+        }
+
+        /**
+         * mirror method in the internal class.
+         *
+         * @param port      port
+         * @param component the component
+         * @return current input power
+         */
+        Optional<Double> currentInputPower(PortNumber port, Object component) {
+            if (!isOpticalChannelInPort(port)) {
+                return Optional.empty();
+            }
+
+            XMLConfiguration xconf = getOpticalChannelState(
+                    groove, port, "<input-power><instant/></input-power>");
+            try {
+                HierarchicalConfiguration config =
+                        xconf.configurationAt("data/components/component/optical-channel/state/input-power");
+                double currentPower = Float.valueOf(config.getString("instant")).doubleValue();
+                return Optional.of(currentPower);
+            } catch (IllegalArgumentException e) {
+                return Optional.empty();
+            }
+        }
+
+        Optional<Range<Double>> getTargetPowerRange(PortNumber port, Object component) {
+            // Only line ports have power
+            if (isOpticalChannelInPort(port)) {
+                return Optional.of(Range.open(-20., 6.));
+            }
+            return Optional.empty();
+        }
+
+        boolean isOpticalChannelInPort(PortNumber port) {
+            DeviceService deviceService = DefaultServiceDirectory.getService(DeviceService.class);
+            DeviceId deviceId = groove.handler().data().deviceId();
+            return (deviceService.getPort(deviceId, port).type() == Port.Type.OCH);
+        }
+
+        Optional<Range<Double>> getInputPowerRange(PortNumber port, Object component) {
+            if (!isOpticalChannelInPort(port)) {
+                return Optional.empty();
+            }
+            XMLConfiguration xconf = getOpticalChannelState(groove, port, "<input-power-range/>");
+            try {
+                HierarchicalConfiguration config =
+                        xconf.configurationAt("data/components/component/optical-channel/state/input-power-range");
+                double inputMin = Float.valueOf(config.getString("min")).doubleValue();
+                double inputMax = Float.valueOf(config.getString("max")).doubleValue();
+                return Optional.of(Range.open(inputMin, inputMax));
+            } catch (IllegalArgumentException e) {
+                return Optional.empty();
+            }
+        }
+
+        List<PortNumber> getPorts(Object component) {
+            // FIXME
+            log.warn("Not Implemented Yet!");
+            return new ArrayList<PortNumber>();
+        }
+
+        /**
+         * Get filtered content under <optical-channel><state>.
+         *
+         * @param pc         power config instance
+         * @param port       the port number
+         * @param underState the filter condition
+         * @return RPC reply
+         */
+        private static XMLConfiguration getOpticalChannelState(GrooveOpenConfigDevicePowerConfig pc,
+                                                               PortNumber port, String underState) {
+            NetconfSession session = pc.getNetconfSession(pc.did());
+            checkNotNull(session);
+            String name = ocName(pc, port);
+            StringBuilder rpcReq = new StringBuilder(RPC_TAG_NETCONF_BASE);
+            rpcReq.append("<get><filter><components xmlns=\"http://openconfig.net/yang/platform\"><component>")
+                    .append("<name>").append(name).append("</name>")
+                    .append("<optical-channel xmlns=\"http://openconfig.net/yang/terminal-device\">")
+                    .append("<state>")
+                    .append(underState)
+                    .append("</state></optical-channel></component></components></filter></get>")
+                    .append(RPC_CLOSE_TAG);
+            XMLConfiguration xconf = pc.executeRpc(session, rpcReq.toString());
+            return xconf;
+        }
+
+
+        /**
+         * Extract component name from portNumber's annotations.
+         *
+         * @param pc         power config instance
+         * @param portNumber the port number
+         * @return the component name
+         */
+        private static String ocName(GrooveOpenConfigDevicePowerConfig pc, PortNumber portNumber) {
+            DeviceService deviceService = DefaultServiceDirectory.getService(DeviceService.class);
+            DeviceId deviceId = pc.handler().data().deviceId();
+            return deviceService.getPort(deviceId, portNumber).annotations().value("oc-name");
+        }
+
+
+        /**
+         * Parse filtering string from port and component.
+         *
+         * @param portNumber Port Number
+         * @param component  port component (optical-channel)
+         * @param power      power value set.
+         * @return filtering string in xml format
+         */
+        private static String parsePort(GrooveOpenConfigDevicePowerConfig pc, PortNumber portNumber,
+                                        Object component, Double power) {
+            if (component == null) {
+                String name = ocName(pc, portNumber);
+                StringBuilder sb = new StringBuilder("<components xmlns=\"http://openconfig.net/yang/platform\">");
+                sb.append("<component>").append("<name>").append(name).append("</name>");
+                if (power != null) {
+                    // This is an edit-config operation.
+                    sb.append("<optical-channel xmlns=\"http://openconfig.net/yang/terminal-device\">")
+                            .append("<config>")
+                            .append("<target-output-power>")
+                            .append(power)
+                            .append("</target-output-power>")
+                            .append("</config>")
+                            .append("</optical-channel>");
+                }
+                sb.append("</component>").append("</components>");
+                return sb.toString();
+            } else {
+                log.error("Cannot process the component {}.", component.getClass());
+                return null;
+            }
+        }
+    }
+}
diff --git a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigFlowRuleProgrammable.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigFlowRuleProgrammable.java
new file mode 100644
index 0000000..ea0d4c8
--- /dev/null
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigFlowRuleProgrammable.java
@@ -0,0 +1,400 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+
+ * This work was partially supported by EC H2020 project METRO-HAUL (761727).
+ */
+
+package org.onosproject.drivers.odtn;
+
+import com.google.common.collect.ImmutableList;
+import org.onosproject.drivers.odtn.impl.DeviceConnectionCache;
+import org.onosproject.drivers.odtn.impl.FlowRuleParser;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.net.flow.DefaultFlowEntry;
+import org.onosproject.net.flow.FlowEntry;
+import org.onosproject.net.flow.FlowRule;
+import org.onosproject.net.flow.FlowRuleProgrammable;
+import org.onosproject.netconf.DatastoreId;
+import org.onosproject.netconf.NetconfController;
+import org.onosproject.netconf.NetconfException;
+import org.onosproject.netconf.NetconfSession;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.xml.namespace.NamespaceContext;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.onosproject.odtn.behaviour.OdtnDeviceDescriptionDiscovery.OC_NAME;
+
+/**
+ * Implementation of FlowRuleProgrammable interface for
+ * OpenConfig terminal devices.
+ */
+public class GrooveOpenConfigFlowRuleProgrammable
+        extends AbstractHandlerBehaviour implements FlowRuleProgrammable {
+
+    private static final Logger log =
+            LoggerFactory.getLogger(GrooveOpenConfigFlowRuleProgrammable.class);
+
+    private static final String RPC_TAG_NETCONF_BASE =
+            "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">";
+
+    private static final String RPC_CLOSE_TAG = "</rpc>";
+
+
+    /**
+     * Apply the flow entries specified in the collection rules.
+     *
+     * @param rules A collection of Flow Rules to be applied
+     * @return The collection of added Flow Entries
+     */
+    @Override
+    public Collection<FlowRule> applyFlowRules(Collection<FlowRule> rules) {
+        NetconfSession session = getNetconfSession();
+        if (session == null) {
+            openConfigError("null session");
+            return ImmutableList.of();
+        }
+        List<FlowRule> added = new ArrayList<>();
+        for (FlowRule r : rules) {
+            try {
+                String connectionId = applyFlowRule(session, r);
+                getConnectionCache().add(did(), connectionId, r);
+                added.add(r);
+            } catch (Exception e) {
+                openConfigError("Error {}", e);
+                continue;
+            }
+        }
+        openConfigLog("applyFlowRules added {}", added.size());
+        return added;
+    }
+
+    /**
+     * Get the flow entries that are present on the device.
+     *
+     * @return A collection of Flow Entries
+     */
+    @Override
+    public Collection<FlowEntry> getFlowEntries() {
+        DeviceConnectionCache cache = getConnectionCache();
+        if (cache.get(did()) == null) {
+            return ImmutableList.of();
+        }
+
+        List<FlowEntry> entries = new ArrayList<>();
+        for (FlowRule r : cache.get(did())) {
+            entries.add(
+                    new DefaultFlowEntry(r, FlowEntry.FlowEntryState.ADDED, 0, 0, 0));
+        }
+        return entries;
+    }
+
+    /**
+     * Remove the specified flow rules.
+     *
+     * @param rules A collection of Flow Rules to be removed
+     * @return The collection of removed Flow Entries
+     */
+    @Override
+    public Collection<FlowRule> removeFlowRules(Collection<FlowRule> rules) {
+        NetconfSession session = getNetconfSession();
+        if (session == null) {
+            openConfigError("null session");
+            return ImmutableList.of();
+        }
+        List<FlowRule> removed = new ArrayList<>();
+        for (FlowRule r : rules) {
+            try {
+                String connectionId = removeFlowRule(session, r);
+                getConnectionCache().remove(did(), connectionId);
+                removed.add(r);
+            } catch (Exception e) {
+                openConfigError("Error {}", e);
+                continue;
+            }
+        }
+        openConfigLog("removedFlowRules removed {}", removed.size());
+        return removed;
+    }
+
+    private DeviceConnectionCache getConnectionCache() {
+        return DeviceConnectionCache.init();
+    }
+
+    // Context so XPath expressions are aware of XML namespaces
+    private static final NamespaceContext NS_CONTEXT = new NamespaceContext() {
+        @Override
+        public String getNamespaceURI(String prefix) {
+            if (prefix.equals("oc-platform-types")) {
+                return "http://openconfig.net/yang/platform-types";
+            }
+            if (prefix.equals("oc-opt-term")) {
+                return "http://openconfig.net/yang/terminal-device";
+            }
+            return null;
+        }
+
+        @Override
+        public Iterator getPrefixes(String val) {
+            return null;
+        }
+
+        @Override
+        public String getPrefix(String uri) {
+            return null;
+        }
+    };
+
+
+    /**
+     * Helper method to get the device id.
+     */
+    private DeviceId did() {
+        return data().deviceId();
+    }
+
+    /**
+     * Helper method to log from this class adding DeviceId.
+     */
+    private void openConfigLog(String format, Object... arguments) {
+        log.info("OPENCONFIG {}: " + format, did(), arguments);
+    }
+
+    /**
+     * Helper method to log an error from this class adding DeviceId.
+     */
+    private void openConfigError(String format, Object... arguments) {
+        log.error("OPENCONFIG {}: " + format, did(), arguments);
+    }
+
+
+    /**
+     * Helper method to get the Netconf Session.
+     */
+    private NetconfSession getNetconfSession() {
+        NetconfController controller =
+                checkNotNull(handler().get(NetconfController.class));
+        return controller.getNetconfDevice(did()).getSession();
+    }
+
+
+    /**
+     * Construct a String with a Netconf filtered get RPC Message.
+     *
+     * @param filter A valid XML tree with the filter to apply in the get
+     * @return a String containing the RPC XML Document
+     */
+    private String filteredGetBuilder(String filter) {
+        StringBuilder rpc = new StringBuilder(RPC_TAG_NETCONF_BASE);
+        rpc.append("<get>");
+        rpc.append("<filter type='subtree'>");
+        rpc.append(filter);
+        rpc.append("</filter>");
+        rpc.append("</get>");
+        rpc.append(RPC_CLOSE_TAG);
+        return rpc.toString();
+    }
+
+    /**
+     * Construct a get request to retrieve Components and their
+     * properties (for the ONOS port, index).
+     *
+     * @return The filt content to send to the device.
+     */
+    private String getComponents() {
+        StringBuilder filt = new StringBuilder();
+        filt.append("<components xmlns='http://openconfig.net/yang/platform'>");
+        filt.append(" <component>");
+        filt.append("  <name/>");
+        filt.append("  <properties/>");
+        filt.append(" </component>");
+        filt.append("</components>");
+        return filteredGetBuilder(filt.toString());
+    }
+
+
+    /**
+     * Construct a get request to retrieve Optical Channels and
+     * the line port they are using.
+     * <p>
+     * Thset ort.
+     *
+     * @return The filt content to send to the device.
+     */
+    private String getOpticalChannels() {
+        StringBuilder filt = new StringBuilder();
+        filt.append("<components xmlns='http://openconfig.net/yang/platform'>");
+        filt.append(" <component>");
+        filt.append("  <name/>");
+        filt.append("  <state/>");
+        filt.append("  <oc-opt-term:optical-channel xmlns:oc-opt-term"
+                            + " = 'http://openconfig.net/yang/terminal-device'>");
+        filt.append("    <oc-opt-term:config>");
+        filt.append("     <oc-opt-term:line-port/>");
+        filt.append("    </oc-opt-term:config >");
+        filt.append("  </oc-opt-term:optical-channel>");
+        filt.append(" </component>");
+        filt.append("</components>");
+        return filteredGetBuilder(filt.toString());
+    }
+
+
+    /**
+     * Get the OpenConfig component name for the OpticalChannel component.
+     *
+     * @param portNumber ONOS port number of the Line port ().
+     * @return the channel component name or null
+     */
+    private String getOpticalChannel(PortNumber portNumber) {
+        Port clientPort = handler().get(DeviceService.class).getPort(did(), portNumber);
+        return clientPort.annotations().value(OC_NAME);
+    }
+
+
+    private void setOpticalChannelFrequency(NetconfSession session, StringBuilder sb) throws NetconfException {
+
+        final boolean ok =
+                session.editConfig(DatastoreId.RUNNING, null, sb.toString());
+
+        if (!ok) {
+            throw new NetconfException("error writing channel frequency");
+        }
+    }
+
+
+    /**
+     * Apply the flowrule.
+     * <p>
+     * Note: only bidirectional are supported as of now,
+     * given OpenConfig note (below). In consequence, only the
+     * TX rules are actually mapped to netconf ops.
+     * <p>
+     * https://github.com/openconfig/public/blob/master/release/models
+     * /optical-transport/openconfig-terminal-device.yang
+     * <p>
+     * Directionality:
+     * To maintain simplicity in the model, the configuration is
+     * described from client-to-line direction.  The assumption is that
+     * equivalent reverse configuration is implicit, resulting in
+     * the same line-to-client configuration.
+     *
+     * @param session The Netconf session.
+     * @param r       Flow Rules to be applied.
+     * @return the optical channel + the frequency or just channel as identifier fo the config installed on the device
+     * @throws NetconfException if exchange goes wrong
+     */
+    protected String applyFlowRule(NetconfSession session, FlowRule r) throws NetconfException {
+        FlowRuleParser frp = new FlowRuleParser(r);
+        if (!frp.isReceiver()) {
+            String optChannel = getOpticalChannel(frp.getPortNumber());
+            final long frequency = (long) frp.getCentralFrequency().asMHz();
+            final String transceiver = optChannel.replace("OCH", "TRANSCEIVER");
+            final StringBuilder sb = new StringBuilder();
+            sb.append(
+                    "<components xmlns='http://openconfig.net/yang/platform'>"
+                            + "<component>"
+                            + "<name>" + optChannel + "</name>"
+                            + "<oc-opt-term:optical-channel "
+                            +
+                            "    xmlns:oc-opt-term='http://openconfig.net/yang/terminal-device'>"
+                            + "  <oc-opt-term:config>"
+                            + "   <oc-opt-term:frequency>" + frequency + "</oc-opt-term:frequency>"
+                            + "  </oc-opt-term:config>"
+                            + " </oc-opt-term:optical-channel>"
+                            + "</component>"
+                            + "<component>"
+                            + "  <name>" + transceiver + "</name>"
+                            + "   <transceiver xmlns='http://openconfig.net/yang/platform/transceiver'>"
+                            + "     <config>"
+                            + "       <enabled>true</enabled>"
+                            + "     </config>"
+                            + "   </transceiver>"
+                            + " </component>"
+                            + "</components>");
+
+            setOpticalChannelFrequency(session, sb);
+            return optChannel + ":" + frp.getCentralFrequency().asGHz();
+        }
+        return String.valueOf(frp.getCentralFrequency().asGHz());
+    }
+
+    protected String removeFlowRule(NetconfSession session, FlowRule r)
+            throws NetconfException {
+        FlowRuleParser frp = new FlowRuleParser(r);
+        if (!frp.isReceiver()) {
+            String optChannel = getOpticalChannel(frp.getPortNumber());
+            final String transceiver = optChannel.replace("OCH", "TRANSCEIVER");
+            final StringBuilder sb = new StringBuilder();
+            /*
+            TODO imcomplete solution: doesn't set frequency to zero; see below
+            sb.append(
+                    "<components xmlns='http://openconfig.net/yang/platform'>"
+                            + "<component>"
+                            + "  <name>" + transceiver + "</name>"
+                            + "   <transceiver xmlns='http://openconfig.net/yang/platform/transceiver'>"
+                            + "     <config>"
+                            + "       <enabled>false</enabled>"
+                            + "     </config>"
+                            + "   </transceiver>"
+                            + " </component>"
+                            + "</components>");
+
+             */
+
+            // NOTE: Disabling the laser via openconfig on Groove is not possible
+            //       and consequently the frequency can't be set to 0.
+            //       This is an error on mapping between native and openconfig model.
+
+            // Workaround: use legacy model
+            Pattern transceiverPattern = Pattern.compile(".*-[1]-[1-9][0-4]?-L[1-2]$"); // e.g. TRANSCEIVER-1-1-L1
+            Matcher lineMatch = transceiverPattern.matcher(transceiver);
+            lineMatch.find();
+            final String[] split = lineMatch.group(0).split("-");
+
+            sb.append("<ne xmlns=\"http://coriant.com/yang/os/ne\">" +
+                              "        <shelf>" +
+                              "          <shelf-id>" + split[1] + "</shelf-id>" +
+                              "          <slot>" +
+                              "            <slot-id>" + split[2] + "</slot-id>" +
+                              "            <card>" +
+                              "              <port>" +
+                              "                <port-id>" + split[3].replace("L", "") + "</port-id>" +
+                              "                <och-os>" +
+                              "                  <frequency>0</frequency>" +
+                              "                  <laser-enable>disabled</laser-enable>" +
+                              "                </och-os>" +
+                              "              </port>" +
+                              "            </card>" +
+                              "          </slot>" +
+                              "        </shelf>" +
+                              "      </ne>");
+
+            setOpticalChannelFrequency(session, sb);
+            return optChannel + ":" + frp.getCentralFrequency().asGHz();
+        }
+        return String.valueOf(frp.getCentralFrequency().asGHz());
+    }
+}
diff --git a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigLambdaQuery.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigLambdaQuery.java
new file mode 100644
index 0000000..71213bc
--- /dev/null
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/GrooveOpenConfigLambdaQuery.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+
+ * This work was partially supported by EC H2020 project METRO-HAUL (761727).
+ */
+
+package org.onosproject.drivers.odtn;
+
+import com.google.common.collect.ImmutableSet;
+import org.onlab.util.Frequency;
+import org.onlab.util.Spectrum;
+import org.onosproject.net.ChannelSpacing;
+import org.onosproject.net.GridType;
+import org.onosproject.net.OchSignal;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.LambdaQuery;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+
+import java.util.Set;
+import java.util.stream.IntStream;
+
+
+public class GrooveOpenConfigLambdaQuery extends AbstractHandlerBehaviour implements LambdaQuery {
+    private static final int LAMBDA_COUNT = 96;
+    private static final Frequency START_CENTER_FREQ = Frequency.ofGHz(191_350);
+
+    @Override
+    public Set<OchSignal> queryLambdas(PortNumber port) {
+
+        int startMultiplier = (int) (START_CENTER_FREQ.subtract(Spectrum.CENTER_FREQUENCY).asHz()
+                / Frequency.ofGHz(50).asHz());
+
+        return IntStream.range(0, LAMBDA_COUNT)
+                .mapToObj(x -> new OchSignal(GridType.DWDM,
+                                             ChannelSpacing.CHL_50GHZ,
+                                             startMultiplier + x,
+                                             4))
+                .collect(ImmutableSet.toImmutableSet());
+    }
+
+}
diff --git a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/InfineraOpenConfigDeviceDiscovery.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/InfineraOpenConfigDeviceDiscovery.java
index e137b92..5c7a0a7 100644
--- a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/InfineraOpenConfigDeviceDiscovery.java
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/InfineraOpenConfigDeviceDiscovery.java
@@ -18,15 +18,6 @@
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableList;
 import com.google.common.io.CharSource;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
 import org.apache.commons.configuration.ConfigurationException;
 import org.apache.commons.configuration.HierarchicalConfiguration;
 import org.apache.commons.configuration.XMLConfiguration;
@@ -49,6 +40,16 @@
 import org.onosproject.odtn.behaviour.OdtnDeviceDescriptionDiscovery;
 import org.slf4j.Logger;
 
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
 import static com.google.common.base.Preconditions.checkNotNull;
 import static org.slf4j.LoggerFactory.getLogger;
 
@@ -64,8 +65,9 @@
     @Override
     public DeviceDescription discoverDeviceDetails() {
         return new DefaultDeviceDescription(handler().data().deviceId().uri(),
-                Device.Type.TERMINAL_DEVICE, "Infinera", "XT-3300",
-                "unknown", "unknown", new ChassisId());
+                                            Device.Type.TERMINAL_DEVICE, "Infinera",
+                                            "XT-3300", "unknown",
+                                            "unknown", new ChassisId());
     }
 
     @Override
@@ -132,8 +134,8 @@
             return toPortDescriptionInternal(component);
         } catch (Exception e) {
             log.error("Unexpected exception parsing component {} on {}",
-                    component.getString("name"),
-                    data().deviceId(), e);
+                      component.getString("name"),
+                      data().deviceId(), e);
             return null;
         }
     }