cassini Modulation Driver Impl | ONOS-7979

Change-Id: Iba45f3e41fc39e63c7dc96acf5d2da248dc6bf68
diff --git a/core/api/src/main/java/org/onosproject/net/ModulationScheme.java b/core/api/src/main/java/org/onosproject/net/ModulationScheme.java
new file mode 100644
index 0000000..fe54c44
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/net/ModulationScheme.java
@@ -0,0 +1,26 @@
+/*
+ * 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 is contributed by Sterlite Technologies
+ */
+package org.onosproject.net;
+
+public enum ModulationScheme {
+
+    DP_QPSK,
+    DP_8QAM,
+    DP_16QAM
+
+}
diff --git a/core/api/src/main/java/org/onosproject/net/behaviour/ModulationConfig.java b/core/api/src/main/java/org/onosproject/net/behaviour/ModulationConfig.java
new file mode 100644
index 0000000..8aa4dbe
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/net/behaviour/ModulationConfig.java
@@ -0,0 +1,57 @@
+/*
+ * 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 is contributed by Sterlite Technologies
+ */
+package org.onosproject.net.behaviour;
+
+import com.google.common.annotations.Beta;
+import org.onosproject.net.ModulationScheme;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.driver.HandlerBehaviour;
+
+import java.util.Optional;
+
+/*
+ *
+ * Modulation operations act on a network port and a component thereof.
+ * Supported components are either the full directed port ({@link org.onosproject.net.Direction})
+ * or a wavelength on a port ({@link org.onosproject.net.OchSignal}).
+ *
+ * Modulation are dependent on channel spacing and bitrate
+ */
+@Beta
+public interface ModulationConfig<T> extends HandlerBehaviour {
+
+    /**
+     * Get the target Modulation Scheme on the component.
+     *
+     * @param port the port
+     * @param component the port component
+     * @return ModulationScheme as per bitRate value
+     */
+    Optional<ModulationScheme> getModulationScheme(PortNumber port, T component);
+
+    /**
+     * Set the target Modulation Scheme on the component.
+     *
+     * @param port the port
+     * @param component the port component
+     * @param bitRate bit rate in bps
+     */
+    void setModulationScheme(PortNumber port, T component, long bitRate);
+
+}
+
diff --git a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/CassiniModulationConfig.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/CassiniModulationConfig.java
new file mode 100644
index 0000000..163bfb5
--- /dev/null
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/CassiniModulationConfig.java
@@ -0,0 +1,435 @@
+/*
+ * 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 is contributed by Sterlite Technologies
+ */
+
+package org.onosproject.drivers.odtn;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.configuration.HierarchicalConfiguration;
+import org.apache.commons.configuration.XMLConfiguration;
+import org.onlab.osgi.DefaultServiceDirectory;
+import org.onosproject.drivers.odtn.util.NetconfSessionUtility;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Direction;
+import org.onosproject.net.ModulationScheme;
+import org.onosproject.net.OchSignal;
+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.NetconfController;
+import org.onosproject.netconf.NetconfSession;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Optional;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/*
+ * Driver Implementation of the ModulationConfig for OpenConfig terminal devices.
+ */
+public class CassiniModulationConfig<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(CassiniModulationConfig.class);
+
+    private ComponentType state = ComponentType.DIRECTION;
+
+    private static final double OSNR_THRESHOLD_VALUE = 13.0;
+
+
+    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;
+        }
+    }
+
+    private NetconfController getController() {
+        return handler().get(NetconfController.class);
+    }
+
+    /*
+     *
+     * Get the deviceId for which the methods apply.
+     *
+     * @return The deviceId as contained in the handler data
+     */
+
+
+    private DeviceId getDeviceId() {
+        return handler().data().deviceId();
+    }
+
+
+    /**
+     * 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) {
+        checkType(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) {
+        checkType(component);
+        state.setModulationScheme(port, component, bitRate);
+    }
+
+    /*
+     *
+     * Set the ComponentType to invoke proper methods for different template T.
+     * @param component the component.
+     */
+    void checkType(Object component) {
+        String clsName = component.getClass().getName();
+
+        if (component instanceof Direction) {
+            state = CassiniModulationConfig.ComponentType.DIRECTION;
+        } else if (component instanceof OchSignal) {
+            state = CassiniModulationConfig.ComponentType.OCHSIGNAL;
+        } else {
+            log.error("Cannot parse the component type {}.", clsName);
+        }
+
+
+        state.cassini = this;
+    }
+
+    /*
+     *
+     * 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) {
+                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);
+            }
+        };
+
+
+        CassiniModulationConfig cassini;
+
+        /*
+         * mirror method in the internal class.
+         * @param port port
+         * @param component component
+         * @return target modulation
+         */
+        Optional<ModulationScheme> getModulationScheme(PortNumber port, Object component) {
+            NetconfSession session = NetconfSessionUtility
+                    .getNetconfSession(cassini.getDeviceId(), cassini.getController());
+            checkNotNull(session);
+            String filter = createModulationFilter(cassini, port);
+            StringBuilder rpcReq = new StringBuilder();
+            rpcReq.append(RPC_TAG_NETCONF_BASE)
+                    .append("<get>")
+                    .append("<filter>")
+                    .append(filter)
+                    .append("</filter>")
+                    .append("</get>")
+                    .append(RPC_CLOSE_TAG);
+            log.info("RPC Call for Getting Modulation : \n {}", rpcReq.toString());
+            XMLConfiguration xconf = NetconfSessionUtility.executeRpc(session, rpcReq.toString());
+            try {
+                HierarchicalConfiguration config =
+                        xconf.configurationAt("data/components/component/optical-channel/config");
+
+                String modulationScheme = String.valueOf(config.getString("modulation"));
+
+                return Optional.of(ModulationScheme.valueOf(modulationScheme));
+            } catch (IllegalArgumentException 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;
+            String editConfig = null;
+            double osnr = 0.0;
+            boolean rpcResponse = false;
+            boolean receiver = false;
+
+            // TODO OSNR is valid only for receiver so need to modify
+            /*if(component.toString().equals(Direction.INGRESS.toString())){
+                receiver=true;
+            }*/
+
+            //check if bitrate is less than equal to 100 Gig
+            if (bitRate <= BitRate.GBPS_100.value) {
+                modulation = ModulationScheme.DP_QPSK;
+                editConfig = modulationEditConfig(cassini, port, component, bitRate, modulation.name());
+                //setting the modulation by calling rpc
+                rpcResponse = setModulationRpc(port, component, editConfig);
+                if (rpcResponse) {
+                    // TODO OSNR is valid only for receiver so need to modify
+                    osnr = fetchDeviceSnr(cassini, port);
+                    if (osnr <= OSNR_THRESHOLD_VALUE) {
+                        log.error("Channel not possible for this OSNR Value : {}", osnr);
+                    }
+                }
+            } else { // check if bitrate is greater than 100 Gig
+                modulation = ModulationScheme.DP_16QAM;
+                editConfig = modulationEditConfig(cassini, port, component, bitRate, modulation.name());
+                //setting the modulation by calling rpc
+                rpcResponse = setModulationRpc(port, component, editConfig);
+                if (rpcResponse) {
+                    //TODO OSNR is valid only for receiver so need to modify
+                    osnr = fetchDeviceSnr(cassini, port);
+                    if (osnr <= OSNR_THRESHOLD_VALUE) {
+                        modulation = ModulationScheme.DP_8QAM;
+                        editConfig = modulationEditConfig(cassini, port, component, bitRate, modulation.name());
+                        //setting the modulation by calling rpc
+                        rpcResponse = setModulationRpc(port, component, editConfig);
+                        if (rpcResponse) {
+                            // TODO OSNR is valid only for receiver so need to modify
+                            osnr = fetchDeviceSnr(cassini, port);
+                            if (osnr <= OSNR_THRESHOLD_VALUE) {
+                                log.warn("Channel not possible for this OSNR Value : {}." +
+                                        " Please reduce the channel bitrate.", osnr);
+                            }
+                        }
+                    }
+                }
+            }
+
+
+        }
+
+
+        /*
+         * 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
+         */
+
+        //RPC call for OSNR still not finalised, need to update Rpc once validated
+        private static XMLConfiguration getTerminalDeviceSnr(CassiniModulationConfig config, PortNumber port) {
+            NetconfSession session = NetconfSessionUtility
+                    .getNetconfSession(config.getDeviceId(), config.getController());
+            checkNotNull(session);
+            String name = ocName(config, port);
+            StringBuilder rpcReq = new StringBuilder(RPC_TAG_NETCONF_BASE);
+            rpcReq.append("<get><filter>")
+                    .append("<osnr xmlns=\"http://openconfig.net/yang/terminal-device\">")
+                    .append("<instant/>")
+                    .append("</osnr></filter></get>")
+                    .append(RPC_CLOSE_TAG);
+            log.info("RPC Call for Fetching OSNR :\n\n {}", rpcReq.toString());
+            XMLConfiguration xconf = NetconfSessionUtility.executeRpc(session, rpcReq.toString());
+            return xconf;
+        }
+
+        private static String createModulationFilter(CassiniModulationConfig 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("<optical-channel xmlns=\"http://openconfig.net/yang/terminal-device\">");
+            sb.append("<config><modulation/></config>");
+            sb.append("</optical-channel>");
+            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(CassiniModulationConfig pc, PortNumber portNumber) {
+            DeviceService deviceService = DefaultServiceDirectory.getService(DeviceService.class);
+            DeviceId deviceId = pc.handler().data().deviceId();
+            return deviceService.getPort(deviceId, portNumber).annotations().value("oc-name");
+        }
+
+        private static String channelSpacing(CassiniModulationConfig modulationConfig, PortNumber portNumber) {
+            DeviceService deviceService = DefaultServiceDirectory.getService(DeviceService.class);
+            DeviceId deviceId = modulationConfig.handler().data().deviceId();
+            String lambda = deviceService.getPort(deviceId, portNumber).annotations().value("lambda");
+
+            ObjectMapper mapper = new ObjectMapper();
+            String channelSpacing = "";
+            try {
+                JsonNode actualObj = mapper.readTree(lambda);
+                JsonNode csNode = actualObj.get("channelSpacing");
+                channelSpacing = csNode.asText();
+                log.info("Channel_Spacing : " + channelSpacing);
+
+            } catch (IOException e) {
+                log.error("Error while parsing Json");
+            }
+            return channelSpacing;
+
+        }
+
+        private double fetchDeviceSnr(CassiniModulationConfig modulationConfig, PortNumber portNumber) {
+            double osnr = 0.0;
+            XMLConfiguration xconf = getTerminalDeviceSnr(cassini, portNumber);
+            if (xconf == null) {
+                return osnr;
+            }
+            try {
+                HierarchicalConfiguration config =
+                        xconf.configurationAt("data/components/component/optical-channel/state/osnr");
+                osnr = Float.valueOf(config.getString("snr")).doubleValue();
+                return osnr;
+            } catch (IllegalArgumentException e) {
+                return osnr;
+            }
+        }
+        /*
+         *
+         * 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(CassiniModulationConfig modulationConfig, PortNumber portNumber,
+                                            Object component, long bitRate, String modulation) {
+            if (component != null) {
+                String portName = ocName(modulationConfig, portNumber);
+                //String channelSpacing = channelSpacing(modulationConfig,portNumber);
+                //ChannelSpacing cs= ChannelSpacing.valueOf(channelSpacing);
+                //double csValue= cs.frequency().asGHz();
+
+                StringBuilder sb = new StringBuilder("<components xmlns=\"http://openconfig.net/yang/platform\">");
+                sb.append("<component>").append("<name>").append(portName).append("</name>");
+                if (modulation != null) {
+                    // This is an edit-config operation.
+                    sb.append("<optical-channel xmlns=\"http://openconfig.net/yang/terminal-device\">")
+                            .append("<config>")
+                            .append("<modulation>")
+                            .append(modulation)
+                            .append("</modulation>")
+                            .append("</config>")
+                            .append("</optical-channel>");
+                }
+                sb.append("</component>").append("</components>");
+                return sb.toString();
+            } else {
+                log.error("Cannot process the component {}.", component.getClass());
+                return null;
+            }
+        }
+
+        private boolean setModulationRpc(PortNumber port, Object component, String editConfig) {
+            NetconfSession session = NetconfSessionUtility
+                    .getNetconfSession(cassini.getDeviceId(), cassini.getController());
+            checkNotNull(session);
+            boolean response = true;
+            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);
+            log.info("RPC call for Setting Modulation : {}", rpcReq.toString());
+            XMLConfiguration xconf = NetconfSessionUtility.executeRpc(session, rpcReq.toString());
+
+            // The successful reply should be "<rpc-reply ...><ok /></rpc-reply>"
+            if (!xconf.getRoot().getChild(0).getName().equals("ok")) {
+                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/util/NetconfSessionUtility.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/util/NetconfSessionUtility.java
new file mode 100644
index 0000000..786c999
--- /dev/null
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/util/NetconfSessionUtility.java
@@ -0,0 +1,85 @@
+/*
+ * 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 is contributed by Sterlite Technologies
+ */
+
+package org.onosproject.drivers.odtn.util;
+
+import org.apache.commons.configuration.XMLConfiguration;
+import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
+import org.onosproject.drivers.utilities.XmlConfigParser;
+import org.onosproject.net.DeviceId;
+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.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+
+public final class NetconfSessionUtility {
+
+    private static final Logger log = LoggerFactory.getLogger(NetconfSessionUtility.class);
+
+    private NetconfSessionUtility() {
+    }
+
+    /**
+     * Returns the NetconfSession with the device for which the method was called.
+     *
+     * @param deviceId   device identifier
+     * @param controller NetconfController
+     * @return The netconf session or null
+     */
+    public static NetconfSession getNetconfSession(DeviceId deviceId,
+                                                   NetconfController controller) {
+        log.info("Inside getNetconfSession () method for device : {}", deviceId);
+        NetconfDevice ncdev = controller.getDevicesMap().get(deviceId);
+        if (ncdev == null) {
+            log.trace("No netconf device, returning null session");
+            return null;
+        }
+        return ncdev.getSession();
+    }
+
+    /**
+     * Execute RPC request.
+     *
+     * @param session Netconf session
+     * @param message Netconf message in XML format
+     * @return XMLConfiguration object
+     */
+
+    public static 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;
+    }
+
+}
diff --git a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/util/package-info.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/util/package-info.java
new file mode 100644
index 0000000..7cdbe9f
--- /dev/null
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/util/package-info.java
@@ -0,0 +1,21 @@
+/*
+ * 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 is contributed by Sterlite Technologies
+ */
+/**
+ * Package for Utility classes to be used by odtn-driver.
+ */
+package org.onosproject.drivers.odtn.util;
\ No newline at end of file
diff --git a/drivers/odtn-driver/src/main/resources/odtn-drivers.xml b/drivers/odtn-driver/src/main/resources/odtn-drivers.xml
index ba102a7..f23cdef 100644
--- a/drivers/odtn-driver/src/main/resources/odtn-drivers.xml
+++ b/drivers/odtn-driver/src/main/resources/odtn-drivers.xml
@@ -77,6 +77,8 @@
                    impl="org.onosproject.drivers.odtn.CassiniFlowRuleProgrammable"/>
         <behaviour api="org.onosproject.net.behaviour.PowerConfig"
                    impl="org.onosproject.drivers.odtn.CassiniTerminalDevicePowerConfig"/>
+        <behaviour api="org.onosproject.net.behaviour.ModulationConfig"
+                   impl="org.onosproject.drivers.odtn.CassiniModulationConfig"/>
     </driver>
     <driver name="nokia-1830" manufacturer="nokia" hwVersion="1830" swVersion="R10.1.1">
         <behaviour api="org.onosproject.net.device.DeviceDescriptionDiscovery"
diff --git a/models/openconfig-odtn/src/main/yang/openconfig-terminal-device.yang b/models/openconfig-odtn/src/main/yang/openconfig-terminal-device.yang
index 0319a6c..6cf9254 100644
--- a/models/openconfig-odtn/src/main/yang/openconfig-terminal-device.yang
+++ b/models/openconfig-odtn/src/main/yang/openconfig-terminal-device.yang
@@ -295,6 +295,18 @@
 
       uses oc-types:avg-min-max-instant-stats-precision2-dB;
     }
+    container osnr {
+          description
+            "Optical signal to noise ratio. Baud rate
+            normalized signal to noise ratio based on
+            error vector magnitude in dB with two decimal
+            precision. Values include the instantaneous, average,
+            minimum, and maximum statistics. If avg/min/max
+            statistics are not supported, the target is expected
+            to just supply the instant value";
+
+          uses oc-types:avg-min-max-instant-stats-precision2-dB;
+        }
   }
 
   grouping terminal-otn-protocol-state {
@@ -854,6 +866,11 @@
       description
         "Frequency of the optical channel, expressed in MHz";
     }
+    leaf modulation {
+          type oc-opt-types:modulation-format;
+          description
+            "Modulation of the optical channel, expressed in dB";
+     }
 
     leaf target-output-power {
       type decimal64 {
diff --git a/models/openconfig-odtn/src/main/yang/openconfig-transport-types.yang b/models/openconfig-odtn/src/main/yang/openconfig-transport-types.yang
index 247b973..bc82766 100644
--- a/models/openconfig-odtn/src/main/yang/openconfig-transport-types.yang
+++ b/models/openconfig-odtn/src/main/yang/openconfig-transport-types.yang
@@ -50,6 +50,64 @@
     description
       "Type for optical spectrum frequency values";
   }
+typedef modulation-format {
+        type enumeration {
+          enum UNKNOWN {
+            description
+              "quadrature phase-shift keying";
+          }
+          enum BPSK {
+            description
+              "quadrature phase-shift keying";
+          }
+          enum DP_BPSK {
+            description
+              "quadrature phase-shift keying";
+          }
+          enum QPSK {
+            description
+              "quadrature phase-shift keying";
+          }
+          enum DP_QPSK {
+            description
+              "quadrature phase-shift keying";
+          }
+          enum 8QAM {
+            description
+              "quadrature amplitude modulation 8";
+          }
+          enum DP_8QAM {
+            description
+              "quadrature amplitude modulation 8";
+          }
+          enum 16QAM {
+            description
+              "quadrature amplitude modulation 16";
+          }
+          enum DP_16QAM {
+            description
+              "quadrature amplitude modulation 16";
+          }
+          enum 32QAM {
+            description
+              "quadrature amplitude modulation 16";
+          }
+          enum DP_32QAM {
+            description
+              "quadrature amplitude modulation 16";
+          }
+          enum 64QAM {
+            description
+              "quadrature amplitude modulation 16";
+          }
+          enum DP_64QAM {
+            description
+              "quadrature amplitude modulation 16";
+          }
+        }
+        description
+          "Modulation format";
+      }
 
   typedef admin-state-type {
     type enumeration {
diff --git a/web/api/src/main/java/org/onosproject/rest/resources/CoreWebApplication.java b/web/api/src/main/java/org/onosproject/rest/resources/CoreWebApplication.java
index 906e27c..3803f0d 100644
--- a/web/api/src/main/java/org/onosproject/rest/resources/CoreWebApplication.java
+++ b/web/api/src/main/java/org/onosproject/rest/resources/CoreWebApplication.java
@@ -55,7 +55,8 @@
                 UiPreferencesWebResource.class,
                 SystemInfoWebResource.class,
                 PacketProcessorsWebResource.class,
-                AuditFilter.class
+                AuditFilter.class,
+                ModulationWebResource.class
         );
     }
 }
diff --git a/web/api/src/main/java/org/onosproject/rest/resources/ModulationWebResource.java b/web/api/src/main/java/org/onosproject/rest/resources/ModulationWebResource.java
new file mode 100644
index 0000000..4c4829f
--- /dev/null
+++ b/web/api/src/main/java/org/onosproject/rest/resources/ModulationWebResource.java
@@ -0,0 +1,278 @@
+/*
+ * 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 is contributed by Sterlite Technologies
+ */
+package org.onosproject.rest.resources;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onosproject.net.Device;
+import org.onosproject.net.Direction;
+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.rest.AbstractWebResource;
+import org.slf4j.Logger;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Iterator;
+import java.util.Map;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.onlab.util.Tools.readTreeFromStream;
+import static org.onosproject.net.DeviceId.deviceId;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Query and program flow rules.
+ */
+
+@Path("modulation")
+public class ModulationWebResource extends AbstractWebResource {
+
+    private final Logger log = getLogger(getClass());
+    @Context
+    private UriInfo uriInfo;
+
+    private static final String DEVICE_NOT_FOUND = "Device is not found";
+    private static final String APP_ID_NOT_FOUND = "Application Id is not found";
+    private static final String MODULATIONCONFIG_UNSUPPORTED = "Modulation Config is not supported";
+
+    private static final String DEVICES = "modulationConfigDevices";
+    private static final String DEVICE_ID = "deviceId";
+    private static final String DEVICE_IDS = "modulationConfigDeviceIds";
+    private static final String MODULATIONCONFIG_SUPPORTED = "modulationConfigSupported";
+    private static final String TARGET_MODULATION = "targetModulation";
+    private static final String TARGET_BITRATE = "targetBitRate";
+    private static final String JSON_INVALID = "Invalid json input";
+
+    private final ObjectMapper mapper = new ObjectMapper();
+
+    /**
+     * Gets all modulation config devices.
+     * Returns array of all discovered modulation config devices.
+     *
+     * @return 200 OK with a collection of devices supporting modulation
+     */
+    @GET
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getModulationSupportedDevices() {
+        ObjectNode root = mapper().createObjectNode();
+        ArrayNode deviceIdsNode = root.putArray(DEVICE_IDS);
+
+        Iterable<Device> devices = get(DeviceService.class).getDevices();
+        if (devices != null) {
+            for (Device d : devices) {
+                if (getModulationConfig(d.id().toString()) != null) {
+                    deviceIdsNode.add(d.id().toString());
+                }
+            }
+        }
+
+        return ok(root).build();
+    }
+
+    private ModulationConfig<Object> getModulationConfig(String id) {
+        Device device = get(DeviceService.class).getDevice(deviceId(id));
+        if (device == null) {
+            throw new IllegalArgumentException(DEVICE_NOT_FOUND);
+        }
+        if (device.is(ModulationConfig.class)) {
+            return device.as(ModulationConfig.class);
+        }
+        return null;
+    }
+
+
+    /**
+     * Gets the details of a modulation config device.
+     * Returns the details of the specified modulation config device.
+     *
+     * @param id device identifier
+     * @return 200 OK with a device
+     */
+    @GET
+    @Path("{id}")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response isModulationSupported(@PathParam("id") String id) {
+        ObjectNode result = mapper.createObjectNode();
+        result.put(MODULATIONCONFIG_SUPPORTED, (getModulationConfig(id) != null) ? true : false);
+        return ok(result).build();
+    }
+
+
+    /**
+     * Returns the supported modulation scheme for specified ports of device.
+     * <p>
+     * ModulationConfigDeviceGetPorts
+     *
+     * @param id     device identifier
+     * @param portId line port identifier
+     * @return 200 OK with a modulationGetResponse.
+     */
+    @GET
+    @Path("{id}/port")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getConfigurablePortModulation(@PathParam("id") String id,
+                                                  @QueryParam("port_id") String portId) {
+        ModulationConfig<Object> modulationConfig = getModulationConfig(id);
+        if (modulationConfig == null) {
+            throw new IllegalArgumentException(MODULATIONCONFIG_UNSUPPORTED);
+        }
+
+        ObjectNode result = encode(id, modulationConfig, portId);
+        return ok(result).build();
+    }
+
+
+    /**
+     * Applies the target modulation for the specified device.
+     *
+     * @param stream JSON representation of device, port, component and target
+     *               bitrate info
+     * @return status of the request - CREATED if the JSON is correct,
+     * BAD_REQUEST if the JSON is invalid
+     * ModulationConfigPut
+     */
+    @PUT
+    @Consumes(MediaType.APPLICATION_JSON)
+    public Response setModulationScheme(InputStream stream) {
+        try {
+            ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
+            decode(jsonTree);
+            return Response.ok().build();
+        } catch (IOException e) {
+            throw new IllegalArgumentException(e);
+        }
+    }
+
+    private ObjectNode encode(String deviceId, ModulationConfig<Object> modulationConfig, String portId) {
+        checkNotNull(modulationConfig, "ModulationConfig cannot be null");
+
+        Direction component = Direction.ALL;
+        PortNumber port = PortNumber.portNumber(portId);
+        log.debug("Port Details for port_id : {} is \n {} ", portId, port);
+
+        ModulationScheme modulation = modulationConfig.getModulationScheme(port, component).get();
+        log.debug("Modulation  fetched from driver : " + modulation.name());
+
+        ObjectNode responseNode = mapper.createObjectNode();
+        responseNode.put("deviceId", deviceId);
+        responseNode.put("portId", portId);
+        responseNode.put("modulation", modulation.name());
+
+        return responseNode;
+    }
+
+    public void decode(ObjectNode json) {
+        if (json == null || !json.isObject()) {
+            throw new IllegalArgumentException(JSON_INVALID);
+        }
+
+        JsonNode devicesNode = json.get(DEVICES);
+        if (!devicesNode.isObject()) {
+            throw new IllegalArgumentException(JSON_INVALID);
+        }
+
+        Iterator<Map.Entry<String, JsonNode>> deviceEntries = devicesNode.fields();
+        while (deviceEntries.hasNext()) {
+            Map.Entry<String, JsonNode> deviceEntryNext = deviceEntries.next();
+            String deviceId = deviceEntryNext.getKey();
+            ModulationConfig<Object> modulationConfig = getModulationConfig(deviceId);
+            JsonNode portsNode = deviceEntryNext.getValue();
+            if (!portsNode.isObject()) {
+                throw new IllegalArgumentException(JSON_INVALID);
+            }
+
+            Iterator<Map.Entry<String, JsonNode>> portEntries = portsNode.fields();
+            while (portEntries.hasNext()) {
+                Map.Entry<String, JsonNode> portEntryNext = portEntries.next();
+                PortNumber portNumber = PortNumber.portNumber(portEntryNext.getKey());
+                JsonNode componentsNode = portEntryNext.getValue();
+                Iterator<Map.Entry<String, JsonNode>> componentEntries = componentsNode.fields();
+                while (componentEntries.hasNext()) {
+                    Direction direction = null;
+                    Map.Entry<String, JsonNode> componentEntryNext = componentEntries.next();
+                    try {
+                        direction = Direction.valueOf(componentEntryNext.getKey().toUpperCase());
+                    } catch (IllegalArgumentException e) {
+                        // TODO: Handle other components
+                    }
+
+                    JsonNode bitRateNode = componentEntryNext.getValue();
+                    if (!bitRateNode.isObject()) {
+                        throw new IllegalArgumentException(JSON_INVALID);
+                    }
+                    Long targetBitRate = bitRateNode.get(TARGET_BITRATE).asLong();
+                    if (direction != null) {
+                        modulationConfig.setModulationScheme(portNumber, direction, targetBitRate);
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * Sets the modulation for specified device and port.
+     * Returns the details of the specified modulation config device ports.
+     * <p>
+     * ModulationConfigDeviceGetPorts
+     *
+     * @param id        device identifier
+     * @param direction port direction(transmitter or receiver port)
+     * @param portId    port channel
+     * @param bitrate   port bitrate
+     * @return status of the request - CREATED if the JSON is correct,
+     * BAD_REQUEST if the JSON is invalid
+     */
+    @PUT
+    @Path("set-modulation/{id}")
+    @Consumes(MediaType.APPLICATION_JSON)
+    public Response setPortModulation(@PathParam("id") String id,
+                                      @QueryParam("port_id") String portId,
+                                      @QueryParam("direction") String direction,
+                                      @QueryParam("bitrate") long bitrate) {
+
+        ModulationConfig<Object> modulationConfig = getModulationConfig(id);
+        PortNumber portNumber = PortNumber.portNumber(portId);
+        log.info("Port Details for port_id : {} is \n {} ", portId, portNumber);
+        if (direction != null) {
+            Direction component = Direction.valueOf(direction.toUpperCase());
+            modulationConfig.setModulationScheme(portNumber, component, bitrate);
+        } else {
+            log.error("Direction cannot be null");
+            return Response.status(400, "Direction cannot be Null").build();
+        }
+        return Response.ok().build();
+    }
+
+
+}