Esempio n. 1
0
        static void InsertExampleDatapointValues(Int32 NumberOfDays, Int32 MinutesBetweenValues)
        {
            List <DatapointNode> datapointNodes = Database.GetAllDatapointNodes();

            Console.Write(String.Format("> Insert values for {0} datapoins, {1} days in a {2} minutes period...", datapointNodes.Count, NumberOfDays, MinutesBetweenValues));
            try {
                Random     random      = new Random();
                const long NSPerSecond = 10000000;
                Int64      TimeTicks   = 60 * 60 * 24 * NSPerSecond;
                TimeTicks *= NumberOfDays;
                TimeTicks += random.Next(1, 59) * NSPerSecond;
                DateTime EndTime   = DateTime.Now;
                DateTime StartTime = new DateTime(EndTime.Ticks - TimeTicks);

                DatapointValueNode valueNode = new DatapointValueNode();
                foreach (DatapointNode datapointNode in datapointNodes)
                {
                    DateTime TempTime = StartTime;
                    valueNode.SetDatapointID(datapointNode.GetID());
                    valueNode.SetType(datapointNode.GetDatapointType());
                    while (TempTime.Ticks < EndTime.Ticks)
                    {
                        valueNode.SetTimeStamp(TempTime);
                        if (datapointNode.GetDatapointType() == DatapointNode.TYPE_FLOATING_POINT)
                        {
                            valueNode.SetDecimalValue(random.NextDouble());
                            valueNode.SetStringValue(valueNode.GetDecimalValue().ToString().Replace(",", "."));
                        }
                        else if (datapointNode.GetDatapointType() == DatapointNode.TYPE_INTEGER)
                        {
                            valueNode.SetIntegerValue(random.Next(30, 130));
                            valueNode.SetStringValue(valueNode.GetIntegerValue().ToString());
                        }
                        Database.InsertNode(valueNode);
                        TempTime = TempTime.AddMinutes(MinutesBetweenValues);
                    }
                    datapointNode.SetLastValue(valueNode.GetStringValue());
                    datapointNode.SetLastValueUpdate(valueNode.GetTimeStamp());
                    Database.UpdateNode(datapointNode);
                }
                ConsoleWriteSuccess("OK");
            } catch (Exception ex) {
                ConsoleWriteError(ex.Message);
            }
        }
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            String DatabaseType     = ConfigurationManager.AppSettings["DatabaseConnector"];
            String DatabaseName     = ConfigurationManager.AppSettings["DatabaseName"];
            String DatabaseServer   = ConfigurationManager.AppSettings["DatabaseServer"];
            String DatabaseUsername = ConfigurationManager.AppSettings["DatabaseUsername"];
            String DatabasePassword = ConfigurationManager.AppSettings["DatabasePassword"];

            Database = new DatabaseFacade();
            if (DatabaseType.Equals("MYSQL"))
            {
                // Tell the DatabseFacade to use the MySQLConnector
                Database.SetDatabaseConnector(
                    new MySQLConnector(String.Format("SERVER={0};DATABASE={1};UID={2};PASSWORD={3};", DatabaseServer, DatabaseName, DatabaseUsername, DatabasePassword))
                    );
            }

            Logger.Info(String.Format("Getting Data for all active devices"));
            if (OpenConnection())
            {
                Logger.Debug("Database Connection Established");
                List <DeviceNode> deviceNodes = Database.GetAllDeviceNodes();
                Logger.Debug(String.Format("Found {0} Device Nodes", deviceNodes.Count));
                foreach (DeviceNode deviceNode in deviceNodes)
                {
                    List <DatapointNode> datapointNodes = Database.GetDatapointNodesByDeviceID(deviceNode.GetID());
                    if (datapointNodes.Count > 0)
                    {
                        // Buffer for incoming data
                        char[] readBuffer = new char[150];

                        // Store the device answer
                        String deviceResponse = null;

                        if (PingHost(deviceNode.GetIPAddress().ToString()))
                        {
                            try {
                                Logger.Info(String.Format("Get Data For Device '{0}' With IP '{1}' And Port '{2}'", deviceNode.GetName(), deviceNode.GetIPAddress(), deviceNode.GetPort()));

                                // Create a tcp client and open the connection
                                TcpClient tcpClient = new TcpClient(deviceNode.GetIPAddress().ToString(), deviceNode.GetPort());
                                tcpClient.ReceiveTimeout = 10000;
                                tcpClient.SendTimeout    = 2000;

                                // Getting the network stream
                                NetworkStream networkStream = tcpClient.GetStream();
                                // Create a writer to write on the network stream
                                StreamWriter streamWriter = new StreamWriter(networkStream);
                                streamWriter.AutoFlush = true;
                                // Create a reader to read from the network stream
                                StreamReader streamReader = new StreamReader(networkStream);

                                // Send a command to the device
                                streamWriter.Write("C:Data:Get;");

                                // Read answer from the device
                                deviceResponse = streamReader.ReadLine();

                                streamWriter.Close();
                                tcpClient.Close();

                                DataObject         dataObject = JsonConvert.DeserializeObject <DataObject>(deviceResponse);
                                DatapointValueNode valueNode  = new DatapointValueNode();
                                foreach (DatapointNode datapointNode in datapointNodes)
                                {
                                    valueNode.SetDatapointID(datapointNode.GetID());
                                    valueNode.SetType(datapointNode.GetDatapointType());
                                    valueNode.SetTimeStamp(DateTime.Now);
                                    if (datapointNode.GetDescription().Equals("Loudness"))
                                    {
                                        valueNode.SetIntegerValue(dataObject.GetLoudness());
                                        valueNode.SetDecimalValue(0.0);
                                        valueNode.SetStringValue(dataObject.GetLoudness().ToString());
                                        Logger.Debug("Loudness = " + valueNode.GetIntegerValue());
                                    }
                                    else if (datapointNode.GetDescription().Equals("CO2Concentration"))
                                    {
                                        valueNode.SetIntegerValue(dataObject.GetCO2Concentration());
                                        valueNode.SetDecimalValue(0.0);
                                        valueNode.SetStringValue(dataObject.GetCO2Concentration().ToString());
                                        Logger.Debug("CO2 Concentration = " + valueNode.GetIntegerValue());
                                    }
                                    else if (datapointNode.GetDescription().Equals("Temperature"))
                                    {
                                        valueNode.SetIntegerValue(0);
                                        valueNode.SetDecimalValue(dataObject.GetTemperature());
                                        valueNode.SetStringValue(dataObject.GetTemperature().ToString().Replace(",", "."));
                                        Logger.Debug("Temperature = " + valueNode.GetDecimalValue());
                                    }
                                    Database.InsertNode(valueNode);
                                    datapointNode.SetLastValue(valueNode.GetStringValue());
                                    datapointNode.SetLastValueUpdate(valueNode.GetTimeStamp());
                                    Database.UpdateNode(datapointNode);
                                }
                            } catch (Exception ex) {
                                Logger.Error(ex.Message, ex);
                            }
                        }
                        else
                        {
                            Logger.Warn(String.Format("Device '{0}'({1}) Could Not Be Pinged > No Need To Establish A Connection", deviceNode.GetName(), deviceNode.GetID()));
                        }
                    }
                    else
                    {
                        Logger.Warn(String.Format("Device '{0}'({1}) Has No Datapoints > No Need To Establish A Connection", deviceNode.GetName(), deviceNode.GetID()));
                    }
                }
                CloseConnection();
            }
            else
            {
                Logger.Warn("Database Connection Could Not Be Established");
            }
        }
Esempio n. 3
0
        /// <summary>
        ///		Insert a DatapointValueNode into the database
        /// </summary>
        /// <param name="Node">
        ///		DatapointValueNode that should be insert
        /// </param>
        /// <returns>
        ///		true, if a row was inserted
        ///		false, if no row was inserted
        /// </returns>
        public Boolean InsertNode(DatapointValueNode Node)
        {
            // Command that will be send to the databse
            MySqlCommand Command = this.Connection.CreateCommand();

            // Update a row in the databse with the given node id
            // UPDATE						> Update rows of a table
            // SET	[colum name] = [value],	> Set a column to the given value
            //		[colum name] = [value]	> Set a column to the given value
            // WHERE object_id = {0}		> Update all rows where the column object_id matches the given id

            if (Node.GetType() == DatapointNode.TYPE_INTEGER)
            {
                Command.CommandText = String.Format(
                    "INSERT INTO datapoint_values VALUES( '{0}' , {1} , {2} , {3} , {4} , '{5}' )",
                    Node.GetTimeStamp().ToString("yyyy-MM-dd HH:mm:ss"), Node.GetDatapointID(), Node.GetType(), Node.GetIntegerValue(), Node.GetDecimalValue(), Node.GetStringValue()
                    );
            }
            else if (Node.GetType() == DatapointNode.TYPE_FLOATING_POINT)
            {
                String decimalValue = Node.GetDecimalValue().ToString().Replace(",", ".");
                decimalValue        = decimalValue.Substring(0, decimalValue.IndexOf(".") + 3);
                Command.CommandText = String.Format(
                    "INSERT INTO datapoint_values VALUES( '{0}' , {1} , {2} , {3} , {4} , '{5}' )",
                    Node.GetTimeStamp().ToString("yyyy-MM-dd HH:mm:ss"), Node.GetDatapointID(), Node.GetType(), Node.GetIntegerValue(), decimalValue, decimalValue
                    );
            }

            Command.Connection = this.Connection;

            // Execute the command and get the number of rows that are affected by the command
            Int32 AffectedRows = Command.ExecuteNonQuery();

            // If no rows where affected return false
            if (AffectedRows == 0)
            {
                return(false);
            }

            // Row successfully insert
            return(true);
        }