Exemplo n.º 1
0
        //------------------------------------------------------------------------------------------------------------------------
        public override void OnThingActivated(ThingKey thingKey)
        {
            DebugEx.TraceLog($"Thing Activated {thingKey}");

            // Check when we activate periodic
            if (things["Periodic"]?.ThingKey == thingKey)
            {
                DebugEx.TraceLog("Periodic Thing Activated");

                // Dispose old task
                PeriodicRunning = false;
                PeriodicTask?.Wait();
                PeriodicTask?.Dispose();

                // Create a new cancellation source
                PeriodicRunning = true;

                //start alive task
                PeriodicTask = TaskEx.RunSafe(() =>
                {
                    while (!IsDisposed && PeriodicRunning)
                    {
                        // Send timestamp if we are connected
                        if (_CloudConnected &&
                            (Ports?.ContainsKey("periodicTimestamp") ?? false))
                        {
                            SetPortState(Ports["periodicTimestamp"].PortKey, DateTime.UtcNow.ToStringInvariant());
                        }
                        Thread.Sleep(Period);
                    }
                });
            }
        }
Exemplo n.º 2
0
 //------------------------------------------------------------------------------------------------------------------------
 protected override void _flush(int Timeout)
 {
     TaskEx.RunSafe(() =>
     {
         try { streamIn?.Flush(); } catch { }
         try { streamOut?.Flush(); } catch { }
     }).Wait(Timeout);
 }
Exemplo n.º 3
0
        private void _InitFlicClient()
        {
            if (_flicClient == null)
            {
                DebugEx.TraceLog("FlicClient is null, Find it!!!!");
                while (true)
                {
                    try
                    {
                        _flicClient = FlicClient.Create(ActiveCfg.FlicDaemonHostname, ActiveCfg.FlicDaemonPort);
                        DebugEx.TraceLog("Connection to FlicClient successful");
                        if (_flicClient != null)
                        {
                            _flicClient.GetInfo(
                                (bluetoothControllerState, myBdAddr, myBdAddrType, maxPendingConnections, maxConcurrentlyConnectedButtons,
                                 currentPendingConnections, currentlyNoSpaceForNewConnection, verifiedButtons) =>
                            {
                                DebugEx.TraceLog("Bluetooth controller status: " + bluetoothControllerState.ToString());
                                foreach (var bdAddr in verifiedButtons)
                                {
                                    GotButton(bdAddr);
                                }
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugEx.TraceErrorException(ex);
                        Thread.Sleep(500);
                        continue;
                    }
                    break;
                }

                _flicClient.BluetoothControllerStateChange += (o, args) =>
                {
                    DebugEx.TraceLog("Bluetooth controller status: " + args.State.ToString());
                };

                _flicClient.NewVerifiedButton += (o, args) =>
                {
                    DebugEx.TraceLog("new NewVerifiedButtonEvent");
                    GotButton(args.BdAddr);
                };

                TaskEx.RunSafe(() =>
                {
                    _flicClient.HandleEvents(); // HandleEvents returns when the socket has disconnected for any reason
                    DebugEx.TraceError("BLE connection lost");
                    OnBLEDisconnected();
                });
            }
        }
Exemplo n.º 4
0
        //------------------------------------------------------------------------------------------------------------------------
        public override void OnTransportConnected(string msg)
        {
            base.OnTransportConnected(msg);
            _CloudConnected = true;


            // Send the connection timestamp
            TaskEx.RunSafe(() =>
            {
                // Send the report 10Second after connection to avoid the timing issue with active port key
                // TODO: Fix this case !!!!
                Thread.Sleep(10000);
                if (Ports?.ContainsKey("connectionTimestamp") ?? false)
                {
                    SetPortState(new List <TupleS <string, string> >()
                    {
                        new TupleS <string, string>(Ports["connectionTimestamp"].PortKey, DateTime.UtcNow.ToStringInvariant()),
                        new TupleS <string, string>(Ports["isTransportConnected"].PortKey, "True"),
                    });
                }
            });
        }
Exemplo n.º 5
0
        public SimpleActionResult Connect(string RemoteHost, int RemotePort, bool Secure, string CertificateServerName = null)
#endif
        {
            if (SupportedChannelSerializationModes.HasFlag(ChannelSerializationMode.MessagePack))
            {
                DebugEx.Assert(MsgPack != null, "MessagePack serializer not provided");
            }

            //init results
            var result = new SimpleActionResult()
            {
                IsSuccessful = false,
                Message      = "",
            };

            //check state
            if (_State != ChannelStates.Closed && _State != ChannelStates.Initializing)
            {
                result.Message = "Connected or connection already in progress";
                return(result);
            }

            //inform
            DebugEx.TraceLog($"YPChannel ({Name}) connecting to {RemoteHost}:{RemotePort}");

            //reset state
            if (_State != ChannelStates.Initializing)
            {
                Reset();
            }

            //keep connection parameters
            this.Secure = Secure;
            this.CertificateServerName = CertificateServerName;
#if NETFX
            this.CustomCertificates = CustomCertificates;
#endif
            try
            {
                //connect socket
                var connTask = TaskEx.RunSafe(() => _sockConnection(RemoteHost, RemotePort));
                connTask.Wait();
                //if (!connTask.Wait(SockConnectionTimeout))
                //throw new Exception("Socket connection timeout");
                var res = connTask.Result;
                if (!res)
                {
                    throw new Exception(result.Message);
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }

                try { Close("YPChannel (" + (Name) + ") : Sock connection attempt failed, " + ex.Message); } catch { }
#if NETFX
                try { _sock?.Close(); } catch { }
#endif
                try { _sock?.Dispose(); } catch { }
                return(result);
            }

            //start heartbeat
            Start();

            //hook for system close
            Channel.OnSystemShutDownRequest?.Add(Yodiwo.WeakAction <object> .Create(_OnSystemShutDownRequestHandler));

            //wait for negotiation finish
            while (State == ChannelStates.Initializing || State == ChannelStates.Negotiating)
            {
                Thread.Sleep(200);
            }

            //set message
            if (State != ChannelStates.Open)
            {
                result.Message = "Could not open channel (Negotiation Failed)";
            }

            //return state
            result.IsSuccessful = State == ChannelStates.Open;
            if (result.IsSuccessful && result.Message == "")
            {
                result.Message = "Connection Established (Channel Openned)";
            }

            return(result);
        }
Exemplo n.º 6
0
        //------------------------------------------------------------------------------------------------------------------------
        public void Stop(bool CloseAllChannels = false)
        {
            try
            {
                lock (this)
                {
                    //close all channels
                    if (CloseAllChannels)
                    {
                        var channelsToClose = _Channels.ToArray();
                        TaskEx.RunSafe(() =>
                        {
                            var po = new ParallelOptions()
                            {
                                MaxDegreeOfParallelism = 8
                            };

                            Parallel.ForEach(channelsToClose, po, c =>
                            {
                                { try { c.Close("Server stopped"); } catch (Exception ex) { DebugEx.TraceErrorException(ex, "Error while closing channel"); } };
                            });
                        });
                    }

                    //update flag
                    if (!_IsRunning)
                    {
                        return;
                    }
                    else
                    {
                        _IsRunning = false;
                    }

                    //close my socket
                    try
                    {
                        if (sock != null)
                        {
#if NETFX
                            try { sock.Close(); } catch { }
#endif
                            try { sock.Dispose(); } catch { }
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugEx.TraceErrorException(ex);
                    }
                    sock = null;

                    //wait for task finish
#if NETFX
                    PortListener?.Join(1000);
#elif UNIVERSAL
                    PortListener?.Wait(1000);
#endif
                    PortListener = null;
                }
            }
            catch (Exception ex)
            {
                DebugEx.Assert(ex, "YPChannel Server Stop() failed");
            }
        }
Exemplo n.º 7
0
        //------------------------------------------------------------------------------------------------------------------------
        protected override void onClose(string Message)
        {
            try
            {
                base.onClose(Message);

                //close all
                try
                {
                    if (streamIn != null)
                    {
#if NETFX
                        TaskEx.RunSafe(streamIn.Close, AssertException: false)?.Wait(1000);
#endif
                        TaskEx.RunSafe(streamIn.Dispose, AssertException: false)?.Wait(1000);
                    }
                }
                catch { }

                try
                {
                    if (streamOut != null)
                    {
#if NETFX
                        TaskEx.RunSafe(streamOut.Close, AssertException: false)?.Wait(1000);
#endif
                        TaskEx.RunSafe(streamOut.Dispose, AssertException: false)?.Wait(1000);
                    }
                }
                catch { }

#if NETFX
                try
                {
                    if (netstream != null)
                    {
                        TaskEx.RunSafe(netstream.Close, AssertException: false)?.Wait(1000);
                        TaskEx.RunSafe(netstream.Dispose, AssertException: false)?.Wait(1000);
                    }
                }
                catch { }
#endif
                try
                {
#if NETFX
                    if (_sock?.Connected == true)
                    {
                        TaskEx.RunSafe(() => _sock?.Disconnect(false), AssertException: false)?.Wait(1000);
                    }

                    TaskEx.RunSafe(() => _sock?.Close(3), AssertException: false)?.Wait(5000);
#endif
                    TaskEx.RunSafe(() => _sock?.Dispose(), AssertException: false)?.Wait(1000);
                }
                catch { }

                //null them
                streamIn  = null;
                streamOut = null;
#if NETFX
                netstream = null;
#endif
                _sock = null;
            }
            catch (Exception ex) { DebugEx.Assert(ex, "YPC (" + Name + ") Exception while disconnecting"); }
        }