protected bool DoGroup(object obj) { if (OnDogroup(obj)) { if (Type == BalanceActionType.Hire) { Balancer.ChangeLeftBuget(-_outputGroupBuget); if (!Balancer.IsNoBuget()) { return(true); } else { return(false); } } else if (Type == BalanceActionType.Fire) { Balancer.ChangeLeftBuget(_outputGroupBuget); if (!Balancer.IsEnoughBuget()) { return(true); } else { return(false); } } } return(true); }
private static void Handler() { bool devMode = false; bool balance_notif = false; while (true) { WriteLine("Command:"); string line_input = ReadLine().ToLower(); switch (line_input) { default: WriteLine("This command does not exist.", ConsoleColor.Yellow); continue; case "help": WriteLines(new[] { "\nBalance - the command to balance an equation.", "Check - the command to check if an equation is balanced correct.", "Atom Info - the command to show information on a specific atom." }, false, new [] { ConsoleColor.Green }); break; case "balance": while (true) { if (Balancer.BalanceEquation(balance_notif) == false) { continue; } balance_notif = true; break; } break; case "check": Checker.CheckEquation(); break; case "-dev": WriteLine("Entered Dev Mode", ConsoleColor.Yellow, false); devMode = true; break; case "atom info": new AtomView().ShowDialog(); break; case "-exit": WriteLine("Exited Dev Mode", ConsoleColor.Yellow, false); devMode = false; break; case "exit": WriteLine("Have a nice day!", ConsoleColor.Gray, false); return; } WriteLine("", ConsoleColor.Gray, false); } }
public BalancerMiddleware(RequestDelegate next, ILogger <BalancerMiddleware> logger, IOptions <BalancerSetting> settings = null) { _next = next; _logger = logger; _balancerSetting = settings.Value; _balancer = new Balancer(_balancerSetting); }
private bool _disposed = false; // To detect redundant calls public EtcdClient(string connectionString, int port = 2379, string username = "", string password = "", string caCert = "", string clientCert = "", string clientKey = "", bool publicRootCa = false) { if (string.IsNullOrWhiteSpace(connectionString)) { throw new Exception("etcd connection string is empty."); } string[] hosts = connectionString.Split(','); List<Uri> nodes = new List<Uri>(); for (int i = 0; i < hosts.Length; i++) { string host = hosts[i]; if (host.Split(':').Length < 3) { host += $":{Convert.ToString(port)}"; } nodes.Add(new Uri(host)); } _balancer = new Balancer(nodes, username, password, caCert, clientCert, clientKey, publicRootCa); }
public void Balancer_Multithread() { var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair <string, string>("Servers:0", "localhost:9000") }) .Build(); var balancer = new Balancer(configuration); var pool = new List <Thread>(); for (var i = 0; i < 150; i++) { var thread = new Thread(() => { Thread.Sleep(new Random().Next(0, 50)); var url = balancer.AllocateServer(); }); thread.Start(); pool.Add(thread); } SpinWait.SpinUntil(() => pool.All(x => !x.IsAlive)); Assert.Equal(150, balancer.GetConnectionsCount("localhost:9000")); }
public void Test1(int[] bankCount, int expected, int part) { var sut = new Balancer(); var actual = sut.Balance(bankCount, part); Assert.That(actual, Is.EqualTo(expected)); }
const int REMOTE_COMMAND_STOP = 's'; // 's' public static void Main() { // 構造体の宣言と初期化 var body = new EV3body(); EV3body.init(ref body); // Bluetooth関係のETロボコン拡張機能を有効にする Brick.InstallETRoboExt(); // リモート接続 NetworkStream connection = connect(); // センサーおよびモータに対して初回アクセスをしておく body.color.Read(); body.sonar.Read(); body.gyro.Read(); body.motorL.SetPower(0); body.motorR.SetPower(0); body.motorT.SetPower(0); body.motorL.ResetTacho(); body.motorR.ResetTacho(); body.motorT.ResetTacho(); Balancer.init(); // スタート待ち wait_start(body, connection); var dialogRun = new InfoDialog("Running", false); dialogRun.Show(); //Wait for enter to be pressed try{ run(body, connection); }catch (Exception) { var dialogE = new InfoDialog("Exception.", false); dialogE.Show(); //Wait for enter to be pressed } body.motorL.Off(); body.motorR.Off(); body.motorT.Off(); // ソケットを閉じる if (connection != null) { connection.Close(); } Lcd.Instance.Clear(); Lcd.Instance.Update(); if (Debugger.IsAttached) { Brick.ExitToMenu(); // MonoBrickメインメニューへ戻る } }
internal async void DoConnect() { _isConnecting = true; _callDisconnectedCallback = false; _gotOnOpenCount = 0; if (_webSocketConnection != null) { _webSocketConnection.Dispose(); } _webSocketConnection = new Connection(_reconnectTimer); _webSocketConnection.OnOpened += new Connection.onOpenedDelegate(_webSocketConnection_OnOpened); _webSocketConnection.OnClosed += new Connection.onClosedDelegate(_webSocketConnection_OnClosed); _webSocketConnection.OnError += new Connection.onErrorDelegate(_webSocketConnection_OnError); _webSocketConnection.OnMessageReceived += new Connection.onMessageReceivedDelegate(_webSocketConnection_OnMessageReceived); if (context.IsCluster) { try { context.Url = await Balancer.ResolveClusterUrlAsync(context.ClusterUrl); //"nope";// GetUrlFromCluster(); context.IsCluster = true; if (String.IsNullOrEmpty(context.Url)) { context.DelegateExceptionCallback(new OrtcEmptyFieldException("Unable to get URL from cluster")); DoReconnect(); } } catch (Exception ex) { if (!_stopReconnecting) { context.DelegateExceptionCallback(new OrtcNotConnectedException(ex.Message)); DoReconnect(); } } } if (!String.IsNullOrEmpty(context.Url)) { try { _webSocketConnection.Connect(context.Url); // Just in case the server does not respond // _waitingServerResponse = true; //StartReconnectTimer(); // } catch (OrtcEmptyFieldException ex) { context.DelegateExceptionCallback(new OrtcNotConnectedException(ex.Message)); DoStopReconnecting(); } catch (Exception ex) { context.DelegateExceptionCallback(new OrtcNotConnectedException(ex.Message)); _isConnecting = false; } } }
public async Task <bool> StartGame() { var context = GetContext(); if (Mode != AutohostMode.None) { var balance = Balancer.BalanceTeams(context, true, null, null); if (!IsNullOrEmpty(balance.Message)) { await SayBattle(balance.Message); } if (!balance.CanStart) { return(false); } context.ApplyBalance(balance); } var startSetup = StartSetup.GetDedicatedServerStartSetup(context); if (!await EnsureEngineIsPresent()) { return(false); } if (IsInGame || spring.IsRunning) { await SayBattle("Game already running"); return(false); } spring.HostGame(startSetup, hostingIp, hostingPort); IsInGame = true; RunningSince = DateTime.UtcNow; foreach (var us in Users.Values) { if (us != null) { ConnectedUser user; if (server.ConnectedUsers.TryGetValue(us.Name, out user)) { await user.SendCommand(GetConnectSpringStructure(us.ScriptPassword)); } } } await server.Broadcast(server.ConnectedUsers.Values, new BattleUpdate() { Header = GetHeader() }); // remove all from MM await Task.WhenAll(startSetup.Players.Where(x => !x.IsSpectator).Select(x => server.MatchMaker.RemoveUser(x.Name, false))); await server.MatchMaker.UpdateAllPlayerStatuses(); return(true); }
static void run(EV3body body) { // 電圧を取得 int battery = Brick.GetVoltageMilliVolt(); sbyte forward; sbyte turn; sbyte oldPwmL = 0, oldPwmR = 0; while (true) { tail_control(body, TAIL_ANGLE_DRIVE); // バランス走行用角度に制御 forward = 50; turn = (body.color.Read() >= (LIGHT_BLACK + LIGHT_WHITE) / 2) ? (sbyte)50 : (sbyte)-50; int gyroNow = body.gyro.Read(); int theTaL = body.motorL.GetTachoCount(); int theTaR = body.motorR.GetTachoCount(); // バックラッシュをキャンセル Balancer.backlash_cancel(oldPwmL, oldPwmR, ref theTaL, ref theTaR); sbyte pwmL, pwmR; Balancer.control( (float)forward, (float)turn, (float)gyroNow, (float)GYRO_OFFSET, (float)theTaL, (float)theTaR, (float)battery, out pwmL, out pwmR ); oldPwmL = pwmL; oldPwmR = pwmR; if (pwmL == 0) { body.motorL.Brake(); } else { body.motorL.SetPower(pwmL); } if (pwmR == 0) { body.motorR.Brake(); } else { body.motorR.SetPower(pwmR); } // バランス制御のみだと3msecで安定 // 尻尾制御と障害物検知を使用する場合2msecで安定 Thread.Sleep(1); } }
public async Task <Instance> SelectOneHealthyInstance(string serviceName, string groupName, IList <string> clusters, bool subscribe) { if (subscribe) { return(Balancer.SelectHost(await _hostReactor.GetServiceInfo(GetGroupedName(serviceName, groupName), string.Join(",", clusters)))); } else { return(Balancer.SelectHost(await _hostReactor.GetServiceInfoDirectlyFromServer(GetGroupedName(serviceName, groupName), string.Join(",", clusters)))); } }
public void TestClosedParenthesisBeforeOpenParenthesisReturnsFalse() { string testString = "("; Balancer.isBalanced(testString).Should().BeFalse(); testString = "{{)(}}"; Balancer.isBalanced(testString).Should().BeFalse(); testString = "({)}"; Balancer.isBalanced(testString).Should().BeFalse(); }
public void SplitAutohost(BattleContext context, string password) { if (AuthServiceClient.VerifyAccountPlain(context.AutohostName, password) == null) { throw new Exception("Invalid password"); } if (context.GetConfig() == null) { throw new Exception("Not an autohost"); } Balancer.SplitAutohost(context); }
public ApiGatewayConfig() { Balancer.Add(new BalancerOption { Enable = false, Host = "localhost:64516", Nodes = new Node[] { new Node { Host = "google.com", Port = 443, Scheme = "https", Enable = true }, new Node { Host = "amazon.com", Port = 443, Scheme = "https", Enable = true } }, Path = "^(.*)$", Policy = "RoundRobin", Port = 64516, Scheme = "http" }); Proxy.Add(new ProxyOption { Enable = false, Host = "localhost:64516", Node = new Node { Host = "google.com", Port = 443, Scheme = "https" }, Path = "^(.*)$", Port = 64516, Scheme = "http" }); Cache = new CacheOption { Enable = false, Duration = 600, MaximumBodySize = 100 * 1024 * 1024, SizeLimit = 64 * 1024 * 1024, UseCaseSensitivePaths = false }; Logging = new LoggingOption { Enable = false }; }
public void Balancer_AllocateServer() { var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair <string, string>("Servers:0", "localhost:9000") }) .Build(); var balancer = new Balancer(configuration); var url = balancer.AllocateServer(); Assert.Equal(1, balancer.GetConnectionsCount(url)); }
public void TestBalancedStringReturnsTrue() { string testString = "()"; Balancer.isBalanced(testString).Should().BeTrue(); testString = "[({})]"; Balancer.isBalanced(testString).Should().BeTrue(); testString = "{}([])"; Balancer.isBalanced(testString).Should().BeTrue(); testString = "{()}[[{}]]"; Balancer.isBalanced(testString).Should().BeTrue(); }
public async Task <bool> RunServerBalance(bool isGameStart, int?allyTeams, bool?clanWise) { try { var context = GetContext(); context.Mode = Mode; var balance = Balancer.BalanceTeams(context, isGameStart, allyTeams, clanWise); await ApplyBalanceResults(balance); return(balance.CanStart); } catch (Exception ex) { Trace.TraceError(ex.ToString()); return(false); } }
const int PWM_ABS_MAX = 60; //完全停止用モータ制御PWM絶対最大値 public static void Main() { // 構造体の宣言と初期化 var body = new EV3body(); EV3body.init(ref body); // Bluetooth関係のETロボコン拡張機能を有効にする Brick.InstallETRoboExt(); // センサーおよびモータに対して初回アクセスをしておく body.color.Read(); body.gyro.Read(); body.motorL.SetPower(0); body.motorR.SetPower(0); body.motorT.SetPower(0); body.motorL.ResetTacho(); body.motorR.ResetTacho(); body.motorT.ResetTacho(); Balancer.init(); // スタート待ち wait_start(body); try{ run(body); }catch (Exception) { var dialogE = new InfoDialog("Exception."); dialogE.Show(); //Wait for enter to be pressed } body.motorL.Off(); body.motorR.Off(); body.motorT.Off(); Lcd.Clear(); Lcd.Update(); if (Debugger.IsAttached) { Brick.ExitToMenu(); // MonoBrickメインメニューへ戻る } }
public void Nanny() { Thread.Sleep(5000); if (ConfigObject.Bots.Any(bot => !bot.TMDisabled)) { Balancer.Init(); } Dictionary <string, DateTime> lastRestart = new Dictionary <string, DateTime>(); TimeSpan restartInterval = new TimeSpan(0, 2, 0); while (!disposed) { try { foreach (RunningBot bot in botProcs) { if (bot.IsRunning && bot.TheBot.WantToRestart()) { DateTime now = DateTime.Now; if (lastRestart.TryGetValue(bot.BotConfig.Username, out DateTime dt)) { TimeSpan timeGone = now.Subtract(dt); if (restartInterval.CompareTo(timeGone) > 0) { mongoLog.ApiError($"Nanny is waiting {restartInterval.Subtract(timeGone).TotalSeconds} seconds"); VK.Alert($"Nanny is waiting {restartInterval.Subtract(timeGone).TotalSeconds} seconds"); Thread.Sleep(restartInterval.Subtract(timeGone)); } } mongoLog.ApiError($"Nanny is restarting bot {bot.BotConfig.Username}"); VK.Alert($"Nanny is restarting bot {bot.BotConfig.Username}"); RestartBot(bot.BotConfig.Username); lastRestart[bot.BotConfig.Username] = DateTime.Now; Thread.Sleep(100); } } } catch (Exception ex) { mongoLog.Error($"Няне больно =(\n{ex.Message}{ex.StackTrace}"); VK.Alert($"Няне больно =(\n{ex.Message}{ex.StackTrace}"); } finally { Thread.Sleep(5000); } } }
public void TestBlueSky_Surplus_LessThanDeficit() { //set-up Builders = CreateBuilders(); decimal surplus = Builders[0].Surplus = 5m; decimal deficit = Builders[1].Deficit = 10m; Balancer = new Balancer(Builders); //pre-conditions Assert.IsTrue(surplus < deficit); //exercise Balancer.BalanceBudget(); //post-conditions Assert.AreEqual(0, Builders[0].Surplus); Assert.AreEqual(5, Builders[1].Deficit); }
public void OnButtonUp() { float Price = Balancer.GetParameterPrice(Count, player.Lvl); if (xp.XPGet(Price)) { if (param == Characteristics.Speed) { Count += 0.05f; } else if (param == Characteristics.SumBaseDamage) { Count++; } else { Count += 10; } } UpdateUI(); }
public void OnButtonDown() { float Price = Balancer.GetParameterPrice(Count - 1, player.Lvl); if (xp.XPReturn(Price)) { if (param == Characteristics.Speed) { Count -= 0.05f; } else if (param == Characteristics.SumBaseDamage) { Count--; } else { Count -= 10; } } UpdateUI(); }
static void Main(string[] args) { var inputs = new[] { "H2 + O2 = H2O", "O2 + FeS2 = SO2 + Fe2O3", "H2O2 + Cr2O7^2- = Cr^3+ + O2 + OH^-", "K4Fe(CN)6 + KMnO4 + H2SO4 = KHSO4 + Fe2(SO4)3 + MnSO4 + HNO3 + CO2 + H2O" }; var balancer = new Balancer(); foreach (var input in inputs) { balancer.Solve(input); //Console.WriteLine(balancer.EquationHtml); Console.WriteLine($" Input: {input}"); Console.WriteLine($"Output: {balancer.EquationText}"); Console.WriteLine(); } Console.ReadLine(); }
public async Task <Instance> SelectOneHealthyInstance(string serviceName, string groupName, List <string> clusters, bool subscribe) { string clusterString = string.Join(",", clusters); if (subscribe) { ServiceInfo serviceInfo = _serviceInfoHolder.GetServiceInfo(serviceName, groupName, clusterString); if (serviceInfo == null) { serviceInfo = await _clientProxy.Subscribe(serviceName, groupName, clusterString).ConfigureAwait(false); } return(Balancer.GetHostByRandom(serviceInfo?.Hosts)); } else { ServiceInfo serviceInfo = await _clientProxy .QueryInstancesOfService(serviceName, groupName, clusterString, 0, false).ConfigureAwait(false); return(Balancer.GetHostByRandom(serviceInfo?.Hosts)); } }
public BalancerPolicy(Balancer balancer, string policy) { _balancer = balancer; _policy = policy; }
/// <summary> /// Saves the authentication token channels permissions in the ORTC server. /// </summary> /// <param name="url">ORTC server URL.</param> /// <param name="isCluster">Indicates whether the ORTC server is in a cluster.</param> /// <param name="authenticationToken">Authentication Token which is generated by the application server, for instance a unique session ID.</param> /// <param name="authenticationTokenIsPrivate">Indicates whether the authentication token is private (1) or not (0).</param> /// <param name="applicationKey">Application Key that was provided to you together with the ORTC service purchasing.</param> /// <param name="timeToLive">The authentication token time to live, in other words, the allowed activity time (in seconds).</param> /// <param name="privateKey">The private key provided to you together with the ORTC service purchasing.</param> /// <param name="permissions">The channels and their permissions (w: write/read or r: read, case sensitive).</param> /// <returns>True if the authentication was successful or false if it was not.</returns> /// <exception cref="OrtcEmptyFieldException">Server URL can not be null or empty.</exception> /// <exception cref="OrtcAuthenticationNotAuthorizedException">Unauthorized by the server.</exception> /// <exception cref="OrtcNotConnectedException">Unable to connect to the authentication server.</exception> /// <example> /// <code> /// // Permissions /// Dictionary;string, ChannelPermissions; permissions = new Dictionary;string, List;ChannelPermissions;;(); /// /// Dictionary;string, List;ChannelPermissions;; channelPermissions = new Dictionary;string, List;ChannelPermissions;;(); /// var permissionsList = new List;ChannelPermissions;(); /// /// permissionsList.Add(ChannelPermissions.Write); /// permissionsList.Add(ChannelPermissions.Presence); /// /// channelPermissions.Add("channel1", permissionsList); /// /// string url = "http://ortc-developers.realtime.co/server/2.1"; /// bool isCluster = true; /// string authenticationToken = "myAuthenticationToken"; /// bool authenticationTokenIsPrivate = true; /// string applicationKey = "myApplicationKey"; /// int timeToLive = 1800; // 30 minutes /// string privateKey = "myPrivateKey"; /// /// bool authSaved = Ibt.Ortc.Api.Ortc.SaveAuthentication(url, isCluster, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, channelPermissions)) /// </code> /// </example> public static bool SaveAuthentication(string url, bool isCluster, string authenticationToken, bool authenticationTokenIsPrivate, string applicationKey, int timeToLive, string privateKey, Dictionary <string, List <ChannelPermissions> > permissions) { if (String.IsNullOrEmpty(url)) { throw new OrtcEmptyFieldException("URL is null or empty."); } else if (String.IsNullOrEmpty(applicationKey)) { throw new OrtcEmptyFieldException("Application Key is null or empty."); } else if (String.IsNullOrEmpty(authenticationToken)) { throw new OrtcEmptyFieldException("Authentication Token is null or empty."); } else if (String.IsNullOrEmpty(privateKey)) { throw new OrtcEmptyFieldException("Private Key is null or empty."); } string connectionUrl = url; if (isCluster) { connectionUrl = Balancer.ResolveClusterUrl(url); } if (String.IsNullOrEmpty(connectionUrl)) { throw new OrtcNotConnectedException("Unable to get URL from cluster"); } connectionUrl = connectionUrl.EndsWith("/") ? connectionUrl + "authenticate" : connectionUrl + "/authenticate"; string postParameters = String.Format("AT={0}&PVT={1}&AK={2}&TTL={3}&PK={4}", authenticationToken, authenticationTokenIsPrivate ? 1 : 0, applicationKey, timeToLive, privateKey); if (permissions != null && permissions.Count > 0) { postParameters += String.Format("&TP={0}", permissions.Count); foreach (var permission in permissions) { var permissionItemText = String.Format("{0}=", permission.Key); foreach (var permissionItemValue in permission.Value.ToList()) { permissionItemText += ((char)permissionItemValue).ToString(); } postParameters += String.Format("&{0}", permissionItemText); } } HttpContent content = new StringContent(postParameters); using (var client = new HttpClient(new NativeMessageHandler())) { var response = client.PostAsync(new Uri(connectionUrl), content).Result; if (response.IsSuccessStatusCode) { return(true); } else { throw new OrtcAuthenticationNotAuthorizedException(response.Content.ReadAsStringAsync().Result); } } }
public BalanceTeamsResult BalanceTeams(BattleContext context, bool isGameStart, int?allyCount, bool?clanWise) { return(Balancer.BalanceTeams(context, isGameStart, allyCount, clanWise)); }
/// <summary> /// 构造函数 /// </summary> /// <param name="connectionString">连接字符串:逗号隔开</param> /// <param name="port">端口</param> /// <param name="username">基本身份验证的etcd服务器的用户名</param> /// <param name="password">基本身份验证的etcd服务器的密码</param> /// <param name="caCert">连接到etcd的CA证书内容。</param> /// <param name="clientCert">连接到etcd的客户端证书内容。</param> /// <param name="clientKey">连接到etcd的客户端密钥内容。</param> /// <param name="publicRootCa">是否使用公共信任的根进行连接。</param> /// <exception cref="Exception"></exception> public EtcdClient(string connectionString, int port = 2379, string username = "", string password = "", string caCert = "", string clientCert = "", string clientKey = "", bool publicRootCa = false) { if (string.IsNullOrWhiteSpace(connectionString)) { throw new Exception("连接到Etcd服务端的连接不能为空."); } string[] hosts; if (connectionString.ToLowerInvariant().StartsWith("discovery-srv://")) { // Expecting it to be discovery-srv://{domain}/{name} // Examples: // discovery-srv://my-domain.local/ would expect entries for either _etcd-client-ssl._tcp.my-domain.local or _etcd-client._tcp.my-domain.local // discovery-srv://my-domain.local/project1 would expect entries for either _etcd-client-ssl-project1._tcp.my-domain.local or _etcd-client-project1._tcp.my-domain.local // Uri discoverySrv = new Uri(connectionString); // var client = new LookupClient {UseCache = true}; // // SSL first ... // var serviceName = "/".Equals(discoverySrv.AbsolutePath) // ? "" // : $"-{discoverySrv.AbsolutePath.Substring(1, discoverySrv.AbsolutePath.Length - 1)}"; // var result = client.Query($"_etcd-client-ssl{serviceName}._tcp.{discoverySrv.Host}", QueryType.SRV); // var scheme = "https"; // if (result.HasError) // { // scheme = "http"; // // No SSL ... // result = client.Query($"_etcd-client{serviceName}._tcp.{discoverySrv.Host}", QueryType.SRV); // if (result.HasError) // { // throw new InvalidOperationException(result.ErrorMessage); // } // } // // var results = result.Answers.OfType<SrvRecord>().OrderBy(a => a.Priority) // .ThenByDescending(a => a.Weight).ToList(); // hosts = new string[results.Count]; // for (int index = 0; index < results.Count; index++) // { // var srvRecord = results[index]; // var additionalRecord = // result.Additionals.FirstOrDefault(p => p.DomainName.Equals(srvRecord.Target)); // var host = srvRecord.Target.Value; // // if (additionalRecord is ARecord aRecord) // { // host = aRecord.Address.ToString(); // } // else if (additionalRecord is CNameRecord cname) // { // host = cname.CanonicalName; // } // // if (host.EndsWith(".")) // host = host.Substring(0, host.Length - 1); // hosts[index] = $"{scheme}://{host}:{srvRecord.Port}"; // } hosts = new string[] { }; } else { hosts = connectionString.Split(','); } List <Uri> nodes = new List <Uri>(); // 处理连接字符串没有加端口号 for (int i = 0; i < hosts.Length; i++) { string host = hosts[i]; if (host.Split(':').Length < 3) { host += $":{Convert.ToString(port)}"; } nodes.Add(new Uri(host)); } _balancer = new Balancer(nodes, username, password, caCert, clientCert, clientKey, publicRootCa); }
static void run(EV3body body, NetworkStream connection) { // 電圧を取得 int battery = Brick.GetVoltageMilliVolt(); sbyte forward; sbyte turn; int counter = 0; bool alert = false; while (!body.touch.IsPressed()) { tail_control(body, TAIL_ANGLE_DRIVE); // バランス走行用角度に制御 if (checkRemoteCommand(connection, REMOTE_COMMAND_STOP)) { break; // PC で 's' キー押されたら走行終了 } if (++counter >= 40 / 4) { alert = sonar_alert(body); counter = 0; } if (alert) { forward = 0; turn = 0; } else { forward = 50; turn = (body.color.Read() >= (LIGHT_BLACK + LIGHT_WHITE) / 2) ? (sbyte)50 : (sbyte)-50; } int gyroNow = body.gyro.Read(); int thetaL = body.motorL.GetTachoCount(); int theTaR = body.motorR.GetTachoCount(); sbyte pwmL, pwmR; Balancer.control( (float)forward, (float)turn, (float)gyroNow, (float)GYRO_OFFSET, (float)thetaL, (float)theTaR, (float)battery, out pwmL, out pwmR ); if (pwmL == 0) { body.motorL.Brake(); } else { body.motorL.SetPower(pwmL); } if (pwmR == 0) { body.motorR.Brake(); } else { body.motorR.SetPower(pwmR); } // バランス制御のみだと3msecで安定 // 尻尾制御と障害物検知を使用する場合2msecで安定 Thread.Sleep(2); } }
public EtcdClient(string connectionString, int port = 2379, HttpClientHandler handler = null, bool ssl = false, bool useLegacyRpcExceptionForCancellation = false) { if (string.IsNullOrWhiteSpace(connectionString)) { throw new Exception("etcd connection string is empty."); } string[] hosts; if (connectionString.ToLowerInvariant().StartsWith("discovery-srv://")) { // Expecting it to be discovery-srv://{domain}/{name} // Examples: // discovery-srv://my-domain.local/ would expect entries for either _etcd-client-ssl._tcp.my-domain.local or _etcd-client._tcp.my-domain.local // discovery-srv://my-domain.local/project1 would expect entries for either _etcd-client-ssl-project1._tcp.my-domain.local or _etcd-client-project1._tcp.my-domain.local Uri discoverySrv = new Uri(connectionString); LookupClient client = new LookupClient(new LookupClientOptions { UseCache = true }); // SSL first ... string serviceName = "/".Equals(discoverySrv.AbsolutePath) ? "" : $"-{discoverySrv.AbsolutePath.Substring(startIndex: 1, length: discoverySrv.AbsolutePath.Length - 1)}"; IDnsQueryResponse result = client.Query($"_etcd-client-ssl{serviceName}._tcp.{discoverySrv.Host}", QueryType.SRV); string scheme = "https"; if (result.HasError) { scheme = "http"; // No SSL ... result = client.Query($"_etcd-client{serviceName}._tcp.{discoverySrv.Host}", QueryType.SRV); if (result.HasError) { throw new InvalidOperationException(result.ErrorMessage); } } List <SrvRecord> results = result.Answers.OfType <SrvRecord>().OrderBy(a => a.Priority) .ThenByDescending(a => a.Weight).ToList(); hosts = new string[results.Count]; for (int index = 0; index < results.Count; index++) { SrvRecord srvRecord = results[index]; DnsResourceRecord additionalRecord = result.Additionals.FirstOrDefault(p => p.DomainName.Equals(srvRecord.Target)); string host = srvRecord.Target.Value; if (additionalRecord is ARecord aRecord) { host = aRecord.Address.ToString(); } else if (additionalRecord is CNameRecord cname) { host = cname.CanonicalName; } if (host.EndsWith(".")) { host = host.Substring(startIndex: 0, host.Length - 1); } hosts[index] = $"{scheme}://{host}:{srvRecord.Port}"; } } else { hosts = connectionString.Split(','); } List <Uri> nodes = new List <Uri>(); for (int i = 0; i < hosts.Length; i++) { string host = hosts[i]; if (host.Split(':').Length < 3) { host += $":{Convert.ToString(port)}"; } if (!(host.StartsWith(InsecurePrefix) || host.StartsWith(SecurePrefix))) { if (ssl) { host = $"{SecurePrefix}{host}"; } else { host = $"{InsecurePrefix}{host}"; } } nodes.Add(new Uri(host)); } _balancer = new Balancer(nodes, handler, ssl, useLegacyRpcExceptionForCancellation); }