//TO DO normal /* * private void CreateDictBots() * { * * DictBots = new Dictionary<long, CBotBase>(); * foreach (CBotBase bot in ListBots) * DictBots[bot.BotId] = bot; * } */ private void OpenCgate() { try { string appKey; if (UseRealServer) { appKey = GlobalConfig.ApplicationKey; } else { appKey = "11111111"; } string stOpen = String.Format(@"ini={0}\netrepl.ini;key={1}", CUtil.GetConfigDir(), appKey); CGate.Open(stOpen); //CGate.Open("ini=netrepl.ini;key=" + appKey); CGate.LogInfo("test .Net log."); } catch (Exception e) { Error("Unable open cgate.", e); } }
/// <summary> /// Запустить адаптер /// </summary> public void Start() { try { lock (_syncRoot) { _cts = new CancellationTokenSource(); UpdateConnectionState(CGConnectionState.Connecting); _configuration.Logger.Debug("Starting CGA"); _marketdataMessagePostingTask = Task.Factory.StartNew(PostNewDataMessagesToSubscribers, TaskCreationOptions.LongRunning); _executionMessagePostingTask = Task.Factory.StartNew(PostNewExecutionMessagesToSubscribers, TaskCreationOptions.LongRunning); string fileName = Path.Combine(_workingDirectory, "netrepl_spectra.ini"); CreateFileIfNeeded(_workingDirectory, fileName); CGate.Open($@"ini={fileName};key={_configuration.Key}"); _dataConnection.Open(); _transactionConnection.Open(); UpdateConnectionState(CGConnectionState.Connected); } } catch (CGateException e) { lock (_startCancelSyncRoot) { _configuration.Logger.Error(e, $"Error while starting CGA: error = {CGate.GetErrorDesc(e.ErrCode)}, message = {e.Message}"); _cts.Cancel(); DisposeCGateObjects(); //CGate.Close(); UpdateConnectionState(CGConnectionState.Shutdown); } throw; } catch (Exception e) { lock (_startCancelSyncRoot) { _configuration.Logger.Error(e, $"Unknown error while starting CGA: {e.Message}"); _cts.Cancel(); DisposeCGateObjects(); UpdateConnectionState(CGConnectionState.Shutdown); } throw; } }
public static void Run() { string streamInfo = "FORTS_FUTINFO_REPL", tableTools = "fut_sess_contents", streamCommonn = "FORTS_FUTCOMMON_REPL", tableCandles = "common", streamGlass = "FORTS_FUTAGGR50_REPL"; string strConnectInfo = "p2repl://" + streamInfo + ";tables=" + tableTools; string strConnectCommon = "p2repl://" + streamCommonn + ";tables=" + tableCandles; string strConnectGlass = "p2repl://" + streamGlass; CGate.Open("ini=/Plaza/bin/cgate.ini;key=11111111"); CGate.LogInfo("test .Net log."); Connection conn = new Connection("p2tcp://127.0.0.1:4001;app_name=TotalInfo"); Listener listInfo = new Listener(conn, strConnectInfo); listInfo.Handler += new Listener.MessageHandler(MessageHandlerTools); Listener listCommon = new Listener(conn, strConnectCommon); listCommon.Handler += new Listener.MessageHandler(MessageHandlerCandles); Listener listGlass = new Listener(conn, strConnectGlass); listGlass.Handler += new Listener.MessageHandler(MessageHandlerGlass); while (!bExit) { try { State state = conn.State; if (state == State.Error) { conn.Close(); } else if (state == State.Closed) { conn.Open(""); } else if (state == State.Active) { ErrorCode result = conn.Process(0); if (result != ErrorCode.Ok && result != ErrorCode.TimeOut) { CGate.LogError(String.Format("Warning: connection state request failed: {0}", CGate.GetErrorDesc(result))); } if (listInfo.State == State.Closed) { listInfo.Open(""); } else if (listInfo.State == State.Error) { listInfo.Close(); } if (listCommon.State == State.Closed) { listCommon.Open(""); } else if (listCommon.State == State.Error) { listCommon.Close(); } if (listGlass.State == State.Closed) { listGlass.Open(""); } else if (listGlass.State == State.Error) { listGlass.Close(); } } } catch (CGateException e) { Console.WriteLine(e.Message); } } conn.Close(); listInfo.Close(); listInfo.Dispose(); listCommon.Close(); listCommon.Dispose(); listGlass.Close(); listGlass.Dispose(); conn.Dispose(); CGate.Close(); }
/// <summary> /// Полинг конекшена на предмет новых сообщений и изменения состояния /// </summary> private void ProcessConnection() { Thread.CurrentThread.Name = $"{_name.ToUpperInvariant()}"; while (true) { var s = Interlocked.CompareExchange(ref _state, STATE_OFF, STATE_OFF); if (s == STATE_OFF) { _logger.Warn($"Exit ProcessConnection, state is {_state}"); break; } s = Interlocked.CompareExchange(ref _state, STATE_OFF, STATE_OFF); if (s == STATE_OFF) { _logger.Warn($"Exit ProcessConnection, state is {_state}"); break; } try { var state = _connection.State; LogStateChange(); if (state == State.Error) { _callback.ConnectionError(this); _logger.Info($"{_name}: Closing error stated connection..."); _connection.Close(); } else if (state == State.Closed) { _callback.ConnectionClosed(this); _logger.Info($"{_name}: opening..."); _connection.Open(""); } else if (state == State.Opening) { _callback.ConnectionOpening(this); var result = _connection.Process(1); if (result != ErrorCode.Ok && result != ErrorCode.TimeOut) { _logger.Error($"{_name}: request failed: {CGate.GetErrorDesc(result)}"); } } else if (state == State.Active) { _callback.ConnectionActive(this); var result = _connection.Process(1); if (result == ErrorCode.Ok) { while ((result = _connection.Process(0)) == ErrorCode.Ok) { } if (result != ErrorCode.TimeOut) { _logger.Error($"{_name}: request failed: {CGate.GetErrorDesc(result)}"); } } else if (result != ErrorCode.TimeOut) { _logger.Error($"{_name}: request failed: {CGate.GetErrorDesc(result)}"); } if (++_cyclesBetweenStreamStateCheck >= MaxCyclesBetweenStreamStateCheck) { _cyclesBetweenStreamStateCheck = 0; //_logger.Info("Check streams states and reopen if needed"); foreach (var subconnection in _streamsAndPublishers1) { subconnection.TryOpen(); subconnection.TryOpen(); } if (_streamsAndPublishers2 != null) { if (_streamsAndPublishers1.All(_ => _.Regime == StreamRegime.ONLINE)) { foreach (var subconnection in _streamsAndPublishers2) { subconnection.TryOpen(); } } } } } } catch (CGateException e) { _logger.Error( e, $"{_name}: Error while polling, CGateException. Error = {CGate.GetErrorDesc(e.ErrCode)}, message = {e.Message}"); Thread.Sleep(_reconnectTimeout); _reconnectTimeout += 1000; // постепенно увеличиваем таймаут между попытками переподключиться } catch (Exception e) { _logger.Error( e, $"{_name}: Error while polling, Exception. Error = {e.Message}"); Thread.Sleep(_reconnectTimeout); _reconnectTimeout += 1000; // постепенно увеличиваем таймаут между попытками переподключиться } } }
private void ThreadProc() { Stopwatch sw = new Stopwatch(); //m_logger = new CLogger(Name); //2017-10-23 m_logger = CreateLogger(Name); Log("Creating working thread for connecion" + Name); m_conn = new Connection(m_settings); bool bActive = false; CreateListeners(); CreatePublishers(); // if (Name == "ConnectionStocksData") // Thread.BeginThreadAffinity(); while (!Exit) { try { State state = m_conn.State; if (state == State.Error) { // CloseListeners(); // ClosePublishers(); OnError(); m_conn.Close(); //TO DO Error log } else if (state == State.Closed) { m_conn.Open(""); // CreateListeners(); // CreatePublishers(); } else if (state == State.Opening) { ErrorCode result = m_conn.Process(0); if (result != ErrorCode.Ok && result != ErrorCode.TimeOut) { //TO DO error to log Log(String.Format("Warning: connection state request failed: {0}", CGate.GetErrorDesc(result))); } } else if (state == State.Active) { if (!bActive) { bActive = true; Log("Connection " + Name + " is active."); } // Log("before process"); sw.Reset(); sw.Start(); ErrorCode result = m_conn.Process(1); /* if (m_sleepTime == 0) * { * if (result == ErrorCode.Ok) * { * _sleeper.OnDataRecieved(); * } * else if (result == ErrorCode.TimeOut) * { * * _sleeper.OnTimeOut(); * * } * }*/ sw.Stop(); //Log("after process"); int delta = m_sleepTime - (int)sw.ElapsedMilliseconds; if (m_sleepTime > 0) { if (delta > 0) { if (!(this.Name == "ConnectionMarketData" && result == ErrorCode.Ok)) { Thread.Sleep(delta); } } } if (result != ErrorCode.Ok && result != ErrorCode.TimeOut) { // CGate.LogError(String.Format("Warning: connection state request failed: {0}", CGate.GetErrorDesc(result))); // TO DO to error log file Log(String.Format("Warning: connection state request failed: {0}", CGate.GetErrorDesc(result))); } //TODO if timeout ProcessListeners(); ProcessPublishers(); m_dtLastOKConnection = DateTime.Now; if (IsConnectionProblem) { IsConnectionProblem = false; if (Name == "ConnectionStocksData") { m_plaza2Connector.StockBoxInp.ReInitAllStocks(); } } } } catch (Exception e) { if ((DateTime.Now - m_dtLastOKConnection).TotalSeconds < m_parSecsSinceConnOK) { string err = "ERROR CConnection ! " + this.Name; Log(err + e.Message); Error(err, e); } } } // if (Name == "ConnectionStocksData") // Thread.EndThreadAffinity(); m_conn.Close(); CloseListeners(); ClosePublishers(); m_conn.Dispose(); }
void Update() { // フレームごとに総合時間から減算 fTotalTime += Time.deltaTime; // キャストした総合時間を秒数に代入 iSecond = (int)fTotalTime; // テキストに秒数を表示 //tTimer.text = iSecond.ToString("00"); float gatetime = CLevelManager.Instance.Get_fGateTime(); float rad = fTotalTime / gatetime * 360; //Debug.Log(fRotationSpeed); gSecondHand.transform.eulerAngles = new Vector3(90.0f, 0.0f, -rad); //gSecondHand.transform.Rotate(0, 0, rad); //if (GameObject.Find(gGate.name + "(Clone)")) { //tTimer.text = "00"; //} /* 下限値の設定 * if (iSecond <= 0) { * tTimer.text = "00"; * fTotalTime = 0.0f; * }*/ // 時間が来たらまたはプレイヤsss.ーの意思で回収 if (fTotalTime >= gatetime || Input.GetKeyDown(KeyCode.Return) || Input.GetButtonDown(stButton0Name)) { // ゲートが二つ出るのを防ぐ if (GameObject.Find(gGate.name + "(Clone)") == null) { List <GameObject> list = csObjectManager.Get_gObjectList(); if (list.Count > 0) { OBJECT_SHAPE order = csOrderManager.Get_Order(0); // 指令の最初のオブジェクトの位置にゲートを出す GameObject first = null; int i; for (i = 0; i < list.Count; i++) { if (list[i].GetComponent <CRotateObject>().Get_Shape() == order) { first = list[i]; break; } } if (i < list.Count) { float deg = first.GetComponent <CRotateObject>().Get_fDegree(); float subdeg = first.GetComponent <CRotateObject>().Get_fDegreeSub(); deg += 30; Vector3 pos; if (deg >= 330 && deg <= 690) { subdeg = 180; } else { subdeg = 0.0f; } if (deg >= 330 && deg <= 690) { if (deg <= 400 && deg >= 330) { subdeg = 180 + (400 - deg) * 3.0f; } } else { if (deg <= 760 && deg >= 690) { subdeg = (760 - deg) * 3.0f; } } pos.x = 7 * Mathf.Sin((deg + 180) * Mathf.Deg2Rad) + 2 * Mathf.Cos(subdeg * Mathf.Deg2Rad) * Mathf.Sin((deg + 180) * Mathf.Deg2Rad); pos.y = 2 * Mathf.Sin(subdeg * Mathf.Deg2Rad); pos.z = 7 * Mathf.Cos((deg + 180) * Mathf.Deg2Rad) + 2 * Mathf.Cos(subdeg * Mathf.Deg2Rad) * Mathf.Cos((deg + 180) * Mathf.Deg2Rad); GameObject gate = Instantiate(gGate, pos, Quaternion.Euler(0, 90, 0)); CGate cs = gate.GetComponent <CGate>(); CRotateObject cro = first.GetComponent <CRotateObject>(); if (deg >= 330 && deg <= 690) { cs.Set_State(RotateState.INSIDE); if (deg <= 400 && deg >= 330) { cs.Set_isInverse(true); cs.Set_fDegreeSub(180 + (400 - deg) * 3.0f); } } else { cs.Set_State(RotateState.OUTSIDE); if (deg <= 760 && deg >= 690) { cs.Set_isInverse(true); cs.Set_fDegreeSub((760 - deg) * 3.0f); } } cs.Set_fDegree(deg); } } } fTotalTime = gatetime; } }