Exemple #1
0
        private static int DoSnmp(Snmp snmp, SnmpTarget target, Pdu pdu,
                                  OperType operType, ref TableReader.GetTableOptions tableOptions,
                                  uint repeat, bool asyncSync, bool debug)
        {
            int ncalls = 0;

            for (uint i = 0; i < repeat; i++)
            {
                using (IMemoryManager mgr = MemoryManager.GetMemoryManager())
                {
                    bool show = (i % 1000) == 0;
                    if (show || debug)
                    {
                        PrintPdu(Console.Out, "Sending PDU to target " + target, pdu, debug);
                    }

                    Pdu resPdu = DoSnmp(snmp, target, pdu,
                                        operType, ref tableOptions,
                                        asyncSync, show, debug, ref ncalls);

                    if ((show || debug) && resPdu != null)
                    {
                        PrintPdu(Console.Out, "Received PDU:", resPdu, debug);
                    }
                    if (debug)
                    {
                        Console.WriteLine("Removing " + mgr.Count + " objects");
                    }
                }
            }
            return(ncalls);
        }
Exemple #2
0
        private static GetTableState PrepareGetTable(
            Snmp snmp, Pdu pdu, SnmpTarget target,
            Oid[] columnOids, Oid startRowIndex, Oid endRowIndex,
            int maxRows, int rowsPerQuery, AsyncCallback callback, object callbackData, bool sync)
        {
            if (!(pdu.Type == PduType.GetNext || pdu.Type == PduType.GetBulk))
            {
                throw new ArgumentException("Invalid pdu type: " + pdu.Type, "pdu");
            }

            if (columnOids.Length == 0)
            {
                throw new ArgumentException("Empty column oid table", "columnOids");
            }

            if (maxRows <= 0)
            {
                maxRows = int.MaxValue;
            }

            columnOids = (Oid[])columnOids.Clone();
            Vb[] vbs = CreateNullVbs(columnOids, startRowIndex);
            pdu = pdu.Clone(vbs);
            pdu.NonRepeaters = 0;

            return(new GetTableState(snmp, pdu, target, columnOids,
                                     endRowIndex, maxRows, rowsPerQuery, vbs,
                                     callback, callbackData, sync));
        }
Exemple #3
0
 /// <summary>
 /// Starts an asynchronous SNMP table retrieval operation.
 /// </summary>
 /// <param name="snmp">The SNMP session object to use.</param>
 /// <param name="pdu">The PDU object used to convey the request type
 /// and some security parameters (variable bindings are ignored; may
 /// be an empty array).</param>
 /// <param name="target">The SNMP target.</param>
 /// <param name="columnOids">The OIDs of table columns to retrieve. The
 /// columns should share table indexes  (e.g., be a part of the same or
 /// AUGMENTed table).</param>
 /// <param name="callback">Callback method to invoke when a table is read
 /// or <b>null</b>.</param>
 /// <param name="callbackData">User state.</param>
 /// <returns><see cref="IAsyncResult"/> object.</returns>
 /// <remarks>
 /// This method starts asynchronous table retrieval for the specified set
 /// of columns. A typical example includes the retrieval of a whole table.
 /// In order to complete the operation and free related resources,
 /// <see cref="EndGetTable"/> must be later called, usually, in the callback
 /// method specified by <b>callback</b> parameter.
 /// </remarks>
 public static IAsyncResult BeginGetTable(Snmp snmp, Pdu pdu, SnmpTarget target,
                                          Oid[] columnOids,
                                          AsyncCallback callback, object callbackData)
 {
     return(BeginGetTable(snmp, pdu, target, columnOids,
                          null, 0, callback, callbackData));
 }
        private async Task <MonitoredPort> EnsureMonitoredPort(SnmpTarget target, int portNumber)
        {
            var existingPort = await MonitoredPorts.Query()
                               .FirstOrDefaultAsync(port => port.PortNumber == portNumber && port.SnmpIpAddress == target.IpAddress);

            if (existingPort == null)
            {
                var newPort = new MonitoredPort
                {
                    AllInOctets           = 0,
                    AllOutOctets          = 0,
                    SnmpIpAddress         = target.IpAddress,
                    PortNumber            = portNumber,
                    FirstTimeScanned      = DateTime.Now,
                    LastInOctets          = 0,
                    LastOutOctets         = 0,
                    ExcludeFromStatistics = false,
                    Comment = null
                };

                newPort = MonitoredPorts.Insert(newPort);

                await Context.SaveAsync();

                return(newPort);
            }

            return(existingPort);
        }
Exemple #5
0
 /// <summary>
 /// Retrieves an SNMP table from an agent.
 /// </summary>
 /// <param name="snmp">The SNMP session object to use.</param>
 /// <param name="pdu">The PDU object used to convey the request type
 /// and some security parameters (variable bindings are ignored; may
 /// be an empty array).</param>
 /// <param name="target">The SNMP target.</param>
 /// <param name="columnOids">The OIDs of table columns to retrieve. The
 /// columns should share table indexes  (e.g., be a part of the same or
 /// AUGMENTed table).</param>
 /// <param name="options">The options for the operation.</param>
 /// <param name="nRequests">Will be incremented every time a response
 /// is received.</param>
 /// <returns>The retrieved rows. Due to performance reasons, the rows
 /// are returned as a jagged array  but the array is guaranteed to be
 /// rectangular.  It contains either valid variable bindings or <b>null</b>
 /// values for table "holes".</returns>
 /// <remarks>This method returns table rows for the specified set of
 /// columns. A typical example includes the retrieval of a complete
 /// table but a number of parameters makes this method more flexible.
 /// For more information on internal behavior, see the
 /// <see cref="TableReader.UseAsyncInvoke"/> property.</remarks>
 public static Vb[][] GetTable(Snmp snmp, Pdu pdu, SnmpTarget target,
                               Oid[] columnOids, GetTableOptions options, ref int nRequests)
 {
     return(GetTable(snmp, pdu, target, columnOids,
                     options.startRowIndex, options.endRowIndex,
                     options.maxRows, options.rowsPerQuery, ref nRequests));
 }
Exemple #6
0
 /// <summary>
 /// Starts an asynchronous SNMP table retrieval operation.
 /// </summary>
 /// <param name="snmp">The SNMP session object to use.</param>
 /// <param name="pdu">The PDU object used to convey the request type
 /// and some security parameters (variable bindings are ignored; may
 /// be an empty array).</param>
 /// <param name="target">The SNMP target.</param>
 /// <param name="columnOids">The OIDs of table columns to retrieve. The
 /// columns should share table indexes  (e.g., be a part of the same or
 /// AUGMENTed table).</param>
 /// <param name="options">The options for the operation.</param>
 /// <param name="callback">Callback method to invoke when a table is read
 /// or <b>null</b>.</param>
 /// <param name="callbackData">User state.</param>
 /// <returns><see cref="IAsyncResult"/> object.</returns>
 /// <remarks>
 /// This method starts asynchronous table retrieval for the specified set
 /// of columns. A typical example includes the retrieval of a whole table
 /// but a number of parameters makes this method more flexible.  In order
 /// to complete the operation and free related resources, <see cref="EndGetTable"/>
 /// must be later called,  usually, in the callback method specified
 /// by <b>callback</b> parameter.
 /// </remarks>
 public static IAsyncResult BeginGetTable(Snmp snmp, Pdu pdu, SnmpTarget target,
                                          Oid[] columnOids, GetTableOptions options,
                                          AsyncCallback callback, object callbackData)
 {
     return(BeginGetTable(snmp, pdu, target, columnOids,
                          options.startRowIndex, options.endRowIndex,
                          options.maxRows, options.rowsPerQuery, callback, callbackData));
 }
Exemple #7
0
        /// <summary>
        /// Retrieves an SNMP table from an agent.
        /// </summary>
        /// <param name="snmp">The SNMP session object to use.</param>
        /// <param name="pdu">The PDU object used to convey the request type
        /// and some security parameters (variable bindings are ignored; may
        /// be an empty array).</param>
        /// <param name="target">The SNMP target.</param>
        /// <param name="columnOids">The OIDs of table columns to retrieve. The
        /// columns should share table indexes  (e.g., be a part of the same or
        /// AUGMENTed table).</param>
        /// <param name="startRowIndex">The row index to start from or <b>null</b>.</param>
        /// <param name="maxRows">Maximum number of rows to retrieve. Specify 0
        /// to read the whole table.</param>
        /// <returns>The retrieved rows. Due to performance reasons, the rows
        /// are returned as a jagged array  but the array is guaranteed to be
        /// rectangular.  It contains either valid variable bindings or <b>null</b>
        /// values for table "holes".</returns>
        /// <remarks>This method returns table rows for the specified set of
        /// columns. A typical example includes the retrieval of a complete
        /// table but a number of parameters makes this method more flexible.
        /// For more information on internal behavior, see the
        /// <see cref="TableReader.UseAsyncInvoke"/> property.</remarks>
        public static Vb[][] GetTable(Snmp snmp, Pdu pdu, SnmpTarget target,
                                      Oid[] columnOids, Oid startRowIndex, int maxRows)
        {
            int nRequests = 0;

            return(GetTable(snmp, pdu, target, columnOids,
                            startRowIndex, null, maxRows, 0, ref nRequests));
        }
Exemple #8
0
 private static Pdu Invoke(Snmp snmp, Pdu pdu, SnmpTarget target, bool asyncSync)
 {
     if (asyncSync)
     {
         IAsyncResult ar = snmp.BeginInvoke(pdu, target, null, null);
         return(snmp.EndInvoke(ar));
     }
     else
     {
         return(snmp.Invoke(pdu, target));
     }
 }
Exemple #9
0
 private static void Table(Snmp snmp, Pdu pdu, SnmpTarget target,
                           ref TableReader.GetTableOptions tableOptions, bool show, bool debug,
                           ref int ncalls)
 {
     Oid[] columnOids = GetColumnOids(pdu);
     pdu = pdu.Clone(new Vb[0]);                 // not really needed; for test purposes
     Vb[][] vbTable = TableReader.GetTable(snmp, pdu, target,
                                           columnOids, tableOptions, ref ncalls);
     if (show || debug)
     {
         TableReader.PrintTable(Console.Out, columnOids, vbTable);
     }
 }
Exemple #10
0
        /// <summary>
        /// Starts an asynchronous SNMP table retrieval operation.
        /// </summary>
        /// <param name="snmp">The SNMP session object to use.</param>
        /// <param name="pdu">The PDU object used to convey the request type
        /// and some security parameters (variable bindings are ignored; may
        /// be an empty array).</param>
        /// <param name="target">The SNMP target.</param>
        /// <param name="columnOids">The OIDs of table columns to retrieve. The
        /// columns should share table indexes  (e.g., be a part of the same or
        /// AUGMENTed table).</param>
        /// <param name="startRowIndex">The row index to start from or <b>null</b>.</param>
        /// <param name="endRowIndex">The row index to finish at or <b>null</b>.</param>
        /// <param name="maxRows">Maximum number of rows to retrieve. Specify 0
        /// to read the whole table.</param>
        /// <param name="rowsPerQuery">Number of rows to read in a single query.
        /// Only valid if the request used will be GetBulk. Specify 0 to enable
        /// a simple heuristic algorithm that dynamically computes this value
        /// so that the response fits a single Ethernet packet.</param>
        /// <param name="callback">Callback method to invoke when a table is read
        /// or <b>null</b>.</param>
        /// <param name="callbackData">User state.</param>
        /// <returns><see cref="IAsyncResult"/> object.</returns>
        /// <remarks>
        /// This method starts asynchronous table retrieval for the specified set
        /// of columns. A typical example includes the retrieval of a whole table
        /// but a number of parameters makes this method more flexible.  In order
        /// to complete the operation and free related resources, <see cref="EndGetTable"/>
        /// must be later called,  usually, in the callback method specified
        /// by <b>callback</b> parameter.
        /// </remarks>
        public static IAsyncResult BeginGetTable(Snmp snmp, Pdu pdu, SnmpTarget target,
                                                 Oid[] columnOids, Oid startRowIndex, Oid endRowIndex,
                                                 int maxRows, int rowsPerQuery,
                                                 AsyncCallback callback, object callbackData)
        {
            GetTableState state = PrepareGetTable(snmp, pdu, target, columnOids,
                                                  startRowIndex, endRowIndex, maxRows, rowsPerQuery,
                                                  callback, callbackData, false);

            state.pdu.MaxRepetitions = GetMaxRepetitions(state);
            snmp.BeginInvoke(state.pdu, state.target,
                             new AsyncCallback(GetTableCallback), state);
            return(state);
        }
Exemple #11
0
        /// <summary>
        /// Retrieves an SNMP table from an agent.
        /// </summary>
        /// <param name="snmp">The SNMP session object to use.</param>
        /// <param name="pdu">The PDU object used to convey the request type
        /// and some security parameters (variable bindings are ignored; may
        /// be an empty array).</param>
        /// <param name="target">The SNMP target.</param>
        /// <param name="columnOids">The OIDs of table columns to retrieve. The
        /// columns should share table indexes  (e.g., be a part of the same or
        /// AUGMENTed table).</param>
        /// <param name="startRowIndex">The row index to start from or <b>null</b>.</param>
        /// <param name="endRowIndex">The row index to finish at or <b>null</b>.</param>
        /// <param name="maxRows">Maximum number of rows to retrieve. Specify 0
        /// to read the whole table.</param>
        /// <param name="rowsPerQuery">Number of rows to read in a single query.
        /// Only valid if the request used will be GetBulk. Specify 0 to enable
        /// a simple heuristic algorithm that dynamically computes this value
        /// so that the response fits a single Ethernet packet.</param>
        /// <param name="nRequests">Will be incremented every time a response
        /// is received.</param>
        /// <returns>The retrieved rows. Due to performance reasons, the rows
        /// are returned as a jagged array  but the array is guaranteed to be
        /// rectangular.  It contains either valid variable bindings or <b>null</b>
        /// values for table "holes".</returns>
        /// <remarks>This method returns table rows for the specified set of
        /// columns. A typical example includes the retrieval of a complete
        /// table but a number of parameters makes this method more flexible.
        /// For more information on internal behavior, see the
        /// <see cref="TableReader.UseAsyncInvoke"/> property.</remarks>
        public static Vb[][] GetTable(Snmp snmp, Pdu pdu, SnmpTarget target,
                                      Oid[] columnOids, Oid startRowIndex, Oid endRowIndex,
                                      int maxRows, int rowsPerQuery, ref int nRequests)
        {
            GetTableState state = PrepareGetTable(snmp, pdu, target, columnOids,
                                                  startRowIndex, endRowIndex, maxRows, rowsPerQuery,
                                                  null, null, true);

            do
            {
                state.pdu.MaxRepetitions = GetMaxRepetitions(state);
            }while (!ProcessGetTable(state, null, ref nRequests));

            return(ExtractRows(state.rows));
        }
Exemple #12
0
        public Rtu(int id, string name, IPEndpoint clientAddress, IPEndpoint hostAddres, ushort localDNP3Addres, ushort remoteDNP3Address,
            Dictionary<int, int> bins, Dictionary<int, int> analogs, Dictionary<int, int> counters, DatabaseTemplate dt, GeminiMap gmap)
        {
            Id = id;
            Name = name;
            //Considerando uma RTU por Canal
            if (Core.LoggingEnabled)
            {
                Channel = Core.DNP3Manager.AddTCPServer(name, LogLevels.ALL, ServerAcceptMode.CloseExisting, hostAddres.address, hostAddres.port, ChannelListener.Print());
            }
            else
            {
                Channel = Core.DNP3Manager.AddTCPServer(name, LogLevels.NONE, ServerAcceptMode.CloseExisting, hostAddres.address, hostAddres.port, ChannelListener.Print());
            }

            //Configuração Padrão de RTU é Outstation
            Config = new OutstationStackConfig
            {
                databaseTemplate = dt
            };
            Config.link.remoteAddr = remoteDNP3Address;
            Config.link.localAddr = localDNP3Addres;
            DNP3ToSNMPBinaries = bins;
            DNP3ToSNMPAnalogs = analogs;
            DNP3ToSNMPCounters = counters;
            Outstation = Channel.AddOutstation(name, RejectingCommandHandler.Instance, DefaultOutstationApplication.Instance, Config);
            Outstation.Enable();
            geminiMap = gmap;

            Target = new SnmpTarget(clientAddress.address, clientAddress.port, Core.Settings.SNMPTimeout, Core.Settings.SNMPRetry);

            foreach (KeyValuePair<int, int> map in DNP3ToSNMPBinaries)
            {
                Target.InsertObject(Core.OidLibrary.GetLabelFromId(map.Value), Core.OidLibrary.GetOidFromId(map.Value));
            }

            foreach (KeyValuePair<int, int> map in DNP3ToSNMPAnalogs)
            {
                Target.InsertObject(Core.OidLibrary.GetLabelFromId(map.Value), Core.OidLibrary.GetOidFromId(map.Value));
            }

            foreach (KeyValuePair<int, int> map in DNP3ToSNMPCounters)
            {
                Target.InsertObject(Core.OidLibrary.GetLabelFromId(map.Value), Core.OidLibrary.GetOidFromId(map.Value));
            }

            MonitorThread = new Timer(new TimerCallback(Update), null, TimeSpan.FromMilliseconds(10), TimeSpan.FromSeconds(Core.Settings.GatewayPoolingTime));
        }
Exemple #13
0
        private List <SnmpResult <int, string> > MapMacAddresses(SnmpTarget snmpTarget)
        {
            var fdbAddressTable = ReadFdbAddressTable(snmpTarget);
            var fdbPortTable    = ReadFdbPortTable(snmpTarget);

            var portMappings = fdbPortTable.Select(port => new
            {
                PortNumber = Convert.ToInt32(port.Value.ToString()),
                Oid        = port.Oid.ToString()
            })
                               .GroupBy(mappings => mappings.PortNumber)
                               .Where(mappings => mappings.Any())
                               .ToDictionary(mapping => mapping.Key, mapping => mapping.ToList());

            var macMappings = fdbAddressTable.Select(port => new
            {
                MacAddress = port.Value.ToString(),
                Oid        = port.Oid.ToString().Replace(SnmpOids.Dot1DTpFdbAddress, SnmpOids.Dot1DTpFdbPort)
            })
                              .GroupBy(mappings => mappings.Oid)
                              .Where(mappings => mappings.Any())
                              .ToDictionary(mapping => mapping.Key, mapping => mapping.First().MacAddress);

            var results = new List <SnmpResult <int, string> >();

            foreach (var portMapping in portMappings)
            {
                string macAddress;

                foreach (var oid in portMapping.Value)
                {
                    if (macMappings.TryGetValue(oid.Oid, out macAddress))
                    {
                        var result = new SnmpResult <int, string>
                        {
                            Identifier = portMapping.Key,
                            Result     = macAddress.Replace(' ', ':'),
                            SnmpTarget = snmpTarget,
                            Oid        = ""
                        };

                        results.Add(result);
                    }
                }
            }

            return(results);
        }
Exemple #14
0
 private Manager(int id,
                 Snmp snmp, SnmpTarget target, Pdu pdu, OperType operType,
                 ref TableReader.GetTableOptions tableOptions, Barrier barrier,
                 uint nRepeats, bool asyncSync, bool debug)
 {
     id_           = id;
     snmp_         = snmp;
     target_       = target;
     pdu_          = pdu;
     operType_     = operType;
     tableOptions_ = tableOptions;
     barrier_      = barrier;
     nRepeats_     = nRepeats;
     asyncSync_    = asyncSync;
     debug_        = debug;
 }
        public static IList Walk(Snmp snmp, SnmpTarget target, Pdu pdu, IList list)
        {
            if (!(pdu.Type == PduType.GetNext || pdu.Type == PduType.GetBulk))
            {
                throw new ArgumentException("Invalid Pdu type", "pdu");
            }

            if (pdu.Count != 1)
            {
                throw new ArgumentException("Expected a single Vb", "pdu");
            }

            try
            {
                Oid subtree = pdu[0].Oid;
                while (true)
                {
                    pdu = snmp.Invoke(pdu, target);

                    Vb lastVb = null;
                    foreach (Vb vb in pdu)
                    {
                        Oid oid = vb.Oid;
                        if (!oid.StartsWith(subtree) ||
                            vb.Value.SmiSyntax == SmiSyntax.EndOfMibView)
                        {
                            return(list);
                        }

                        lastVb = vb;
                        list.Add(vb);
                    }

                    pdu = pdu.Clone(lastVb);
                }
            }
            catch (SnmpException e)
            {
                // SNMPv1 and NoSuchName?
                if (e.ErrorStatus != SnmpError.NoSuchName)
                {
                    throw;
                }
            }

            return(list);
        }
Exemple #16
0
 public GetTableState(Snmp snmp, Pdu pdu, SnmpTarget target,
                      Oid[] columnOids, Oid endRowIndex,
                      int maxRows, int rowsPerQuery,
                      Vb[] vbs,
                      AsyncCallback callback, object callbackData, bool sync)
 {
     this.snmp         = snmp;
     this.target       = target;
     this.columnOids   = columnOids;
     this.endRowIndex  = endRowIndex;
     this.maxRows      = maxRows;
     this.rowsPerQuery = rowsPerQuery;
     this.rows         = new Hashtable();
     this.callback     = callback;
     this.callbackData = callbackData;
     this.invoke       = sync
                                                             ? new SnmpInvoke(SyncInvoke)
                                                             : new SnmpInvoke(AsyncInvoke);
     this.pdu = pdu;
     this.vbs = vbs;
 }
Exemple #17
0
        private static void Walk(Snmp snmp, Pdu pdu, SnmpTarget target,
                                 bool asyncSync, bool show, bool debug, ref int ncalls)
        {
            Console.WriteLine("Rentre dans le Walk");
            string thName  = Thread.CurrentThread.Name;
            Oid    rootOid = pdu[0].Oid;

            while (true)
            {
                if (debug)
                {
                    PrintPdu(Console.Out, "Sending PDU to target " + target, pdu, debug);
                }

                Pdu resp = Invoke(snmp, pdu, target, asyncSync);
                ncalls++;

                Vb  nextVb  = resp[0];
                Oid nextOid = nextVb.Oid;
                if (!nextOid.StartsWith(rootOid))
                {
                    break;
                }

                if (debug)
                {
                    PrintPdu(Console.Out, "Received PDU:", resp, debug);
                }
                else
                if (show)
                {
                    SnmpSyntax val  = nextVb.Value;
                    SmiSyntax  type = val != null ? val.SmiSyntax : SmiSyntax.Null;
                    Console.WriteLine("[{0}]: {1},{2},{3}", thName, nextOid, val, type);
                }

                pdu = pdu.Clone(new Vb(nextOid));
            }
        }
Exemple #18
0
        private static void GotTrap(Snmp snmp, Pdu pdu, SnmpTarget target, object cbData)
        {
            if ((int)cbData != CB_DATA_)
            {
                Console.Error.WriteLine("*** Invalid callback data!");
            }
            if (threadId_ == null)
            {
                threadId_ = Interlocked.Increment(ref nextId_);
            }

            // Use a lock if you want do not want messages from various threads
            // to be interleaved
            ManagerUtilities.PrintPdu(Console.Out,
                                      Now() + ": " + pdu.Type + " received from " + target,
                                      pdu, true, threadId_);
            Console.Out.WriteLine(
                "Enterprise: " + pdu.NotifyEnterprise
                + "\nNotify OID      : " + pdu.NotifyId
                + "\nV1 generic-trap : " + pdu.V1GenericTrap
                + "\nV1 specific-trap: " + pdu.V1SpecificTrap
                + "\nTimestamp        : " + pdu.NotifyTimestamp);
            if (pdu.Type == PduType.V1Trap)
            {
                Console.Out.WriteLine("v1TrapAddr: " + pdu.V1TrapAddress);
            }

            if (pdu.Type == PduType.Inform)
            {
                Vb vb = new Vb("1.3.6.1", new OctetStr("this is the response"));
                pdu = new Pdu(PduType.Response, vb);
                snmp.Invoke(pdu, target);
                ManagerUtilities.PrintPdu(Console.Out,
                                          "Response sent to " + target, pdu, true, threadId_);
            }

            // Long trap processing follows...
            Thread.Sleep(5000);
        }
Exemple #19
0
        static void Main(string[] args)
        {
            Core.Start();

            SnmpTarget retAbelSantana = new SnmpTarget("10.7.5.150");

            retAbelSantana.InsertObject("batteryTemperaturesValue", ".1.3.6.1.4.1.12148.10.10.7.5.0");
            SnmpV2Packet result     = retAbelSantana.GetUpdate();
            IPEndpoint   myEndPoint = new IPEndpoint("0.0.0.0", 20500);
            Rtu          rtu        = new Rtu("Teste DNP3", myEndPoint, 2, 1);
            ChangeSet    changeSet;
            int          currentValue;

            while (true)
            {
                if (result != null)
                {
                    changeSet = new ChangeSet();
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                    }
                    else
                    {
                        currentValue = Convert.ToInt32(result.Pdu.VbList[0].Value.ToString());
                        changeSet.Update(new Analog(currentValue, 1, DateTime.Now), 0);
                        Console.WriteLine("Atualizando valor da analógica para " + currentValue);
                        rtu.Outstation.Load(changeSet);
                    }
                }
                else
                {
                    Console.WriteLine("Erro SNMP Nulo");
                }
                Thread.Sleep(15000);
            }
        }
Exemple #20
0
        private static Hashtable DoSnmp(Snmp snmp, SnmpTarget target, Pdu pdu,
                                        OperType operType, ref TableReader.GetTableOptions tableOptions,
                                        uint repeat, bool asyncSync, bool debug)
        {
            int       ncalls   = 0;
            Hashtable htResult = new Hashtable();

            for (uint i = 0; i < repeat; i++)
            {
                using (IMemoryManager mgr = MemoryManager.GetMemoryManager())
                {
                    bool show = (i % 1000) == 0;
                    if (show || debug)
                    {
                        //PrintPdu(Console.Out, "Sending PDU to target " + target, pdu, debug);
                    }

                    Pdu resPdu = DoSnmp(snmp, target, pdu,
                                        operType, ref tableOptions,
                                        asyncSync, show, debug, ref ncalls);

                    if ((show || debug) && resPdu != null)
                    {
                        //**********OLI***********//
                        //PrintPdu(Console.Out, "Received PDU:", resPdu, debug);
                        //************************//
                        htResult = ManagerUtilities.getValues(resPdu);
                    }
                    if (debug)
                    {
                        Console.WriteLine("Removing " + mgr.Count + " objects");
                    }
                }
            }
            htResult.Add("count", ncalls);
            return(htResult);
            //return ncalls;
        }
Exemple #21
0
        private static Pdu DoSnmp(Snmp snmp, SnmpTarget target, Pdu pdu,
                                  OperType operType, ref TableReader.GetTableOptions tableOptions,
                                  bool asyncSync, bool show, bool debug, ref int ncalls)
        {
            switch (operType)
            {
            case OperType.Walk:
                Walk(snmp, pdu, target, asyncSync, show, debug, ref ncalls);
                pdu = null;
                break;

            case OperType.Table:
                Table(snmp, pdu, target, ref tableOptions, show, debug, ref ncalls);
                pdu = null;
                break;

            default:
                pdu = Invoke(snmp, pdu, target, asyncSync);
                ncalls++;
                break;
            }
            return(pdu);
        }
Exemple #22
0
        private List <Vb> ReadFdbPortTable(SnmpTarget snmpTarget)
        {
            var community = new OctetString(
                string.IsNullOrEmpty(snmpTarget.Community) ? "public" : snmpTarget.Community);
            var param = new AgentParameters(community)
            {
                Version = SnmpVersion.Ver2
            };
            var agent   = new IpAddress(snmpTarget.IpAddress);
            var target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            var rootOid = new Oid(SnmpOids.Dot1DTpFdbPort);
            var lastOid = (Oid)rootOid.Clone();
            var pdu     = new Pdu(PduType.GetBulk)
            {
                NonRepeaters = 0, MaxRepetitions = 5
            };
            var results = new List <Vb>();

            while (lastOid != null)
            {
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                pdu.VbList.Clear();
                pdu.VbList.Add(lastOid);
                var result = (SnmpV2Packet)target.Request(pdu, param);

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                        break;
                    }

                    foreach (var v in result.Pdu.VbList)
                    {
                        if (rootOid.IsRootOf(v.Oid))
                        {
                            Console.WriteLine("{0} ({1}): {2}",
                                              v.Oid,
                                              SnmpConstants.GetTypeName(v.Value.Type),
                                              v.Value);

                            results.Add(v);

                            lastOid = v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW ? null : v.Oid;
                        }
                        else
                        {
                            lastOid = null;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();

            return(results);
        }
Exemple #23
0
 /// <summary>
 /// Retrieves an SNMP table from an agent.
 /// </summary>
 /// <param name="snmp">The SNMP session object to use.</param>
 /// <param name="pdu">The PDU object used to convey the request type
 /// and some security parameters (variable bindings are ignored; may
 /// be an empty array).</param>
 /// <param name="target">The SNMP target.</param>
 /// <param name="columnOids">The OIDs of table columns to retrieve. The
 /// columns should share table indexes  (e.g., be a part of the same or
 /// AUGMENTed table).</param>
 /// <returns>The retrieved rows. Due to performance reasons, the rows
 /// are returned as a jagged array  but the array is guaranteed to be
 /// rectangular.  It contains either valid variable bindings or <b>null</b>
 /// values for table "holes".</returns>
 /// <remarks>This method returns table rows for the specified set of
 /// columns. A typical example includes the retrieval of a complete
 /// table. For more information on internal behavior, see the
 /// <see cref="TableReader.UseAsyncInvoke"/> property.</remarks>
 public static Vb[][] GetTable(Snmp snmp, Pdu pdu, SnmpTarget target,
                               Oid[] columnOids)
 {
     return(GetTable(snmp, pdu, target, columnOids,
                     null, 0));
 }
Exemple #24
0
        private List <SnmpResult <int, long> > ProcessTargetsTraffic(SnmpTarget snmpTarget, string snmpOid,
                                                                     string communityString = "public")
        {
            var results = new List <SnmpResult <int, long> >();

            var community = new OctetString(communityString);
            var param     = new AgentParameters(community)
            {
                Version = SnmpVersion.Ver2
            };
            var agent   = new IpAddress(snmpTarget.IpAddress);
            var target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            var rootOid = new Oid(snmpOid);
            var lastOid = (Oid)rootOid.Clone();
            var pdu     = new Pdu(PduType.GetBulk)
            {
                NonRepeaters = 0, MaxRepetitions = 5
            };

            while (lastOid != null)
            {
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                pdu.VbList.Clear();
                pdu.VbList.Add(lastOid);
                var result = (SnmpV2Packet)target.Request(pdu, param);

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                        break;
                    }

                    foreach (var v in result.Pdu.VbList)
                    {
                        var current = new SnmpResult <int, long>();

                        if (rootOid.IsRootOf(v.Oid))
                        {
                            Console.WriteLine("{0} ({1}): {2}",
                                              v.Oid,
                                              SnmpConstants.GetTypeName(v.Value.Type),
                                              v.Value);

                            current.Result     = Convert.ToInt64(v.Value.ToString());
                            current.Identifier = Convert.ToInt32(v.Oid.ToString().Split('.').Last());
                            current.Oid        = v.Oid.ToString();
                            current.SnmpTarget = snmpTarget;

                            results.Add(current);

                            lastOid = v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW ? null : v.Oid;
                        }
                        else
                        {
                            lastOid = null;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();

            return(results);
        }
Exemple #25
0
 private static void AsyncDoSnmp(Snmp snmp, SnmpTarget target, Pdu pdu,
                                 AsyncCallback callback, Object data)
 {
     snmp.BeginInvoke(pdu, target, callback, data);
 }
 public static IList Walk(Snmp snmp, SnmpTarget target, Pdu pdu)
 {
     return(Walk(snmp, target, pdu, new ArrayList(128)));
 }