public override List <Field> ParseContent(object Content, ReadoutType Types, DateTime From, DateTime To)
        {
            List <Field>      Result = new List <Field>();
            string            s      = Content as string;
            PhysicalMagnitude M;

            if (!string.IsNullOrEmpty(s) && PhysicalMagnitude.TryParse(s, out M))
            {
                try
                {
                    Result.Add(new FieldNumeric(this, this.FieldName, 0, null, DateTime.Now, M.Value, M.NrDecimals, M.Unit, ReadoutType.MomentaryValues, FieldStatus.AutomaticReadout, string.Empty));
                }
                catch (Exception ex)
                {
                    this.LogError(ex.Message);
                }
            }
            else if (s != null)
            {
                this.LogError(String(45, "Unable to parse physical magnitude value: %0%", s));
            }
            else
            {
                this.LogError(String(46, "Unable to parse physical magnitude value."));
            }

            return(Result);
        }
Example #2
0
        private void AddField(List <Field> Fields, string Value, string FieldName, EditableObject Node, DateTime TP)
        {
            double            d;
            bool              b;
            int               NrDec;
            long              l;
            DateTime          TP2;
            Duration          D;
            Guid              Guid;
            PhysicalMagnitude M;

            if (long.TryParse(Value, out l))
            {
                Fields.Add(new FieldNumeric(Node, FieldName, 0, null, TP, l, ReadoutType.MomentaryValues, FieldStatus.AutomaticReadout, string.Empty));
            }
            else if (XmlUtilities.TryParseDouble(Value, out d, out NrDec))
            {
                Fields.Add(new FieldNumeric(Node, FieldName, 0, null, TP, d, NrDec, string.Empty, ReadoutType.MomentaryValues, FieldStatus.AutomaticReadout, string.Empty));
            }
            else if (XmlUtilities.TryParseBoolean(Value, out b))
            {
                Fields.Add(new FieldBoolean(Node, FieldName, 0, null, TP, b, ReadoutType.MomentaryValues, FieldStatus.AutomaticReadout, string.Empty));
            }
            else if (XmlUtilities.TryParseDateTimeXml(Value, out TP2))
            {
                Fields.Add(new FieldDateTime(Node, FieldName, 0, null, TP, TP2, ReadoutType.MomentaryValues, FieldStatus.AutomaticReadout, string.Empty));
            }
            else if ((TP2 = Web.ParseDateTimeRfc822(Value)) != DateTime.MinValue)
            {
                Fields.Add(new FieldDateTime(Node, FieldName, 0, null, TP, TP2, ReadoutType.MomentaryValues, FieldStatus.AutomaticReadout, string.Empty));
            }
            else if (XmlUtilities.TryParseDuration(Value, out D))
            {
                try
                {
                    Fields.Add(new FieldTimeSpan(Node, FieldName, 0, null, TP, D.ToTimeSpan(), ReadoutType.MomentaryValues, FieldStatus.AutomaticReadout, string.Empty));
                }
                catch (Exception ex)
                {
                    this.LogError(ex.Message);
                }
            }
            else if (XmlUtilities.TryParseGuid(Value, out Guid))
            {
                Fields.Add(new FieldString(Node, FieldName, 0, null, TP, Value, ReadoutType.MomentaryValues, FieldStatus.AutomaticReadout, string.Empty));
            }
            else if (long.TryParse(Value, System.Globalization.NumberStyles.HexNumber, null, out l))
            {
                Fields.Add(new FieldString(Node, FieldName, 0, null, TP, Value, ReadoutType.MomentaryValues, FieldStatus.AutomaticReadout, string.Empty));
            }
            else if (PhysicalMagnitude.TryParse(Value, out M))
            {
                Fields.Add(new FieldNumeric(Node, FieldName, 0, null, TP, M.Value, M.NrDecimals, M.Unit, ReadoutType.MomentaryValues, FieldStatus.AutomaticReadout, string.Empty));
            }
            else
            {
                Fields.Add(new FieldString(Node, FieldName, 0, null, TP, Value, ReadoutType.MomentaryValues, FieldStatus.AutomaticReadout, string.Empty));
            }
        }
        private void Scan(object Parameter)
        {
            object[] P            = (object[])Parameter;
            User     User         = (User)P[0];
            Language UserLanguage = (Language)P[1];

            try
            {
                CoapEndpoint       Endpoint = this.Endpoint;
                CoapResponse       Response;
                LinkFormatDocument LinkDoc;

                Response = Endpoint.GET(true, this.Host, this.Port, ".well-known/core", string.Empty, 20000);

                LinkDoc = Response.Response as LinkFormatDocument;
                if (LinkDoc == null)
                {
                    throw new Exception(CoapNode.String(28, "Unexpected response returned."));
                }

                foreach (Link Link in LinkDoc.Links)
                {
                    Uri              Uri = new Uri(Link.Url);
                    string[]         Parts = Uri.PathAndQuery.Split('/');
                    EditableTreeNode Node = this;
                    int              i, c = Parts.Length;
                    string           Segment;
                    object           Obj;
                    CoapContent      Content;
                    CoapFolder       Folder;
                    CoapNode         Found;
                    StringBuilder    Path = null;

                    for (i = 0; i < c - 1; i++)
                    {
                        Segment = Parts[i];
                        if (string.IsNullOrEmpty(Segment))
                        {
                            continue;
                        }

                        if (i <= 1 && Segment == ".well-known")
                        {
                            break;
                        }

                        Found = null;

                        if (Path == null)
                        {
                            Path = new StringBuilder();
                        }
                        else
                        {
                            Path.Append('/');
                        }

                        Path.Append(Segment);

                        foreach (EditableTreeNode Child in Node.AllChildren)
                        {
                            if ((Folder = Child as CoapFolder) != null && Folder.Folder == Segment)
                            {
                                Found = Folder;
                                break;
                            }
                        }

                        if (Found == null)
                        {
                            Parameters Param = EditableObject.GetParametersForNewObject(typeof(CoapFolder), true, User.AllPrivileges);
                            Param[Clayster.Library.Meters.Node.DefaultIdParameterId] = this.Id + "/" + Path.ToString();
                            Param["folder"] = Segment;

                            Found = (CoapNode)EditableObject.CreateNewObject(typeof(CoapFolder), Param, UserLanguage, true, Topology.Source, User);
                            Node.Add(Found);
                        }

                        Node = Found;
                    }

                    Segment = Parts[c - 1];
                    if (!string.IsNullOrEmpty(Segment))
                    {
                        Found = null;

                        if (Path == null)
                        {
                            Path = new StringBuilder();
                        }
                        else
                        {
                            Path.Append('/');
                        }

                        Path.Append(Segment);

                        foreach (EditableTreeNode Child in Node.AllChildren)
                        {
                            if ((Content = Child as CoapContent) != null && Content.Resource == Segment)
                            {
                                Found = Content;
                                break;
                            }
                        }

                        if (Found == null)
                        {
                            try
                            {
                                Type T = null;

                                Response = Endpoint.GET(true, this.Host, this.Port, Path.ToString(), string.Empty, 20000);
                                Obj      = Response.Response;

                                if (Obj is string)
                                {
                                    string            s = (string)Obj;
                                    PhysicalMagnitude M;
                                    Duration          D;
                                    DateTime          TP;
                                    double            d;
                                    int  NrDec;
                                    bool b;

                                    if (XmlUtilities.TryParseBoolean(s, out b))
                                    {
                                        T = typeof(CoapBoolean);
                                    }
                                    else if (XmlUtilities.TryParseDuration(s, out D))
                                    {
                                        T = typeof(CoapDuration);
                                    }
                                    else if (XmlUtilities.TryParseDateTimeXml(s, out TP) || (TP = Web.ParseDateTimeRfc822(s)) != DateTime.MinValue)
                                    {
                                        T = typeof(CoapDateTime);
                                    }
                                    else if (XmlUtilities.TryParseDouble(s, out d, out NrDec))
                                    {
                                        T = typeof(CoapNumber);
                                    }
                                    else if (PhysicalMagnitude.TryParse(s, out M))
                                    {
                                        T = typeof(CoapPhysicalMagnitude);
                                    }
                                    else
                                    {
                                        try
                                        {
                                            TurtleDocument TurtleDoc = new TurtleDocument((string)Obj, "coap://" + this.Host + ":" + this.Port.ToString() + "/" + Path.ToString());
                                        }
                                        catch (Exception)
                                        {
                                            T = typeof(CoapString);
                                        }
                                    }
                                }
                                else if (Obj is XmlDocument)
                                {
                                    XmlDocument Doc = (XmlDocument)Obj;

                                    if (Doc.DocumentElement.LocalName == "FieldsRoot" && Doc.DocumentElement.NamespaceURI == "http://clayster.com/schema/Fields/v1.xsd")
                                    {
                                        T = typeof(CoapFields);
                                    }
                                    else if ((Doc.DocumentElement.LocalName == "fields" || Doc.DocumentElement.LocalName == "failure") && Doc.DocumentElement.NamespaceURI == "urn:xmpp:iot:sensordata")
                                    {
                                        T = typeof(CoapXep0323);
                                    }
                                    else
                                    {
                                        T = typeof(CoapXml);
                                    }
                                }
                                else if (Obj is LinkFormatDocument)
                                {
                                    // Ignore
                                }
                                else if (Obj is byte[])
                                {
                                    // Ignore
                                }
                                else
                                {
                                    T = typeof(CoapJson);
                                }

                                if (T != null)
                                {
                                    Parameters Param = EditableObject.GetParametersForNewObject(T, true, User.AllPrivileges);
                                    Param[Clayster.Library.Meters.Node.DefaultIdParameterId] = this.Id + "/" + Path.ToString();
                                    Param["resource"] = Segment;

                                    if (Param.ContainsParameter("fieldName"))
                                    {
                                        Param["fieldName"] = Segment;
                                    }

                                    Found = (CoapNode)EditableObject.CreateNewObject(T, Param, UserLanguage, true, Topology.Source, User);
                                    Node.Add(Found);
                                }
                            }
                            catch (Exception ex)
                            {
                                this.LogException(ex);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.LogException(ex);
            }
            finally
            {
                this.scanning = false;
            }
        }
Example #4
0
        private static void MonitorMqtt()
        {
            UTF8Encoding Encoder        = new UTF8Encoding(false);
            bool         HasLightValue  = false;
            bool         HasMotionValue = false;
            MqttClient   Client         = null;

            try
            {
                WaitHandle[] Handles = new WaitHandle[] { updateLeds, updateAlarm };

                while (executing)
                {
                    try
                    {
                        if (Client == null)
                        {
                            Client = new MqttClient("iot.eclipse.org", MqttClient.DefaultPort, "LearningIoTController", string.Empty, false);
                            //Client.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal));

                            Client.Open();
                            Client.CONNECT(20, true);

                            Client.OnDataPublished += (Sender, e) =>
                            {
                                string Topic = e.Topic;
                                if (!Topic.StartsWith("Clayster/LearningIoT/Sensor/"))
                                {
                                    return;
                                }

                                string            s = System.Text.Encoding.UTF8.GetString(e.Data);
                                PhysicalMagnitude Magnitude;
                                bool b;

                                Topic = Topic.Substring(28);
                                switch (Topic)
                                {
                                case "Light":
                                    if (PhysicalMagnitude.TryParse(s, out Magnitude) && Magnitude.Unit == "%" && Magnitude.Value >= 0 && Magnitude.Value <= 100)
                                    {
                                        lightPercent = Magnitude.Value;
                                        if (!HasLightValue)
                                        {
                                            HasLightValue = true;
                                            if (HasMotionValue)
                                            {
                                                hasValues = true;
                                            }
                                        }

                                        CheckControlRules();
                                    }
                                    break;

                                case "Motion":
                                    if (!string.IsNullOrEmpty(s) && XmlUtilities.TryParseBoolean(s, out b))
                                    {
                                        motion = b;

                                        if (!HasMotionValue)
                                        {
                                            HasMotionValue = true;
                                            if (HasLightValue)
                                            {
                                                hasValues = true;
                                            }
                                        }

                                        CheckControlRules();
                                    }
                                    break;
                                }
                            };

                            Client.SUBSCRIBE(new KeyValuePair <string, MqttQoS> ("Clayster/LearningIoT/Sensor/#", MqttQoS.QoS1_Acknowledged));
                            Log.Information("Listening on MQTT topic Clayster/LearningIoT/Sensor @ ", EventLevel.Minor, Client.Host + ":" + Client.PortNumber.ToString());
                        }

                        switch (WaitHandle.WaitAny(Handles, 1000))
                        {
                        case 0:                                 // Update LEDS
                            int i;

                            lock (synchObject)
                            {
                                i = lastLedMask;
                            }

                            Client.PUBLISH("Clayster/LearningIoT/Actuator/do", Encoder.GetBytes(i.ToString()), MqttQoS.QoS1_Acknowledged, true);

                            // Just to synchronize with the other topics.
                            for (int j = 1; j <= 8; j++)
                            {
                                Client.PUBLISH("Clayster/LearningIoT/Actuator/do" + j.ToString(), Encoder.GetBytes((i & 1).ToString()), MqttQoS.QoS1_Acknowledged, true);
                                i >>= 1;
                            }
                            break;

                        case 1:                                 // Update Alarm
                            bool b;

                            lock (synchObject)
                            {
                                b = lastAlarm.Value;
                            }

                            Client.PUBLISH("Clayster/LearningIoT/Actuator/ao", Encoder.GetBytes(b ? "1" : "0"), MqttQoS.QoS1_Acknowledged, true);

                            if (b)
                            {
                                Thread T = new Thread(SendAlarmMail);
                                T.Priority = ThreadPriority.BelowNormal;
                                T.Name     = "SendAlarmMail";
                                T.Start();
                            }
                            break;

                        default:                                        // Timeout
                            CheckSubscriptions(30);
                            break;
                        }
                    } catch (ThreadAbortException)
                    {
                        // Don't log. Exception will be automatically re-raised.
                    } catch (Exception ex)
                    {
                        Log.Exception(ex);

                        if (Client != null)
                        {
                            Client.Dispose();
                            Client = null;
                        }

                        Thread.Sleep(5000);
                    }
                }
            } finally
            {
                Client.Dispose();
            }
        }