Beispiel #1
0
        /// <summary>
        ///     取得Socket对象
        /// </summary>
        /// <param name="type"></param>
        /// <param name="socket"></param>
        /// <returns></returns>
        private static bool GetSocket(string type, out RequestSocket socket)
        {
            try
            {
                lock (Publishers)
                {
                    if (Publishers.TryGetValue(type, out socket))
                    {
                        return(true);
                    }
                    var config = StationProgram.GetConfig(type);
                    if (config == null)
                    {
                        StationProgram.WriteLine($"【{type}】connect error =>无法拉取配置");
                        return(false);
                    }

                    socket = new RequestSocket();
                    socket.Options.Identity =
                        StationProgram.Config.StationName.ToAsciiBytes(); //RandomOperate.Generate(8).ToAsciiBytes();
                    socket.Options.ReconnectInterval = new TimeSpan(0, 0, 0, 0, 200);
                    socket.Connect(config.OutAddress);
                    Publishers.Add(type, socket);
                }
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                StationProgram.WriteLine($"【{type}】connect error =>连接时发生异常:{e}");
                socket = null;
                return(false);
            }

            return(true);
        }
Beispiel #2
0
        internal async void HandleMetadata(SongMetadata songMetadata, StationStream currentStream)
        {
            if (songMetadata == null || songMetadata.IsUnknownMetadata)
            {
                SetCurrentMetadataToUnknown();
                return;
            }

            await metadataLock.WaitAsync();

            try
            {
                CurrentStation = await NepApp.Stations.GetStationByNameAsync(currentStream.ParentStation);

                StationProgram currentProgram = null;
                if (IsHostedStationProgramBeginning(songMetadata, CurrentStation, out currentProgram))
                {
                    //we're tuning into a hosted radio program. this may be a DJ playing remixes, for example.

                    ActivateStationProgrammingMode(songMetadata, currentStream, currentProgram);

                    //block programs are handled differently.
                }
                else
                {
                    //we're tuned into regular programming/music

                    HandleStationSongMetadata(songMetadata, currentStream, CurrentStation);
                }
            }
            finally
            {
                metadataLock.Release();
            }
        }
 private bool Request(string msg, ref int retry)
 {
     if (++retry > 5)
     {
         LogRecorder.Error($"数据事件服务(EntityEvent)无法连接!\r\n{msg}");
         return(false);
     }
     try
     {
         lock (this)
         {
             _socket.Request(msg);
         }
         return(true);
     }
     catch (Exception e)
     {
         LogRecorder.Exception(e);
         StationProgram.WriteLine($"【EntityEvent】publish error =>{e.Message}");
         retry++;
         Thread.Sleep(10);
         CreateSocket();
         return(Request(msg, ref retry));
     }
 }
Beispiel #4
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Hello ZeroNet");

            StationProgram.RegisteStation(new RemoteLogRecorder());
            StationProgram.Initialize();
            StationProgram.RunConsole();
        }
Beispiel #5
0
        /// <summary>
        /// 命令轮询
        /// </summary>
        /// <returns></returns>
        private void PollTask()
        {
            StationProgram.WriteLine($"【{StationName}】poll start");
            var timeout = new TimeSpan(0, 0, 5);

            _inPoll = true;
            while (RunState == StationState.Run)
            {
                try
                {
                    if (!_socket.TryReceiveFrameString(timeout, out var title, out var more) || !more)
                    {
                        continue;
                    }
                    if (!_socket.TryReceiveFrameBytes(out var description, out more) || !more)
                    {
                        continue;
                    }
                    PublishItem item = new PublishItem
                    {
                        Title = title
                    };
                    int idx = 1;
                    while (more)
                    {
                        if (!_socket.TryReceiveFrameString(out var val, out more))
                        {
                            continue;
                        }
                        switch (description[idx++])
                        {
                        case ZeroHelper.zero_pub_sub:
                            item.SubTitle = val;
                            break;

                        case ZeroHelper.zero_pub_publisher:
                            item.Station = val;
                            break;

                        case ZeroHelper.zero_arg:
                            item.Content = val;
                            break;
                        }
                    }
                    _items.Push(item);
                }
                catch (Exception e)
                {
                    StationProgram.WriteLine($"【{StationName}】poll error{e.Message}...");
                    LogRecorder.Exception(e);
                    RunState = StationState.Failed;
                }
            }
            _inPoll = false;
            StationProgram.WriteLine($"【{StationName}】poll stop");
            _items.Save(CacheFileName);
            CloseSocket();
        }
Beispiel #6
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Hello ZeroNet");

            StationProgram.RegisteStation(new PerformanceCounter());
            StationProgram.RegisteStation(new RuntimeWaring());
            StationProgram.Initialize();
            StationProgram.RunConsole();
        }
Beispiel #7
0
        /// <summary>
        /// 查找API
        /// </summary>
        /// <param name="assembly"></param>
        public void FindSubs(Assembly assembly)
        {
            var types = assembly.GetTypes().Where(p => p.IsSubclassOf(typeof(SubStation))).ToArray();

            foreach (var type in types)
            {
                StationProgram.RegisteStation(type.CreateObject() as SubStation);
            }
        }
 /// <summary>
 /// 构造
 /// </summary>
 public ZeroEntityEventProxy()
 {
     _config = StationProgram.GetConfig("EntityEvent");
     if (_config == null)
     {
         throw new Exception("无法拉取配置");
     }
     _socket = new RequestSocket();
     CreateSocket();
 }
Beispiel #9
0
 /// <summary>
 /// 初始化
 /// </summary>
 public static void Initialize()
 {
     // 日志支持
     //Agebull.Common.Logging.LogRecorder.GetRequestIdFunc = () => ApiContext.RequestContext.RequestId;.
     LogRecorder.Initialize(new RemoteRecorder());
     AppConfig.Initialize(Path.Combine(Startup.Configuration["contentRoot"], "route_config.json"));
     StationProgram.Run();
     RouteChahe.Flush();
     RuntimeWaring.Flush();
     RouteCommand.ZeroFlush();
     //Datas = new List<RouteData>();
 }
Beispiel #10
0
        private bool FilterStationBlockPrograms(StationProgram program)
        {
            if (program.Style != StationProgramStyle.Block)
            {
                return(false);
            }

            return(program.TimeListings.Any(listing =>
            {
                return listing.Time.TimeOfDay < DateTime.Now.TimeOfDay && DateTime.Now.TimeOfDay < listing.EndTime.TimeOfDay && listing.Day == DateTime.Now.DayOfWeek;
            }));
        }
Beispiel #11
0
 /// <summary>
 /// 执行
 /// </summary>
 /// <param name="station"></param>
 public static void Run(SubStation station)
 {
     station.Close();
     station.Config = StationProgram.GetConfig(station.StationName);
     if (station.Config == null)
     {
         StationProgram.WriteLine($"{station.StationName} not find,try install...");
         StationProgram.InstallApiStation(station.StationName);
         return;
     }
     station.Run();
 }
Beispiel #12
0
        private void ActivateStationProgrammingMode(SongMetadata songMetadata, StationStream currentStream, StationProgram currentProgram)
        {
            StationRadioProgramStarted?.Invoke(this, new NepAppStationProgramStartedEventArgs()
            {
                RadioProgram = currentProgram,
                Metadata     = songMetadata,
                Station      = currentStream?.ParentStation
            });

            CurrentProgram = currentProgram;
            SetCurrentMetadataToUnknownInternal(currentProgram.Name);
        }
Beispiel #13
0
        /// <summary>
        ///     远程调用
        /// </summary>
        /// <returns></returns>
        private string CallZero()
        {
            var values = new Dictionary <string, string>();

            //参数解析
            foreach (var query in Request.Query.Keys)
            {
                if (!values.ContainsKey(query))
                {
                    values.Add(query, Request.Query[query]);
                }
            }

            if (Data.HttpMethod == "POST")
            {
                if (Request.ContentLength > 0)
                {
                    foreach (var form in Request.Form.Keys)
                    {
                        if (!values.ContainsKey(form))
                        {
                            values.Add(form, Request.Form[form]);
                        }
                    }
                }
            }

            LogRecorder.BeginStepMonitor("内部Zero调用");
            LogRecorder.MonitorTrace($"Station:{Data.HostName}");
            LogRecorder.MonitorTrace($"Command:{Data.ApiName}");

            // 远程调用状态
            try
            {
                Data.ResultMessage = StationProgram.Call(Data.HostName, Data.ApiName, JsonConvert.SerializeObject(values));
            }
            catch (Exception ex)
            {
                LogRecorder.Exception(ex);
                LogRecorder.MonitorTrace($"发生异常:{ex.Message}");
                Data.ResultMessage = RouteRuntime.NetworkError;
                Data.Status        = RouteStatus.RemoteError;
            }
            finally
            {
                LogRecorder.MonitorTrace(Data.ResultMessage);
                LogRecorder.EndStepMonitor();
            }

            return(Data.ResultMessage);
        }
Beispiel #14
0
        /// <summary>
        /// 心跳
        /// </summary>
        /// <returns></returns>
        public static void ApiTest()
        {
            var request = new RequestSocket();
            var config  = StationProgram.GetConfig(station);

            try
            {
                int id = 1;
                request.Options.Identity          = RandomOperate.Generate(8).ToAsciiBytes();
                request.Options.ReconnectInterval = new TimeSpan(0, 0, 0, 0, 200);
                request.Connect(config.OutAddress);
                //for (int i = 0; i < 1024; i++)//
                {
                    Console.WriteLine("request...");
                    DateTime s = DateTime.Now;
                    request.SendFrame(api, true);
                    request.SendFrame($"{++id}", true);
                    request.SendFrame("{}", true);
                    if (!request.TrySendFrame(new TimeSpan(0, 0, 0, 3), argument))
                    {
                        Console.WriteLine("*  3");
                        return;
                    }
                    bool more = true;
                    //收完消息
                    while (more)
                    {
                        string result;
                        if (request.TryReceiveFrameString(new TimeSpan(0, 0, 0, 500), out result, out more))
                        {
                            Console.WriteLine(result);
                            continue;
                        }
                        Console.WriteLine("*  4");
                        return;
                    }
                    time += (DateTime.Now - s).TotalMilliseconds;
                    cnt++;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                request.Close();
                //tasks.Remove(Task.CurrentId.Value);
            }
        }
Beispiel #15
0
 private void CreateSocket()
 {
     try
     {
         _socket.Options.Identity          = StationProgram.Config.ServiceName.ToAsciiBytes();
         _socket.Options.ReconnectInterval = new TimeSpan(0, 0, 0, 0, 200);
         _socket.Connect(_config.OutAddress);
     }
     catch (Exception e)
     {
         LogRecorder.Exception(e);
         StationProgram.WriteLine($"【EntityEvent】connect error =>{e.Message}");
         throw;
     }
 }
Beispiel #16
0
        /// <inheritdoc />
        /// <summary>
        /// 命令轮询
        /// </summary>
        /// <returns></returns>
        public sealed override bool Run()
        {
            lock (this)
            {
                if (RunState != StationState.Run)
                {
                    RunState = StationState.Start;
                }
                if (_socket != null)
                {
                    return(false);
                }
            }
            _inPoll = false;

            _socket = new SubscriberSocket();
            try
            {
                _socket.Options.Identity          = RealName.ToAsciiBytes();
                _socket.Options.ReconnectInterval = new TimeSpan(0, 0, 0, 0, 200);
                _socket.Subscribe(Subscribe);
                _socket.Connect(Config.InnerAddress);
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                RunState = StationState.Failed;
                CloseSocket();
                StationProgram.WriteLine($"【{StationName}】connect error =>{e.Message}");
                return(false);
            }
            RunState = StationState.Run;

            _items = MulitToOneQueue <PublishItem> .Load(CacheFileName);

            Task.Factory.StartNew(CommandTask);

            var task1 = Task.Factory.StartNew(PollTask);

            task1.ContinueWith(OnTaskStop);
            while (!_inPoll)
            {
                Thread.Sleep(50);
            }
            StationProgram.WriteLine($"【{StationName}:{RealName}】runing...");
            return(true);
        }
Beispiel #17
0
        internal void ShowStationHostedProgrammingToastNotification(StationProgram program, SongMetadata metadata)
        {
            ToastContent content = new ToastContent()
            {
                Launch = "now-playing",
                Audio  = new ToastAudio()
                {
                    Silent = true,
                },
                Visual = new ToastVisual()
                {
                    BindingGeneric = new ToastBindingGeneric()
                    {
                        Children =
                        {
                            new AdaptiveText()
                            {
                                Text      = "Tuning into " + metadata.Track,
                                HintStyle = AdaptiveTextStyle.Title
                            },

                            new AdaptiveText()
                            {
                                Text      = "Hosted by " + program.Host,
                                HintStyle = AdaptiveTextStyle.Subtitle
                            },

                            new AdaptiveText()
                            {
                                Text      = metadata.StationPlayedOn,
                                HintStyle = AdaptiveTextStyle.Caption
                            },
                        },
                    }
                }
            };

            var notification = new ToastNotification(content.GetXml());

            notification.Tag = SongNotificationTag;
            notification.NotificationMirroring = NotificationMirroring.Disabled;
            toastNotifier.Show(notification);
        }
Beispiel #18
0
        public static void DoTest()
        {
            Console.WriteLine("Hello ZeroNet");
            //StationProgram.RegisteApiStation(new SubStation
            //{
            //    StationName = "BusinessMonitor",
            //    ExecFunc = ExecCommand
            //});
            //StationProgram.Run/*Console*/();
            StationProgram.RegisteApiStation(new SubStation
            {
                StationName = "EntityEvent",
                ExecFunc    = ExecCommand
            });
            StationProgram.RunConsole();

            while (true)
            {
                Console.ReadKey();
                //MarkPoint();
                cnt = 0;
                Console.WriteLine("start...");
                DateTime start = DateTime.Now;

                time = 0.0;
                for (int i = 0; i < 256; i++)
                {
                    tasks.Add(Task.Factory.StartNew(ApiTest).Id);
                }
                //foreach (var task in tasks)
                //    task.Wait();
                double total;
                while (tasks.Count > 0)
                {
                    Thread.Sleep(1000);
                    total = (DateTime.Now - start).TotalMilliseconds;
                    Console.WriteLine($"{cnt}/{time}ms/{total}ms => {cnt / time * 1000}/s -- {cnt / total * 1000}/s -- { total / cnt }ms -- { time / cnt }ms");
                }
                total = (DateTime.Now - start).TotalMilliseconds;
                Console.WriteLine($"{cnt}/{time}ms/{total}ms => {cnt / time * 1000}/s -- {cnt / total * 1000}/s -- { total / cnt }ms -- { time / cnt }ms");
            }
        }
Beispiel #19
0
        /// <summary>
        ///     发送广播
        /// </summary>
        /// <param name="item"></param>
        /// <param name="socket"></param>
        /// <returns></returns>
        private static bool Send(RequestSocket socket, PublishItem item)
        {
            try
            {
                lock (socket)
                {
                    List <string> frames = new List <string> {
                        item.Title
                    };
                    socket.SendMoreFrame(item.Title);
                    byte[] description = new byte[5];
                    description[0] = (byte)3;
                    description[1] = ZeroHelper.zero_pub_publisher;
                    description[2] = ZeroHelper.zero_pub_sub;
                    description[3] = ZeroHelper.zero_arg;
                    description[4] = ZeroHelper.zero_end;
                    socket.SendMoreFrame(item.Title);
                    socket.SendMoreFrame(description);
                    socket.SendMoreFrame(StationProgram.Config.StationName);
                    socket.SendMoreFrame(item.SubTitle);
                    socket.SendFrame(item.Content);
                    var word = socket.ReceiveFrameString();
                    StationProgram.WriteLine($"【{item.Station}-{item.Title}】{word}");
                    return(word == "ok");
                }
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                StationProgram.WriteLine($"【{item.Station}-{item.Title}】request error =>{e.Message}");
            }

            lock (Publishers)
            {
                Publishers.Remove(item.Station);
            }

            return(false);
        }
Beispiel #20
0
        /// <summary>
        /// 命令轮询
        /// </summary>
        /// <returns></returns>
        private void OnStop()
        {
            if (StationProgram.State != StationState.Run)
            {
                return;
            }
            bool restart;

            lock (this)
            {
                restart = RunState == StationState.Failed || RunState == StationState.Start;
            }
            if (!restart)
            {
                return;
            }
            StationProgram.WriteLine($"【{StationName}】restart...");
            if (Run())
            {
                return;
            }
            Thread.Sleep(1000);
            OnStop();
        }
Beispiel #21
0
        private bool IsHostedStationProgramBeginning(SongMetadata songMetadata, StationItem currentStation, out StationProgram stationProgram)
        {
            try
            {
                //this function checkes for "hosted" programs which rely on metadata matching to activate.
                Func <StationProgram, bool> getStationProgram = x =>
                {
                    if (x.Style != StationProgramStyle.Hosted)
                    {
                        return(false);
                    }

                    if (!string.IsNullOrWhiteSpace(x.Host))
                    {
                        if (x.Host.ToLower().Equals(songMetadata.Artist.Trim().ToLower()))
                        {
                            return(true);
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(x.HostRegexExpression))
                    {
                        if (Regex.IsMatch(songMetadata.Artist, x.HostRegexExpression))
                        {
                            return(true);
                        }
                    }

                    return(false);
                };

                if (currentStation?.Programs != null)
                {
                    if (currentStation.Programs.Any(getStationProgram))
                    {
                        //we're tuning into a special radio program. this may be a DJ playing remixes, for exmaple.
                        stationProgram = currentStation.Programs?.First(getStationProgram);

                        return(true);
                    }
                }
            }
            catch (Exception)
            {
#if DEBUG
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
#endif
            }

            stationProgram = null;
            return(false);
        }