コード例 #1
0
        /// <summary>
        /// Create a new server socket, set up all the endpoints, bind the socket and then listen
        /// </summary>
        public void listen()
        {
            // Wait for VCRScheduler...
            //ConsoleOutputLogger.WriteLine("HTTP Server is waiting for VCRScheduler...");
            //while (!internal_vcr_scheduler_set)
            //{
            //    Thread.Sleep(10);
            //}
            Socket     listener  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress  ipaddress = IPAddress.Parse(HTTPServer_ListeningIP);
            IPEndPoint endpoint  = new IPEndPoint(ipaddress, HTTPServer_Port);

            try
            {
                // Create a new server socket, set up all the endpoints, bind the socket and then listen
                listener.Bind(endpoint);
                listener.Blocking = true;
                listener.Listen(-1);
                ConsoleOutputLogger.WriteLineToScreenOnly("[HTTP] Administrationsoberfläche unter http://" + HTTPServer_ListeningIP + ":" + HTTPServer_Port + " erreichbar.");
                while (true)
                {
                    try
                    {
                        // Accept a new connection from the net, blocking till one comes in
                        Socket s = listener.Accept();

                        // Create a new processor for this request
                        HttpProcessor processor = new HttpProcessor(s, HTTPServer_DocumentRoot, Storage, LatitudeStorage, XS1_Configuration, ConsoleOutputLogger, ELVMAXMonitoringThread, AuthorizationEnabled, Username, Password, AuthDisabledForAdressesThatStartWith);

                        // Dispatch that processor in its own thread
                        Thread thread = new Thread(new ThreadStart(processor.process));
                        thread.Start();
                        Thread.Sleep(10);
                        //processor.process();
                    }
                    catch (NullReferenceException)
                    {
                        // Don't even ask me why they throw this exception when this happens
                        ConsoleOutputLogger.WriteLine("[FEHLER@HTTP] Kann nicht auf TCP-Port " + HTTPServer_Port + " verbinden - wird vermutlich schon benutzt.");
                    }
                }
            }
            catch (Exception e)
            {
                ConsoleOutputLogger.WriteLine("[FEHLER@HTTP] " + e.Message);
            }
        }
コード例 #2
0
        public void MQTT_Handle_Sensor(xs1.XS1_DataObject XS1SensorData)
        {
            ConsoleOutputLogger.WriteLineToScreenOnly("MQTT-Binding-SensorInput: " + XS1SensorData.Name);

            foreach (MqttSensorMapping sensormap in MQTTBindingConfiguration.MQTTBindingConfigFile.mqtt_sensor_mapping)
            {
                if (sensormap.hacs == XS1SensorData.Name)
                {
                    // we have a valid mapping
                    if (!client.IsConnected)
                    {
                        client.Connect(clientId);
                    }

                    client.Publish(sensormap.mqtt, Encoding.UTF8.GetBytes(Convert.ToString(XS1SensorData.Value)), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
                    ConsoleOutputLogger.WriteLine("MQTT-Publish: " + sensormap.mqtt + " - " + XS1SensorData.Value);
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// Create a new server socket, set up all the endpoints, bind the socket and then listen
        /// </summary>
        public void listen()
        {
            Socket     listener  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress  ipaddress = IPAddress.Parse(HTTPServer_ListeningIP);
            IPEndPoint endpoint  = new IPEndPoint(ipaddress, HTTPServer_Port);

            try
            {
                // Create a new server socket, set up all the endpoints, bind the socket and then listen
                listener.Bind(endpoint);
                listener.Blocking = true;
                listener.Listen(-1);
                ConsoleOutputLogger.WriteLineToScreenOnly("[HTTP] Administrationsoberfläche unter http://" + HTTPServer_ListeningIP + ":" + HTTPServer_Port + " erreichbar.");
                while (true)
                {
                    try
                    {
                        // Accept a new connection from the net, blocking till one comes in
                        Socket s = listener.Accept();

                        // Create a new processor for this request
                        HttpProcessor processor = new HttpProcessor(s, HTTPServer_DocumentRoot, ConsoleOutputLogger, ThumbCache);


                        // Dispatch that processor in its own thread
                        Thread thread = new Thread(new ThreadStart(processor.process));
                        thread.Start();
                        //Thread.Sleep(10);
                        //processor.process();
                    }
                    catch (NullReferenceException)
                    {
                        // Don't even ask me why they throw this exception when this happens
                        ConsoleOutputLogger.WriteLine("[FEHLER@HTTP] Kann nicht auf TCP-Port " + HTTPServer_Port + " verbinden - wird vermutlich schon benutzt.");
                    }
                }
            }
            catch (Exception e)
            {
                ConsoleOutputLogger.WriteLine("[FEHLER@HTTP] " + e.Message);
            }
        }
コード例 #4
0
ファイル: JSONData.cs プロジェクト: devrez/hacs
        /// <summary>
        /// generates JSON dataset from sensor data
        /// </summary>
        /// <returns></returns>
        public String GenerateDataJSONOutputWithoutInterpolation(ObjectTypes DataType, String ObjectTypeName, String ObjectName, DateTime StartDateTime, DateTime EndDateTime)
        {
            /* Example:
             *
             * {    label: 'Europe (EU27)',
             *       data: [[1999, 3.0], [2000, 3.9], [2001, 2.0], [2002, 1.2], [2003, 1.3], [2004, 2.5], [2005, 2.0], [2006, 3.1], [2007, 2.9], [2008, 0.9]]
             * }
             *
             * */

            StringBuilder Output = new StringBuilder();

            Output.Append("{ \"label\": \"" + ObjectName + "\", \"data\": [");
            bool   firstdataset      = true;
            UInt64 SerializerCounter = 0;
            UInt64 OutputCounter     = 0;
            double LastValue         = double.NaN;

            // TODO: there should be an appropriate caching algorithm in the sensor data...

            lock (sensor_data.InMemoryIndex)
            {
                foreach (OnDiscAdress ondisc in sensor_data.InMemoryIndex)
                {
                    if (ondisc.CreationTime >= StartDateTime.Ticks)
                    {
                        if (ondisc.CreationTime <= EndDateTime.Ticks)
                        {
                            XS1_DataObject dataobject = ReadFromCache(ondisc);
                            SerializerCounter++;

                            if (dataobject.Type == DataType)
                            {
                                if (dataobject.TypeName == ObjectTypeName)
                                {
                                    if (dataobject.Name == ObjectName)
                                    {
                                        if (!firstdataset)
                                        {
                                            Output.Append(",");
                                        }
                                        else
                                        {
                                            firstdataset = false;
                                        }

                                        if (LastValue == double.NaN)
                                        {
                                            LastValue = dataobject.Value;
                                            Output.Append("[");
                                            Output.Append(dataobject.Timecode.JavaScriptTimestamp());
                                            Output.Append(",");
                                            Output.Append(dataobject.Value.ToString().Replace(',', '.'));
                                            Output.Append("]");
                                            OutputCounter++;
                                        }
                                        else
                                        {
                                            if (LastValue != dataobject.Value)
                                            {
                                                Output.Append("[");
                                                Output.Append(dataobject.Timecode.JavaScriptTimestamp());
                                                Output.Append(",");
                                                Output.Append(dataobject.Value.ToString().Replace(',', '.'));
                                                Output.Append("]");
                                                OutputCounter++;
                                            }
                                            LastValue = dataobject.Value;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Output.Append("]}");

            ConsoleOutputLogger_.WriteLineToScreenOnly("Generated JSON Dataset with " + SerializerCounter + " Elements and outputted " + OutputCounter + " Elements.");

            return(Output.ToString());
        }
コード例 #5
0
        /// <summary>
        /// We need to make sure that the url that we are trying to treat as a file
        /// lies below the document root of the http server so that people can't grab
        /// random files off your computer while this is running.
        /// </summary>
        public void writeURL()
        {
            try
            {
                // set this to true when implementing and reaching a new method
                bool method_found = false;

                // first check if the request is actually authenticated
                IPEndPoint AC_endpoint = (IPEndPoint)s.RemoteEndPoint;
                ConsoleOutputLogger.WriteLine(AC_endpoint.Address.ToString() + " GET " + original_url);

                querystring = "";
                url         = original_url;

                if (url.ToUpper().StartsWith("/PICS/"))
                {
                    List <FileInfo> Jpegs = FileManager.EnumerateAllJPGs(GalleryServer.Properties.Settings.Default.PicturesPath);
                    Dictionary <String, List <FileInfo> > sortedByDays = FileManager.SortAllJpegsByDay(Jpegs);

                    // let's find out if we're going to go deeper...

                    if (url.ToUpper().EndsWith("/PICS/"))
                    {
                        #region this is the first level /pics/
                        // the first level just get's you the days of which pics are available...
                        Dictionary <String, String> OutputObj = new Dictionary <string, string>();
                        foreach (String Date in sortedByDays.Keys)
                        {
                            OutputObj.Add(Date, "/pics/" + Date.ToLower());
                        }
                        string Output = JsonConvert.SerializeObject(OutputObj, Formatting.Indented);

                        int left = new UTF8Encoding().GetByteCount(Output);
                        //writeSuccess(left, "application/json");
                        writeSuccess(left, "text/html");
                        byte[] buffer = new UTF8Encoding().GetBytes(Output);
                        ns.Write(buffer, 0, left);
                        ns.Flush();
                        return;

                        #endregion
                    }
                    else
                    {
                        #region Here we go into deeper levels, first level will be day
                        url = url.Remove(0, 6);
                        Dictionary <String, String> OutputObj = new Dictionary <string, string>();

                        foreach (String Day in sortedByDays.Keys)
                        {
                            if (url.ToUpper().EndsWith(Day.ToUpper()))
                            {
                                // we've found the day, output all jpgs here...
                                foreach (FileInfo _file in sortedByDays[Day])
                                {
                                    OutputObj.Add(_file.Name + _file.LastWriteTime.Ticks, "/picture/" + _file.Name + _file.LastWriteTime.Ticks);
                                }
                            }
                        }
                        string Output = JsonConvert.SerializeObject(OutputObj, Formatting.Indented);

                        int left = new UTF8Encoding().GetByteCount(Output);
                        //writeSuccess(left, "application/json");
                        writeSuccess(left, "text/html");
                        byte[] buffer = new UTF8Encoding().GetBytes(Output);
                        ns.Write(buffer, 0, left);
                        ns.Flush();
                        return;

                        #endregion
                    }
                }
                else
                if (url.ToUpper().StartsWith("/PICTURE/"))
                {
                    List <FileInfo> Jpegs = FileManager.EnumerateAllJPGs(GalleryServer.Properties.Settings.Default.PicturesPath);
                    // remove the /picture thingie...
                    url = url.Remove(0, 9);

                    foreach (FileInfo jpg in Jpegs)
                    {
                        if (url.ToUpper().StartsWith(jpg.Name + jpg.LastWriteTime.Ticks))
                        {
                            // we've found the picture, now we determine if we want the picture or the thumbnail...
                            if (url.ToUpper().EndsWith("/THUMBNAIL"))
                            {
                                // it's the thumbnail...
                                byte[] ThumbnailData = ThumbCache.RetrieveThumbnail(jpg);
                                Stream stream        = new MemoryStream(ThumbnailData);
                                long   left          = ThumbnailData.Length;
                                long   bytesSent     = 0;
                                writeSuccess(left, "image/jpeg");

                                BufferedStream bs = new BufferedStream(stream);

                                // for performance reasons...
                                int read;
                                while (left > 0 && (read = bs.Read(bytes, 0, (int)Math.Min(left, bytes.Length))) != 0)
                                {
                                    ns.Write(bytes, 0, read);
                                    bytesSent = bytesSent + read;
                                    left     -= read;
                                }
                                ns.Flush();
                                bs.Close();
                                stream.Close();
                                return;
                            }
                            else
                            {
                                #region throw the original file out...
                                FileStream     fs        = null;
                                BufferedStream bs        = null;
                                long           bytesSent = 0;
                                // Open the file for binary transfer
                                fs = new FileStream(jpg.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                                long left = jpg.Length;
                                writeSuccess(left, "image/jpeg");
                                bs = new BufferedStream(fs);

                                // for performance reasons...
                                int read;
                                while (left > 0 && (read = bs.Read(bytes, 0, (int)Math.Min(left, bytes.Length))) != 0)
                                {
                                    ns.Write(bytes, 0, read);
                                    bytesSent = bytesSent + read;
                                    left     -= read;
                                }
                                ns.Flush();
                                bs.Close();
                                fs.Close();
                                return;

                                #endregion
                            }
                        }
                    }
                }
                else
                {
                    #region File request (everything else...)

                    #region default page
                    if (url == "/")
                    {
                        url = "/index.html";
                    }
                    #endregion

                    // check if we have some querystring parameters
                    if (url.Contains("?"))
                    {
                        // yes, remove everything after the ? from the url but save it to querystring
                        querystring = url.Substring(url.IndexOf('?') + 1);
                        url         = url.Remove(url.IndexOf('?'));
                    }

                    // Replace the forward slashes with back-slashes to make a file name
                    string filename = url.Replace('/', Path.DirectorySeparatorChar);                     //you have different path separators in unix and windows
                    try
                    {
                        // Construct a filename from the doc root and the filename
                        FileInfo file = new FileInfo(docRootFile + filename);
                        // Make sure they aren't trying in funny business by checking that the
                        // resulting canonical name of the file has the doc root as a subset.
                        filename = file.FullName;
                        if (!filename.StartsWith(docRootFile.FullName))
                        {
                            writeForbidden();
                        }
                        else
                        {
                            FileStream     fs        = null;
                            BufferedStream bs        = null;
                            long           bytesSent = 0;
                            bool           resumed   = false;

                            try
                            {
                                if (filename.EndsWith(".log"))
                                {
                                    // now give the user a 403 and break...
                                    writeForbidden();
                                    ns.Flush();
                                }
                                else
                                if (filename.EndsWith(".html") | (filename.EndsWith(".htm")))
                                {
                                    //
                                    String Output = File.ReadAllText(filename);

                                    int left = new UTF8Encoding().GetByteCount(Output);
                                    writeSuccess(left, "text/html");
                                    byte[] buffer = new UTF8Encoding().GetBytes(Output);
                                    ns.Write(buffer, 0, left);
                                    ns.Flush();
                                }
                                else
                                {
                                    // Open the file for binary transfer
                                    fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                                    long left = file.Length;
                                    bool isThisARecordingRecording = false;

                                    #region different mime-type-handling
                                    switch (getFileExtension(filename))
                                    {
                                    case ".css":
                                        writeSuccess(left, "text/css");
                                        break;

                                    case ".gif":
                                        writeSuccess(left, "image/gif");
                                        break;

                                    case ".png":
                                        writeSuccess(left, "image/png");
                                        break;

                                    case ".jpg":
                                        writeSuccess(left, "image/jpeg");
                                        break;

                                    case ".jpeg":
                                        writeSuccess(left, "image/jpeg");
                                        break;

                                    case ".ico":
                                        writeSuccess(left, "image/ico");
                                        break;

                                    default:
                                        // Write the content length and the success header to the stream; it's binary...so treat it as binary
                                        writeSuccess(left, "application/octet-stream");
                                        break;
                                    }
                                    #endregion

                                    // Copy the contents of the file to the stream, ensure that we never write
                                    // more than the content length we specified.  Just in case the file somehow
                                    // changes out from under us, although I don't know if that is possible.
                                    bs   = new BufferedStream(fs);
                                    left = file.Length;

                                    // for performance reasons...
                                    int read;
                                    while (left > 0 && (read = bs.Read(bytes, 0, (int)Math.Min(left, bytes.Length))) != 0)
                                    {
                                        ns.Write(bytes, 0, read);
                                        bytesSent = bytesSent + read;
                                        left     -= read;
                                    }
                                    ns.Flush();
                                    bs.Close();
                                    fs.Close();
                                }
                            }
                            catch (Exception e)
                            {
                                ConsoleOutputLogger.WriteLineToScreenOnly("[FEHLER@HTTP] " + e.Message);
                                try
                                {
                                    writeFailure();
                                }
                                catch (Exception)
                                {
                                    ConsoleOutputLogger.WriteLineToScreenOnly("[FEHLER@HTTP] connection lost to client");
                                }
                                if (bs != null)
                                {
                                    bs.Close();
                                }
                                if (bs != null)
                                {
                                    fs.Close();
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        ConsoleOutputLogger.WriteLineToScreenOnly("[FEHLER@HTTP] " + e.Message);
                        writeFailure();
                    }
                    #endregion
                }
            }
            catch (Exception e)
            {
                ConsoleOutputLogger.WriteLineToScreenOnly("[FEHLER@HTTP] " + e.Message + " ## " + e.StackTrace);
                writeFailure();
            }
        }