示例#1
0
	private List<StationInfo> CreateStations()
	{
		List<StationInfo> stationList = new List<StationInfo>();
		
		print ("Preparing to add " + numStations + " stations");
		
		for (int i=0; i<numStations; i++)
		{
			StationInfo myStation = new StationInfo();
			
			Vector3 possibleLocation = Vector3.zero;
			bool goodStationLocation = false;
			//while (!goodStationLocation) {
				possibleLocation = new Vector3(Random.Range(-dimensions.x/2f, dimensions.x/2f),
												Random.Range(-dimensions.y/2f, dimensions.y/2f),
												Random.Range(-dimensions.z/2f, dimensions.z/2f));
			//	goodStationLocation = CheckLocation(possibleLocation,stationList);
			//}
			myStation.location = possibleLocation;
			myStation.go = Instantiate (stationPrefab,myStation.location,Quaternion.identity) as GameObject;
			
			stationList.Add(myStation);
			print ("Added station #" + i + " at " + myStation.location);
		}
		
		return stationList;
	}
示例#2
0
        /// <summary>
        /// Saves a record to the station table.
        /// </summary>
        public virtual void Insert(StationInfo stationInfo)
        {
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@stationid", stationInfo.Stationid),
                new SqlParameter("@name", stationInfo.Name),
                new SqlParameter("@province", stationInfo.Province),
                new SqlParameter("@company", stationInfo.Company)
            };

            SqlClientUtility.ExecuteNonQuery(connectionStringName, CommandType.StoredProcedure, "station_Insert", parameters);
        }
示例#3
0
 /// <summary>
 /// Saves a record to the station table.
 /// </summary>
 public virtual void Update(StationInfo stationInfo)
 {
     try
     {
         new StationTFM().Update(stationInfo);
     }
     catch (Exception ex)
     {
         //Provider.Log.Error(ex, "TFM.Biz.Implements.Station - Update" + ex.Message);
         throw;
     }
 }
示例#4
0
 /// <summary>
 /// Saves a record to the station table.
 /// </summary>
 public virtual void Insert(StationInfo stationInfo)
 {
     try
     {
         new StationTFM().Insert(stationInfo);
     }
     catch (Exception ex)
     {
         //Log error by TFM framwork here
         //Provider.Log.Error(ex, "TFM.Biz.Implements.Station - Insert" + ex.Message);
         throw;
     }
 }
示例#5
0
 public IEnumerable <MXFChannel> GetMXFChannels()
 {
     foreach (var stationIdAndInfo in stationInfoByStationId_)
     {
         string      stationId      = stationIdAndInfo.Key;
         StationInfo stationInfo    = stationIdAndInfo.Value;
         var         channelNumbers = stationInfo.guideChannelNumbers;
         foreach (var channelNumber in channelNumbers)
         {
             yield return(new MXFChannel(channelNumber, stationInfo.sdStation));
         }
         if (channelNumbers.Count == 0)
         {
             yield return(new MXFChannel(null, stationInfo.sdStation));
         }
     }
 }
        public static void TryPickPlace()
        {
            if (CheckPickPlaceCondition())
            {
                int num = EquipmentInfo.STATION_NUM - 2;
                if (AppInfo.AppType == AppInfo.APP_TYPE_CAMERA)
                {
                    num = 2;
                }
                string bin = "";
                for (int i = num; i >= 0; i--)
                {
                    StationInfo stationInfo = EquipmentInfo.GetStationInfo(i);

                    if (stationInfo.Work)
                    {
                        bin += '1';
                    }
                    else
                    {
                        bin += '0';
                    }
                }

                int    d     = Convert.ToInt32(bin, 2);
                string param = Convert.ToString(d);
                string resp;

                ThreadPool.QueueUserWorkItem(delegate {
                    //LiteDataClient.Instance.BroadcastPickPlace();

                    Log.Debug("PickPlace " + "1站取放 " + bin);
                    if (EquipmentCmd.Instance.SendCommand("1站取放", param, out resp))
                    {
                        LiteDataClient.Instance.BroadcastPickPlace();
                    }
                });

                for (int i = 0; i < EquipmentInfo.STATION_NUM; i++)
                {
                    StationInfo stationInfo = EquipmentInfo.GetStationInfo(i);
                    stationInfo.Complete = false;
                }
            }
        }
示例#7
0
        public override void Initialize()
        {
            this._sky        = new Sky(this._app, SkyUsage.StarMap, 0);
            this._crits      = new GameObjectSet(this._app);
            this._planetView = this._crits.Add <PlanetView>();
            this._crits.Add((IGameObject)this._sky);
            StationInfo       stationInfo        = this._app.GameDatabase.GetStationInfo(this._stationID);
            OrbitalObjectInfo orbitalObjectInfo1 = this._app.GameDatabase.GetOrbitalObjectInfo(this._stationID);
            OrbitalObjectInfo orbitalObjectInfo2 = this._app.GameDatabase.GetOrbitalObjectInfo(orbitalObjectInfo1.ParentID.Value);

            this._app.UI.SetText(this._app.UI.Path(this.ID, "station_class"), string.Format(App.Localize("@STATION_LEVEL"), (object)stationInfo.DesignInfo.StationLevel.ToString(), (object)stationInfo.DesignInfo.StationType.ToString()));
            this._app.UI.SetText(this._app.UI.Path(this.ID, "upkeep_cost"), string.Format(App.Localize("@STATION_UPKEEP_COST"), (object)GameSession.CalculateStationUpkeepCost(this._app.GameDatabase, this._app.AssetDatabase, stationInfo).ToString()));
            if (stationInfo.DesignInfo.StationType == StationType.NAVAL)
            {
                this._app.UI.SetText(this._app.UI.Path(this.ID, "naval_capacity"), string.Format(App.Localize("@STATION_FLEET_CAPACITY"), (object)this._app.GameDatabase.GetSystemSupportedCruiserEquivalent(this._app.Game, orbitalObjectInfo2.StarSystemID, this._app.LocalPlayer.ID).ToString()));
            }
            else
            {
                this._app.UI.SetVisible(this._app.UI.Path(this.ID, "naval_capacity"), false);
            }
            StarSystemInfo starSystemInfo = this._app.GameDatabase.GetStarSystemInfo(orbitalObjectInfo2.StarSystemID);

            this._app.UI.SetText("gameStationName", orbitalObjectInfo1.Name);
            this._enteredStationName = orbitalObjectInfo2.Name;
            this._app.UI.SetText(this._app.UI.Path(this.ID, "system_name"), string.Format(App.Localize("@STATION_BUILT"), (object)starSystemInfo.Name).ToUpperInvariant());
            this._cameraReduced                 = new OrbitCameraController(this._app);
            this._cameraReduced.MinDistance     = 1002.5f;
            this._cameraReduced.MaxDistance     = 10000f;
            this._cameraReduced.DesiredDistance = 2000f;
            this._cameraReduced.DesiredYaw      = MathHelper.DegreesToRadians(45f);
            this._cameraReduced.DesiredPitch    = -MathHelper.DegreesToRadians(25f);
            this._cameraReduced.SnapToDesiredPosition();
            this._starmapReduced = new StarMap(this._app, this._app.Game, this._sky);
            this._starmapReduced.Initialize(this._crits);
            this._starmapReduced.SetCamera(this._cameraReduced);
            this._starmapReduced.FocusEnabled = false;
            this._starmapReduced.PostSetProp("Selected", this._starmapReduced.Systems.Reverse[starSystemInfo.ID].ObjectID);
            this._starmapReduced.PostSetProp("CullCenter", this._app.GameDatabase.GetStarSystemInfo(starSystemInfo.ID).Origin);
            this._starmapReduced.PostSetProp("CullRadius", 15f);
            DesignInfo di = DesignLab.CreateStationDesignInfo(this._app.AssetDatabase, this._app.GameDatabase, this._app.LocalPlayer.ID, stationInfo.DesignInfo.StationType, stationInfo.DesignInfo.StationLevel, false);

            this._stationModel = new StarSystemDummyOccupant(this._app, this._app.AssetDatabase.ShipSections.First <ShipSectionAsset>((Func <ShipSectionAsset, bool>)(x => x.FileName == di.DesignSections[0].FilePath)).ModelName, stationInfo.DesignInfo.StationType);
            this._stationModel.PostSetScale(1f / 500f);
            this._stationModel.PostSetPosition(this._trans);
        }
示例#8
0
        /// <summary>
        /// 获取所有的车站信息集合
        /// </summary>
        /// <returns>所有信息</returns>
        public ObservableCollection <StationInfo> SelectAllCollection()
        {
            ObservableCollection <StationInfo> datas = new ObservableCollection <StationInfo>();
            SqlStatement stmt = _session.CreateSqlStatement();

            stmt.AppendString("select * from StationInfo");
            stmt.StatementType = SqlStatementType.Select;
            GenDataReader reader = _session.ExcecuteReader(stmt);

            while (reader.Read())
            {
                StationInfo dao = new StationInfo();
                DataReaderToEntity(reader, dao);
                datas.Add(dao);
            }
            reader.Close();
            return(datas);
        }
示例#9
0
 IEnumerator SpawnNPC(StationInfo st)
 {
     for (int i = 0; i < st.PeopleGetOn; i++)
     {
         int Dir = Random.value > 0.5 ? 1 : -1;
         var GO  = Instantiate(CatNPCPrefab, new Vector3(Dir * 160, -60, 0), Quaternion.identity);
         GO.GetComponent <CatNPC>().Dir         = -Dir;
         GO.GetComponent <CatNPC>().m_Character = m_Character;
         GO.transform.localScale = Random.Range(1f, 1.75f) * Vector3.one;
         //if (GO.GetComponent<JellySprite>())
         //{
         //    GO.GetComponent<JellySprite>().AddForce(new Vector2(-Dir, 1) * 10000000);
         //    print("???")
         //}
         nowNPC.Add(GO.GetComponent <NPC>());
         yield return(new WaitForSeconds(Random.Range(0.25f, 0.75f)));
     }
 }
示例#10
0
        private IEnumerator <IYieldInstruction> LoadExternalAssetsForStation(StationInfo stationInfo, FashionGameStation station, Action <FashionGameStation> onResult)
        {
            ClientAssetRepository assetRepo = GameFacade.Instance.RetrieveProxy <ClientAssetRepository>();
            int loadingSounds = 0;

            foreach (string soundPath in stationInfo.SoundPaths)
            {
                loadingSounds++;
                assetRepo.LoadAssetFromPath <SoundAsset>(soundPath, delegate(SoundAsset asset)
                {
                    loadingSounds--;
                    station.AddActivationSound(asset.AudioClip);
                });
            }

            int loadingAnimation = 0;

            if (stationInfo.WorkingAnimationPath != null)
            {
                loadingAnimation++;
                SetupWorkerAnimation(stationInfo.WorkingAnimationPath, stationInfo, station, delegate(AnimationClip clip)
                {
                    loadingAnimation--;
                    station.SetWorkingAnimation(clip);
                });
            }

            if (stationInfo.IdleAnimationPath != null)
            {
                loadingAnimation++;
                SetupWorkerAnimation(stationInfo.IdleAnimationPath, stationInfo, station, delegate(AnimationClip clip)
                {
                    loadingAnimation--;
                    station.SetIdleAnimation(clip);
                });
            }

            yield return(new YieldWhile(delegate()
            {
                return loadingSounds != 0 || loadingAnimation != 0;
            }));

            onResult(station);
        }
示例#11
0
        public static TemplatePaperData CreateTransportDescriptionData(Job job, string trainName, List <Car> jobCars, List <Tuple <TrainCarType, string> > carsInfo, int pageNum = 0, int totalPages = 0)
        {
            string jobTitle = (job.jobType == PassJobType.Express) ? EXPRESS_JOB_TITLE : COMMUTE_JOB_TITLE;

            string description;

            if (job.jobType == PassJobType.Express)
            {
                description = $"Transport {trainName} to {job.chainData.chainDestinationYardId}";

                if (PassengerJobs.Settings.UseCustomWages)
                {
                    float bonusAmount = Mathf.Round(PassengerJobGenerator.BONUS_TO_BASE_WAGE_RATIO * job.GetBasePaymentForTheJob() / 1000f);
                    description += $" (${bonusAmount}k bonus with on-time completion)";
                }
            }
            else
            {
                description = $"Transport a commuter train to {job.chainData.chainDestinationYardId}";
            }

            string trainLength = jobCars.Sum(c => c.length).ToString("F") + " m";
            string trainMass   = (GetLoadedConsistMass(jobCars) * 0.001f).ToString("F") + " t";
            string trainValue  = "$" + (GetTrainValue(jobCars) / 1000000f).ToString("F") + "m";
            string timeLimit   = (job.TimeLimit > 0) ? (Mathf.FloorToInt(job.TimeLimit / 60f) + " min") : "No bonus";
            string payment     = job.GetBasePaymentForTheJob().ToString();

            StationInfo startStation = ExtractStationFromId(job.chainData.chainOriginYardId);
            StationInfo endStation   = ExtractStationFromId(job.chainData.chainDestinationYardId);

            return(new FrontPageTemplatePaperData(
                       jobTitle, "", job.ID, PASS_JOB_COLOR, description,
                       job.requiredLicenses, new List <CargoType>()
            {
                CargoType.Passengers
            },
                       Enumerable.Repeat(CargoType.Passengers, jobCars.Count).ToList(),
                       "", "", TemplatePaperData.NOT_USED_COLOR,
                       startStation.Name, startStation.Type, startStation.StationColor,
                       endStation.Name, endStation.Type, endStation.StationColor,
                       carsInfo, trainLength, trainMass, trainValue, timeLimit, payment,
                       (pageNum > 0) ? pageNum.ToString() : "",
                       (totalPages > 0) ? totalPages.ToString() : ""));
        }
示例#12
0
        private async void Test()
        {
            try
            {
                //Open connection
                var conn = OpenSprinklerApp.ViewModels.AppModel.Current.Connection;                 // await OpenSprinklerNet.OpenSprinklerConnection.OpenAsync("http://192.168.1.15:80", "opendoor");
                //Get controller metadata
                ControllerInfo controllerInfo = await conn.GetControllerInfoAsync();

                //controllerInfoView.DataContext = controllerInfo;
                //Get current settings
                ControllerSettingsInfo settings = await conn.GetControllerSettingsAsync();

                //Get all programs
                ProgramDetailsInfo programs = await conn.GetProgamDetailsAsync();

                //Get info about the stations
                StationInfo stationInfo = await conn.GetStationsAsync();

                //Check whether sprinkler '1' is on
                bool isOn = await conn.QueryStationStatusAsync(1);

                //Check on/off status of all sprinklers
                var stations = await conn.QueryStationStatusesAsync();

                //Check if in manual mode
                if (settings.ManualMode == OpenSprinklerNet.Status.On)
                {
                    //Turn sprinkler 3 on
                    await conn.SetStationStatusAsync(3, OpenSprinklerNet.Status.On);

                    await Task.Delay(2000);

                    var bit = await conn.QueryStationStatusAsync(3);

                    stations = await conn.QueryStationStatusesAsync();

                    System.Diagnostics.Debug.Assert(bit);
                    //Turn sprinkler 3 off
                    await conn.SetStationStatusAsync(3, OpenSprinklerNet.Status.Off);
                }
            }
            catch { }
        }
示例#13
0
    public static void SerializeStationInfoList2Xml()
    {
        StationInfoList list = new StationInfoList();

        StationInfo station = new StationInfo();

        station.Index                              = 5;
        station.Name                               = "赵营";
        station.EngName                            = "ZhaoYing";
        station.BuyTicketPointCount                = 48;
        station.BuyTicketRestAreaPointCount        = 8;
        station.EnterCheckTicketPointCount         = 35;
        station.EnterCheckTicketRestAreaPointCount = 8;
        station.WaitTrainUpPointCount              = 144;
        station.WaitTrainDownPointCount            = 144;
        station.DownTrainUpPointCount              = 72;
        station.DownTrainDownPointCount            = 72;
        station.ExitCheckTicketPointCount          = 35;
        station.ExitCheckTicketRestAreaPointCount  = 8;
        station.EnterStationUpMaxNpcCount          = 15;
        station.EnterStationDownMaxNpcCount        = 15;
        station.ExitStationUpMaxNpcCount           = 15;
        station.ExitStationUpGenerateNpcCount      = 10;
        station.ExitStationDownMaxNpcCount         = 15;
        station.ExitStationDownGenerateNpcCount    = 10;
        station.GenerateNpcIntervalTime            = 2.0f;

        list.stationInfoList.Add(station);

        if (File.Exists(AppConfigPath.StationInfoXmlPath))
        {
            File.Delete(AppConfigPath.StationInfoXmlPath);
        }

        FileStream fileStream = new FileStream(AppConfigPath.StationInfoXmlPath,
                                               FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
        StreamWriter  sw  = new StreamWriter(fileStream, System.Text.Encoding.UTF8);
        XmlSerializer xml = new XmlSerializer(list.GetType());

        xml.Serialize(sw, list);
        sw.Close();
        fileStream.Close();
    }
示例#14
0
        private void RegistrationStatusAction(CompanyInfo companyInfo, User user, StationInfo stationInfo, bool b)
        {
            if (!b)
            {
                Close();
                Application.Exit();
                return;
            }


            Utils.CorporateInfo = companyInfo;
            Utils.CurrentUser   = user;
            Utils.StationInfo   = stationInfo;

            if (!CheckAppDB())
            {
                MetroMessageBox.Show(this, _mssg.Length > 0 ? _mssg : "This application is unable to communicate with the registered database. Kindly ensure that all connection parameters are properly configured", "Configuration Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
                Application.Exit();
                return;
            }

            //Update local Corporate Info
            //var corporateInfo = new CorporateInfo
            //{
            //    StationName = companyInfo.StationName,
            //    Address = companyInfo.Address,
            //    StationKey = companyInfo.StationKey,
            //    HostServerAddress = companyInfo.HostServerAddress,
            //    PhoneNumbers = companyInfo.PhoneNumbers,
            //    MobileNumber = companyInfo.MobileNumber,
            //    TimeStampRegistered = DateMap.CurrentTimeStamp(),
            //};

            string msg;

            //var retVal = ServiceProvider.Instance().GetCorporateInfoServices().AddCorporateInfo(corporateInfo, out msg);
            _frmCorporateRegistration.Close();
            _frmCorporateRegistration.Visible = false;


            Close();
        }
示例#15
0
        public frmLogin(out bool flag)
        {
            InitializeComponent();
            EventHandler();
            flag         = true;
            _stationInfo = new StationInfo();

            #region Locally Setup
            //if (!loadSettings())
            //{
            //    flag = false;
            //}
            //else
            //{
            //    EventHandler();
            //    flag = true;
            //}
            #endregion
        }
示例#16
0
        public IActionResult Install([FromForm] StationInfo info)
        {
            if (string.IsNullOrWhiteSpace(info.Name) || string.IsNullOrWhiteSpace(info.Type))
            {
                return(Json(ApiResult.Error(ErrorCode.LogicalError, "参数错误")));
            }
            ZeroStationType type;

            switch (info.Type.ToLower())
            {
            case "pub":
                type = ZeroStationType.Publish;
                break;

            case "vote":
                type = ZeroStationType.Vote;
                break;

            case "api":
                type = ZeroStationType.Api;
                break;

            default:
                return(Json(ApiResult.Error(ErrorCode.LogicalError, "参数错误")));
            }
            var config = new StationConfig
            {
                Name         = info.Name,
                Description  = info.Description,
                StationType  = type,
                ShortName    = info.short_name ?? info.Name,
                StationAlias = string.IsNullOrWhiteSpace(info.Alias)
                    ? new List <string>()
                    : info.Alias.Trim().Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList()
            };

            if (!ZeroApplication.Config.Check(config, config))
            {
                return(Json(ApiResult.Error(ErrorCode.LogicalError, "名称存在重复")));
            }

            return(Json(ZeroManager.Install(config)));
        }
示例#17
0
        public async Task <IActionResult> DeleteStationInfo([FromRoute] int StationId)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            StationInfo Station = await _greenHouseContext.StationInfo.SingleOrDefaultAsync(m => m.StationId == StationId);

            if (Station == null)
            {
                return(NotFound());
            }

            _greenHouseContext.StationInfo.Remove(Station);
            await _greenHouseContext.SaveChangesAsync();

            return(NoContent());
        }
示例#18
0
        static public bool BusinessVerify(IDBProvider dBProvider, ILoginUser userData)
        {
            _stationInfo = StationInfo.GetLocateStationInfo(_serverName, dBProvider);
            if (_stationInfo == null)
            {
                MessageBox.Show("当前站点信息尚未配置,请联系管理员。", "提示");
                return(false);
            }

            //判断当前用户是否能够登录当前科室的系统
            UserModel um = new UserModel(dBProvider);
            List <UserReleationData> urds = um.GetUserDepartmentRoleInfos(userData.UserId);

            if (urds == null)
            {
                MessageBox.Show("未找到对应科室信息不能进行登录,请联系管理员。", "提示");
                return(false);
            }

            string departmentId = _stationInfo.DepartmentId;

            int index = urds.FindIndex(T => T.科室ID == departmentId);

            if (index < 0)
            {
                MessageBox.Show("当前科室 [" + _stationInfo.DepartmentName + "] 未配置该用户不能进行登录,请联系管理员。", "提示");
                return(false);
            }

            UserReleationData urd = urds[index];

            if (string.IsNullOrEmpty(urd.角色ID))
            {
                MessageBox.Show("当前用户尚未分配角色不能进行登录,请联系管理员。", "提示");
                return(false);
            }

            userData.RoleId       = urd.角色ID;
            userData.DepartmentId = urd.科室ID;

            return(true);
        }
示例#19
0
        internal Nullable <StationInfo> loadStationInfo(String NameMAC)
        {
            Nullable <StationInfo> si = null;

            using (ConnectionHandle conn = new ConnectionHandle(connectionpool, connectionstring))
            {
                String query = "select roomname,xpos,ypos from stations where namemac=@namemac";
                try
                {
                    if (!connectioncheck(conn))
                    {
                        throw new Exception("Connection is not open");
                    }
                    using (var cmd = new NpgsqlCommand(query, conn.conn))
                    {
                        cmd.Parameters.AddWithValue("namemac", NameMAC);
                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                StationInfo si2 = new StationInfo();
                                si2.NameMAC  = NameMAC;
                                si2.RoomName = reader.GetString(0);
                                si2.X        = reader.GetFloat(1);
                                si2.Y        = reader.GetFloat(2);
                                si           = si2;
                            }
                            else
                            {
                                si = null;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    manageDbException(ex, conn.conn, true);
                    si = null;
                }
            }
            return(si);
        }
示例#20
0
 public static StationInfo GetStationInfo(string stationId)
 {
     StationInfo info = new StationInfo();
     Dictionary<string, float> passengersMap = new Dictionary<string, float>();
     Dictionary<string, string> unparsedMap = ConfigReader.GetConfig().GetField("levels").GetField(stationId).GetField("passengersMap").ToDictionary();
     foreach (var item in unparsedMap)
     {
         float value = (float)Convert.ToDouble(item.Value);
         passengersMap.Add(item.Key, value);
     }
     info.PassengersMap = passengersMap;
     info.Name = ConfigReader.GetConfig().GetField("levels").GetField(stationId).GetField("name").str;
     info.CheckPointsCount =
         (int)ConfigReader.GetConfig().GetField("levels").GetField(stationId).GetField("count").n;
     DoorsTimer.DoorsOpenMode openMode =
         (DoorsTimer.DoorsOpenMode)
             Enum.Parse(typeof(DoorsTimer.DoorsOpenMode), ConfigReader.GetConfig().GetField("levels").GetField(stationId).GetField("doorsOpenMode").str);
     info.DoorsOpenMode = openMode;
     return info;
 }
示例#21
0
        public ActionResult Create(int pathId, string stationName, int stationCode, string status)
        {
            StationInfo station = new StationInfo();

            station.StationName = stationName;
            station.StationCode = stationCode;
            if (status == null)
            {
                station.Status = 0;
            }
            else
            {
                station.Status = int.Parse(status);
            }
            PathInfo path = Container.Instance.Resolve <IPathInfoService>().GetEntity(pathId);

            station.Path = path;
            Container.Instance.Resolve <IStationInfoService>().Add(station);
            return(View());
        }
        public ModelInvokeResult <StationInfoPK> Nullify(string strStationId)
        {
            ModelInvokeResult <StationInfoPK> result = new ModelInvokeResult <StationInfoPK> {
                Success = true
            };

            try
            {
                List <IBatisNetBatchStatement> statements = new List <IBatisNetBatchStatement>();
                Guid?_StationId = strStationId.ToGuid();
                if (_StationId == null)
                {
                    result.Success   = false;
                    result.ErrorCode = 59996;
                    return(result);
                }
                StationInfo stationInfo = new StationInfo {
                    StationId = _StationId
                };                                                                   //没有Status 字段
                /***********************begin 自定义代码*******************/
                stationInfo.OperatedBy = NormalSession.UserId.ToGuid();
                stationInfo.OperatedOn = DateTime.Now;
                /***********************end 自定义代码*********************/
                statements.Add(new IBatisNetBatchStatement {
                    StatementName = stationInfo.GetUpdateMethodName(), ParameterObject = stationInfo.ToStringObjectDictionary(false), Type = SqlExecuteType.UPDATE
                });
                /***********************begin 自定义代码*******************/
                /***********************此处添加自定义代码*****************/
                /***********************end 自定义代码*********************/
                BuilderFactory.DefaultBulder().ExecuteNativeSqlNoneQuery(statements);
                result.instance = new StationInfoPK {
                    StationId = _StationId
                };
            }
            catch (Exception ex)
            {
                result.Success      = false;
                result.ErrorMessage = ex.Message;
            }
            return(result);
        }
示例#23
0
文件: MES.cs 项目: jtzhang163/TengDa
        public static void GetInfo()
        {
            if (!Current.Mes.IsPingSuccess)
            {
                return;
            }

            string      msg = string.Empty;
            string      ip  = MES.LocalIPAddr.ToString();
            ProcessInfo pi  = Tafel.MES.MES.GetProcessInfo(new IP {
                IPAddress = ip
            }, out msg);

            if (string.IsNullOrEmpty(msg))//成功获取到
            {
                if (pi == null)
                {
                    Error.Alert("无法获取到工序工位信息");
                    return;
                }
                Current.Option.CurrentProcess = string.Format("{0},{1}", pi.ProcessName, pi.ProcessCode);
            }
            else
            {
                Error.Alert(msg);
            }


            StationInfo si = Tafel.MES.MES.GetStationInfo(new IpAndProcess {
                IPAddress = ip, ProcessCode = pi.ProcessCode
            }, out msg);

            if (string.IsNullOrEmpty(msg))//成功获取到
            {
                Current.Option.CurrentStation = string.Format("{0},{1}", si.StationName, si.StationCode);
            }
            else
            {
                Error.Alert(msg);
            }
        }
示例#24
0
        /// <summary>
        /// 更新车站信息
        /// </summary>
        /// <param name="dao">数据对象</param>
        /// <returns>成功/失败</returns>
        public bool Update(StationInfo dao)
        {
            SqlStatement stmt = _session.CreateSqlStatement();

            stmt.AppendString("update StationInfo set ");
            stmt.AppendString("ID=");
            stmt.AppendParameter(_session.MakeInParameter("ID", dao.ID, SqlDbType.Int));
            stmt.AppendString(",GroupID=");
            stmt.AppendParameter(_session.MakeInParameter("GroupID", dao.GroupID, SqlDbType.UniqueIdentifier));
            stmt.AppendString(",RegionID=");
            stmt.AppendParameter(_session.MakeInParameter("RegionID", dao.RegionID, SqlDbType.Int));
            stmt.AppendString(",AreaID=");
            stmt.AppendParameter(_session.MakeInParameter("AreaID", dao.AreaID, SqlDbType.Int));
            stmt.AppendString(",StationID=");
            stmt.AppendParameter(_session.MakeInParameter("StationID", dao.StationID, SqlDbType.Int));
            stmt.AppendString(" where ");
            stmt.AppendString("StationName=");
            stmt.AppendParameter(_session.MakeInParameter("StationName", dao.StationName, SqlDbType.NVarChar));
            stmt.StatementType = SqlStatementType.Update;
            return(_session.Excecute(stmt).RowsAffected > 0);
        }
示例#25
0
    public static StationInfo GetStationInfo(string stationId)
    {
        StationInfo info = new StationInfo();
        Dictionary <string, float>  passengersMap = new Dictionary <string, float>();
        Dictionary <string, string> unparsedMap   = ConfigReader.GetConfig().GetField("levels").GetField(stationId).GetField("passengersMap").ToDictionary();

        foreach (var item in unparsedMap)
        {
            float value = (float)Convert.ToDouble(item.Value);
            passengersMap.Add(item.Key, value);
        }
        info.PassengersMap    = passengersMap;
        info.Name             = ConfigReader.GetConfig().GetField("levels").GetField(stationId).GetField("name").str;
        info.CheckPointsCount =
            (int)ConfigReader.GetConfig().GetField("levels").GetField(stationId).GetField("count").n;
        DoorsTimer.DoorsOpenMode openMode =
            (DoorsTimer.DoorsOpenMode)
            Enum.Parse(typeof(DoorsTimer.DoorsOpenMode), ConfigReader.GetConfig().GetField("levels").GetField(stationId).GetField("doorsOpenMode").str);
        info.DoorsOpenMode = openMode;
        return(info);
    }
        /// <summary>
        /// 广播可以取放
        /// </summary>
        /// <returns></returns>
        public bool BroadcastPickPlace()
        {
            Log.Debug("SendPickPlace " + 0);
            SendPickPlace(0);

            for (int i = 0; i < EquipmentInfo.STATION_NUM - 1; i++)
            {
                StationInfo stationInfo = AppInfo.EquipmentInfo.GetStationInfo(i);
                if (stationInfo.Work)
                {
                    Log.Debug("SendPickPlace " + (i + 1));
                    SendPickPlace(i + 1);
                }
                else
                {
                    break;
                }
            }

            return(true);
        }
示例#27
0
        internal void RapidWindEvt(string json)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            try {
                // evt[0] = timestamp
                // evt[1] = speed (m/s)
                // evt[2] = direction
                WindObj = serializer.Deserialize <WindData>(json);

                StationInfo si = wf_station.FindStationSky(WindObj.serial_number);
                if (si.rapid)
                {
                    WeatherFlowNS.NS.RaiseRapidEvent(this, new RapidEventArgs(WindObj));
                    WeatherFlowNS.NS.RaiseUpdateEvent(this, new UpdateEventArgs((int)WindObj.ob[0], WindObj.serial_number + "_r", DataType.WIND));
                }
            } catch (Exception ex) {
                WFLogging.Error("Failed to deserialize rapid wind event: " + ex.Message);
                WFLogging.Error(json);
            }
        }
示例#28
0
        /// <summary>
        /// DBに無線局情報を登録します。
        /// </summary>
        /// <param name="station">登録する無線局情報</param>
        public void Update(StationInfo station)
        {
            bool hasRows;

            using (SQLiteCommand cmd = conn.CreateCommand()) {
                cmd.CommandText = "select * from Station where Callsign = '" + station.Callsign + "';";
                using (var reader = cmd.ExecuteReader()) {
                    hasRows = reader.HasRows;
                }
                if (hasRows)
                {
                    cmd.CommandText = "update Station set Addresses = '" + string.Join(",", station.Address.ToArray()) + "', Updated = '" + Date.NowToString() + "' where Callsign = '" + station.Callsign + "';";
                    cmd.ExecuteNonQuery();
                }
                else
                {
                    cmd.CommandText = "insert into Station(Callsign, Addresses, Updated) values('" + station.Callsign + "', '" + string.Join(",", station.Address.ToArray()) + "', '" + Date.NowToString() + "');";
                    cmd.ExecuteNonQuery();
                }
            }
        }
示例#29
0
        public bool WriteStationInfo(string[] str)
        {
            CRLStationInfo si = StationInfo.Find(
                delegate(CRLStationInfo ss)
            {
                return(ss.stationno == int.Parse(str[0]));
            }
                );

            if (si != null)
            {
                byte[] byt = new byte[20];//leo 30 to 20
                for (int i = 1; i < str.Length; i++)
                {
                    Array.Copy(GetHexBytes(str[i]), 0, byt, (i - 1) * 2, 2);
                }
                ////mPLC.Connect();
                //if (!mPLC.Write(50, si.value, 20, byt))//leo 30 to 20  PLCList[csi.key_ip]
                //if (PLCList[si.key_ip].Write(50, si.value, 20, byt))
                //{
                //    mPLC.Connect();
                //    return false;
                //}
                if (si.cFlag)
                {
                    PLCList[si.key_ip].Write(50, si.value, 20, byt);
                }
                ////PLC连不上时临时使用
                //si.taskno = int.Parse(str[1]);
                //si.barcode1 = int.Parse(str[2]) * 65536 + int.Parse(str[3]);
                //si.barcode2 = int.Parse(str[3]);
                //si.goodstype = int.Parse(str[4]);
                //si.fromstation = int.Parse(str[5]);
                //si.tostation = int.Parse(str[6]);
                //si.weight1 = int.Parse(str[7]);
                //si.weight2 = int.Parse(str[8]);
                //si.checkinfo = int.Parse(str[9]);
            }
            return(true);
        }
示例#30
0
        public static void GetStationInfo(CommandArg[] args)
        {
            string outPath = Path.Combine(FoxyToolsMain.ModEntry.Path, "station.txt");

            try
            {
                using (var fs = new FileStream(outPath, FileMode.Create))
                {
                    using (var sw = new StreamWriter(fs))
                    {
                        var stations = GameObject.FindObjectsOfType <StationController>();
                        foreach (StationController station in stations)
                        {
                            StationInfo info = station.stationInfo;
                            sw.WriteLine($"[{info.Name} ({info.YardID})]");

                            // job rules
                            var ruleSet = station.proceduralJobsRuleset;
                            sw.WriteLine("\tInputs:");
                            foreach (CargoType input in ruleSet.inputCargoGroups.SelectMany(group => group.cargoTypes))
                            {
                                sw.WriteLine($"\t\t{input.GetCargoName()}");
                            }

                            sw.WriteLine("\n\tOutputs:");
                            foreach (CargoType output in ruleSet.outputCargoGroups.SelectMany(group => group.cargoTypes))
                            {
                                sw.WriteLine($"\t\t{output.GetCargoName()}");
                            }

                            sw.WriteLine();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("Couldn't open output file:\n" + ex.Message);
            }
        }
示例#31
0
        protected void PopulateModulesList(StationInfo station)
        {
            this.App.UI.SetPropertyString("moduleDescriptionText", "text", "");
            this._selectedStation = station;
            StationModuleQueue.UpdateStationMapsForFaction(this.App.LocalPlayer.Faction.Name);
            List <LogicalModuleMount> stationModuleMounts = this.App.Game.GetStationModuleMounts(station);

            this.App.UI.ClearItems("stationModules");
            StationModuleQueue.UpdateStationMapsForFaction(this.App.LocalPlayer.Faction.Name);
            StationModuleQueue.InitializeQueuedItemMap(this.App.Game, station, this._queuedItemMap);
            int userItemId = 0;

            foreach (StationModules.StationModule uniqueStationModule in StationModuleQueue.EnumerateUniqueStationModules(this.App.Game, station))
            {
                this.App.UI.AddItem("stationModules", "", userItemId, "");
                string itemGlobalId = this.App.UI.GetItemGlobalID("stationModules", "", userItemId, "");
                this.App.UI.SetPropertyString(itemGlobalId, "id", "module" + (object)uniqueStationModule.SMType);
                this.App.UI.SetPropertyString(this.App.UI.Path(itemGlobalId, "huverbuttin"), "id", station.OrbitalObjectID.ToString() + "|" + (object)uniqueStationModule.SMType);
                this.App.UI.SetPropertyString(this.App.UI.Path(itemGlobalId, "module_label"), "text", uniqueStationModule.Name);
                this.App.UI.SetVisible(this.App.UI.Path(itemGlobalId, "module_up"), true);
                this.App.UI.SetVisible(this.App.UI.Path(itemGlobalId, "module_down"), true);
                this.App.UI.SetVisible(this.App.UI.Path(itemGlobalId, "module_max"), true);
                this.App.UI.SetPropertyString(this.App.UI.Path(itemGlobalId, "module_up"), "id", station.OrbitalObjectID.ToString() + "|" + uniqueStationModule.SMType.ToString() + "|module_up");
                this.App.UI.SetPropertyString(this.App.UI.Path(itemGlobalId, "module_down"), "id", station.OrbitalObjectID.ToString() + "|" + uniqueStationModule.SMType.ToString() + "|module_down");
                this.App.UI.SetPropertyString(this.App.UI.Path(itemGlobalId, "module_max"), "id", station.OrbitalObjectID.ToString() + "|" + uniqueStationModule.SMType.ToString() + "|module_max");
                ++userItemId;
            }
            if (stationModuleMounts.FirstOrDefault <LogicalModuleMount>((Func <LogicalModuleMount, bool>)(x => x.ModuleType == "AlienHabitation")) != null && this._queuedItemMap.Where <KeyValuePair <ModuleEnums.StationModuleType, int> >((Func <KeyValuePair <ModuleEnums.StationModuleType, int>, bool>)(x => AssetDatabase.StationModuleTypeToMountTypeMap[x.Key].ToString() == "AlienHabitation")).Count <KeyValuePair <ModuleEnums.StationModuleType, int> >() == 0)
            {
                this.AddBlankModule(userItemId++, station, ModuleEnums.StationModuleType.AlienHabitation);
            }
            if (stationModuleMounts.FirstOrDefault <LogicalModuleMount>((Func <LogicalModuleMount, bool>)(x => x.ModuleType == "LargeAlienHabitation")) != null && this._queuedItemMap.Where <KeyValuePair <ModuleEnums.StationModuleType, int> >((Func <KeyValuePair <ModuleEnums.StationModuleType, int>, bool>)(x => AssetDatabase.StationModuleTypeToMountTypeMap[x.Key].ToString() == "LargeAlienHabitation")).Count <KeyValuePair <ModuleEnums.StationModuleType, int> >() == 0)
            {
                int cur = userItemId;
                int num = cur + 1;
                this.AddBlankModule(cur, station, ModuleEnums.StationModuleType.LargeAlienHabitation);
            }
            this.SyncModuleItems();
            this.SyncBuildQueue();
        }
示例#32
0
        protected void gvStationGroupStations_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            AdminController aCont = new AdminController();

            txtSelectedStationGroupStations.Value = (gvStationGroupStations.SelectedRow.FindControl("hdngvStationGroupStationId") as HiddenField).Value;
            StationInfo station = aCont.Get_StationById(Convert.ToInt32(txtSelectedStationGroupStations.Value));
            bool        dupe    = false;

            if (station.Id != -1)
            {
                //first, check for dupes
                foreach (ListItem li in lbxStationsInGroupModal.Items)
                {
                    if (li.Value == station.Id.ToString())
                    {
                        dupe = true;
                    }
                }
                if (!dupe)
                {
                    aCont.Add_StationsInGroup(PortalId, station.Id, Convert.ToInt32(txtSelectedStationGroup.Value));
                    lbxStationsInGroupModal.Items.Add(new ListItem(station.StationName, station.Id.ToString()));
                    lbxStationGroupStations.Items.Add(new ListItem(station.StationName, station.Id.ToString()));
                    //btnDeleteTapeFormat.Enabled = true;
                    btnRemoveStationFromGroup.Enabled        = true;
                    txtStationGroupStationsCreatedBy.Value   = station.CreatedById.ToString();
                    txtStationGroupStationsCreatedDate.Value = station.DateCreated.Ticks.ToString();
                    lblStationGroupStationsModalMessage.Text = "Station added to Group.";
                }
                else
                {
                    lblStationGroupStationsModalMessage.Text = "That station is already in this group.";
                }
            }
            else
            {
                btnRemoveStationFromGroup.Enabled        = false;
                lblStationGroupStationsModalMessage.Text = "There was an error loading this Station.";
            }
        }
示例#33
0
        public static List <StationInfo> GetStations(int lscId, string lscName, string connectionString)
        {
            var records = new List <StationInfo>();
            var command = @"SELECT 0 AS [Area2ID],[CityName] AS [Area2Name],0 AS [Area3ID],[RegionName] AS [Area3Name],[StaId],[StaName],[UpdateTime] FROM [dbo].[RM_StaInfo];";

            SqlHelper.TestConnection(connectionString);
            using (var rdr = SqlHelper.ExecuteReader(connectionString, System.Data.CommandType.Text, command, null)) {
                while (rdr.Read())
                {
                    var station = new StationInfo();
                    station.LscID          = lscId;
                    station.LscName        = lscName;
                    station.Area1ID        = 0;
                    station.Area1Name      = String.Empty;
                    station.Area2ID        = ComUtility.DBNullInt32Handler(rdr["Area2ID"]);
                    station.Area2Name      = ComUtility.DBNullStringHandler(rdr["Area2Name"]);
                    station.Area3ID        = ComUtility.DBNullInt32Handler(rdr["Area3ID"]);
                    station.Area3Name      = ComUtility.DBNullStringHandler(rdr["Area3Name"]);
                    station.StaID          = 0;
                    station.StaName        = ComUtility.DBNullStringHandler(rdr["StaName"]);
                    station.StaDesc        = String.Empty;
                    station.StaTypeID      = 0;
                    station.StaTypeName    = String.Empty;
                    station.StaFeatureID   = 0;
                    station.StaFeatureName = String.Empty;
                    station.BuildingID     = 0;
                    station.BuildingName   = String.Empty;
                    station.LocationWay    = EnmMapType.GPS;
                    station.Longitude      = 0;
                    station.Latitude       = 0;
                    station.MapDesc        = String.Empty;
                    station.STDStationID   = String.Empty;
                    station.MID            = ComUtility.DBNullStringHandler(rdr["StaID"]);
                    station.DevCount       = 0;
                    station.Enabled        = true;
                    records.Add(station);
                }
            }
            return(records);
        }
示例#34
0
        public void GetStation()
        {
            string strProcedureName =
                string.Format(
                    "{0}.{1}",
                    className,
                    MethodBase.GetCurrentMethod().Name);

            WriteLog.Instance.WriteBeginSplitter(strProcedureName);
            try
            {
                int    errCode = 0;
                string errText = "";
                station = new StationInfo();

                IRAPSystemClient.Instance.sfn_GetInfo_Station(
                    IRAPUser.Instance.CommunityID,
                    IRAPUser.Instance.SysLogID,
                    ref station,
                    out errCode,
                    out errText);
                WriteLog.Instance.Write(
                    string.Format("({0}){1}", errCode, errText),
                    strProcedureName);
                if (errCode != 0)
                {
                    throw new Exception(errText);
                }
            }
            catch (Exception error)
            {
                WriteLog.Instance.Write(error.Message, strProcedureName);
                WriteLog.Instance.Write(error.StackTrace, strProcedureName);
                throw error;
            }
            finally
            {
                WriteLog.Instance.WriteEndSplitter(strProcedureName);
            }
        }
示例#35
0
        internal static void ConfirmStationQueuedItems(
            GameSession game,
            StationInfo station,
            Dictionary <ModuleEnums.StationModuleType, int> queuedItemMap)
        {
            List <LogicalModuleMount> stationModuleMounts = game.GetAvailableStationModuleMounts(station);

            foreach (KeyValuePair <ModuleEnums.StationModuleType, int> keyValuePair in queuedItemMap.ToList <KeyValuePair <ModuleEnums.StationModuleType, int> >())
            {
                KeyValuePair <ModuleEnums.StationModuleType, int> thing = keyValuePair;
                int num = thing.Value;
                while (num > 0)
                {
                    List <DesignModuleInfo>   list1   = game.GameDatabase.GetQueuedStationModules(station.DesignInfo.DesignSections[0]).ToList <DesignModuleInfo>();
                    List <DesignModuleInfo>   modules = station.DesignInfo.DesignSections[0].Modules;
                    List <LogicalModuleMount> list2   = stationModuleMounts.Where <LogicalModuleMount>((Func <LogicalModuleMount, bool>)(x => x.ModuleType == AssetDatabase.StationModuleTypeToMountTypeMap[thing.Key].ToString())).ToList <LogicalModuleMount>();
                    bool flag = false;
                    foreach (LogicalModuleMount logicalModuleMount in list2)
                    {
                        LogicalModuleMount mount = logicalModuleMount;
                        if (list1.Where <DesignModuleInfo>((Func <DesignModuleInfo, bool>)(x => x.MountNodeName == mount.NodeName)).Count <DesignModuleInfo>() == 0 && modules.Where <DesignModuleInfo>((Func <DesignModuleInfo, bool>)(x => x.MountNodeName == mount.NodeName)).Count <DesignModuleInfo>() == 0)
                        {
                            List <PlayerInfo> list3                = game.GameDatabase.GetPlayerInfos().ToList <PlayerInfo>();
                            Player            playerObject         = game.GetPlayerObject(station.PlayerID);
                            string            moduleFactionDefault = StationModuleQueue.GetModuleFactionDefault(thing.Key, playerObject.Faction);
                            int moduleId = game.GameDatabase.GetModuleID(game.AssetDatabase.GetStationModuleAsset(thing.Key, moduleFactionDefault), list3.First <PlayerInfo>((Func <PlayerInfo, bool>)(x => game.GameDatabase.GetFactionName(x.FactionID) == moduleFactionDefault)).ID);
                            game.GameDatabase.InsertQueuedStationModule(station.DesignInfo.DesignSections[0].ID, moduleId, new int?(), mount.NodeName, thing.Key);
                            --num;
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        break;
                    }
                }
                queuedItemMap[thing.Key] = 0;
            }
        }
示例#36
0
		public void TestStationInfo ()
		{
			StationInfo si = new StationInfo ();
			string[] countries = si.listCountries ();
			Assert.IsNotNull (countries);
			Assert.AreEqual (215, countries.Length);
			Assert.AreEqual ("afghanistan", countries[0]);
			Assert.AreEqual ("spain", countries[177]);
			Assert.AreEqual ("zimbabwe", countries[214]);
			
			Station[] stations = si.searchByCountry ("spain");
			Assert.IsNotNull (stations);
			foreach (Station sta in stations)
			{
				Assert.IsNotNull (sta);
				if (sta.icao == "LEBL")
					Assert.AreEqual ("Barcelona / Aeropuerto", sta.name);
			}
			
			Station[] st = si.searchByCode ("LEBL");
			Assert.IsNotNull (st);
			Assert.AreEqual (1, st.Length);
			Assert.AreEqual ("Barcelona / Aeropuerto", st[0].name);
		}
示例#37
0
	private void Cleanup () { 
		
		station = null;

		if (background != null) {
			background.Dispose();
			background = null;
		}
		if (timer != null) {
			timer.Dispose();
			timer = null;
		}

		network.Close();
		timedimage.Close();
		recognizer.Close();
		radio.Stop();
		player.Close();
		intercomView.Close();
	}
示例#38
0
	protected void OnEventRightButtonPressEvent (object o, ButtonPressEventArgs args) {
		stationIndex++;
		if (stationIndex >= stations.Count) stationIndex = stations.Count - 1;
		station = stations[stationIndex];
		ctlDrawingMeta.QueueDraw();
	}
示例#39
0
	protected void OnEventLeftButtonPressEvent (object o, ButtonPressEventArgs args) {
		stationIndex--;
		if (stationIndex < 0) stationIndex = 0;
		station = stations[stationIndex];
		ctlDrawingMeta.QueueDraw();
	}
示例#40
0
	void PlayRadioStation (string stationCallLetters) {
		for (stationIndex = 1; stationIndex < stations.Count; stationIndex++) {
			if (stations[stationIndex].CallLetters == stationCallLetters) {
				break;
			}
		}
		if (stationIndex == stations.Count) stationIndex = 0;
		station = stations[stationIndex];
		ctlDrawingMeta.QueueDraw();
	}
示例#41
0
        /// <summary>
        /// Creates a new instance of the station class and populates it with data from the specified SqlDataReader.
        /// </summary>
        protected virtual StationInfo MakeStationInfo(SqlDataReader dataReader)
        {
            StationInfo stationInfo = new StationInfo();
            stationInfo.Stationid = SqlClientUtility.GetInt32(dataReader,DbConstants.STATION.STATIONID, 0);
            stationInfo.Name = SqlClientUtility.GetString(dataReader,DbConstants.STATION.NAME, String.Empty);
            stationInfo.Province = SqlClientUtility.GetString(dataReader,DbConstants.STATION.PROVINCE, String.Empty);
            stationInfo.Company = SqlClientUtility.GetString(dataReader,DbConstants.STATION.COMPANY, String.Empty);

            return stationInfo;
        }
        /// <summary>
        /// Returns best position to move and profit
        /// </summary>
        /// <param name="maxEnergy"></param>
        /// <param name="profit"></param>
        /// <param name="robot"></param>
        /// <returns></returns>
        public Position GetBestMovePosition(int maxEnergy, out int profit, Rb robot = null)
        {
            if (robot == null)
                robot = Current.Robot;
            Position bestPosition = null;
            var bestProfit = int.MinValue;
            var posVariants = new Dictionary<Position, PositionInfo>();
            var stationsInTouch = DistanceHelper.GetNearbyStations(robot.Position, maxEnergy);

            foreach (var station in stationsInTouch)
            {
                for (var i = -Constants.EnergyCollectingDistance; i <= Constants.EnergyCollectingDistance; ++i)
                {
                    for (var j = -Constants.EnergyCollectingDistance; j <= Constants.EnergyCollectingDistance; ++j)
                    {
                        var pos = new Position(station.Position.X + i, station.Position.Y + j);
                        if(DistanceHelper.FindCost(pos, robot.Position) > maxEnergy) continue;
                        Rb attRob;
                        var stInfo = new StationInfo()
                        {
                            UsageVariant = CheckStaionUsage(station, out attRob),
                            AttackRobot = attRob
                        };
                        if(stInfo.UsageVariant == StationUseVariant.SkipOrLeave) continue;

                        if (posVariants.ContainsKey(pos))
                        {
                            posVariants[pos].NearestStations.Add(station, stInfo);
                        }
                        else
                        {
                            var posInfo = new PositionInfo
                            {
                                NearestStations = new Dictionary<EnergyStation, StationInfo> {{station, stInfo}}
                            };
                            posVariants[pos] = posInfo;
                        }
                    }
                }
            }

            foreach (var posKV in posVariants)
            {
                var pos = posKV.Key;
                var posInfo = posVariants[posKV.Key];
                var joinableStations = 0;
                var reserveStations = 0;
                posInfo.Profit = 0;
                foreach (var stationKV in posInfo.NearestStations)
                {
                    var station = stationKV.Key;
                    var stInfo = stationKV.Value;
                    posInfo.Profit += station.Energy;
                    switch (stInfo.UsageVariant)
                    {
                        case StationUseVariant.JoinOrCollect:
                            joinableStations++;
                            break;
                        case StationUseVariant.AttackOnly:
                            if (pos == stInfo.AttackRobot.Position)
                                posInfo.Profit += -50 + stInfo.AttackRobot.Energy/20;
                            else
                                posInfo.Profit -= station.Energy;
                            break;
                        case StationUseVariant.JoinReserve:
                            posInfo.Profit -= station.Energy;
                            reserveStations++;
                            break;
                    }
                }
                posInfo.Profit += (int) (posInfo.Profit*((double) joinableStations/2));
                posInfo.Profit += (int) (posInfo.Profit*((double) reserveStations/8));
                posInfo.Profit -= DistanceHelper.FindCost(robot.Position, pos);
                if (posInfo.Profit > bestProfit)
                {
                    bestProfit = posInfo.Profit;
                    bestPosition = pos;
                }
            }

            profit = bestProfit;
            return bestPosition;
        }
示例#43
0
 internal void PopulateFromConfig()
 {
     Console.WriteLine("Donwloading channel lineups");
     Clear();
     foreach(var lineup in config.lineups)
     {
         foreach(var station in lineup.GetDownloadedStations())
         {
             string stationId = station.stationID;
             if (!stationInfoByStationId_.ContainsKey(stationId))
                 stationInfoByStationId_[stationId] = new StationInfo(station);
             var stationInfo = stationInfoByStationId_[stationId];
             var newChannelNumbers = lineup.EffectiveStationChannelNumbers(stationId);
             stationInfo.AddChannelNumbers(newChannelNumbers);
             foreach(var channelNumber in newChannelNumbers)
             {
                 if (!stationIdsByChannelNumber_.ContainsKey(channelNumber))
                     stationIdsByChannelNumber_[channelNumber] = new HashSet<string>();
                 stationIdsByChannelNumber_[channelNumber].Add(stationId);
             }
             stationInfo.AddTuningConfigs(lineup.EffectivePhysicalChannelNumbers(stationId));
         }
     }
 }
示例#44
0
	protected void backgroundTick (object sender) {
		Gtk.Application.Invoke(delegate {

			try {

				string test = "";
				if (recognizer.TimeRecognized != DateTime.MinValue) {
					test = recognizer.TimeRecognized.ToShortTimeString() + ": " + recognizer.KeywordRecognized;
				}
				if (test != lastRecognized || 
					recognizer.Noise != lastNoise || 
					recognizer.BufferSize != lastBuffer ||
					status != lastStatus) {
					drawWiFi.QueueDraw();
				}

				activeConnection = network.WiFi;
				ipAddress = network.IpAddress;

				if (prevIpAddress != ipAddress) {
					Console.WriteLine("IP Address changed to " + ipAddress);
					drawWiFi.QueueDraw();
				}
				prevIpAddress = ipAddress;

				if (ipAddress != "") {
					if (DateTime.Now.Subtract(weatherview.Weather.LastSuccess).TotalHours > 4) {
						weatherview.UpdateWeather();
					}
				}

				if (intercomView.IsBusy) {
					ChangeTab(4);
					stationIndex = 0;
					station = null;
				}

				if (recognizer.Status == "Ready" && station != null && playingStation == null) {
					if (ipAddress.Length > 0) {
						status = "Radio " + station.CallLetters;
						Console.WriteLine("Start playing radio station " + station.CallLetters);
						radio.Start(station.Url);
						playingStation = station;
					}
				} else if (playingStation != null && playingStation != station) {
					Console.WriteLine("Start playing radio station " + playingStation.CallLetters);
					radio.Stop();
					playingStation = null;
					findArtwork.Artwork = null;
					artist = "";
					song = "";
					status = "";
					ctlDrawingMeta.QueueDraw();
				} else if (recognizer.Status == "Ready" && !isAlarmActive && station == null && playingStation == null && !intercomView.IsBusy) {
					Console.WriteLine("Recognizer is ready and idle - start listening");
					recognizer.StartListening();
				} else if (recognizer.Status != "Ready" && (station != null || isAlarmActive || intercomView.IsBusy)) {
					recognizer.StopListening();
				}

				if (DateTime.Now > DateTime.Parse("08/01/2015")) {

					analogclock.AutoUpdate = true;

					if (lastMinute != DateTime.Now.Minute) {
						lastMinute = DateTime.Now.Minute;

						List<AlarmItem> alarms = clockAlarms.FindOn(DateTime.Now);
						activeAlarm = "";
						foreach (AlarmItem item in alarms) {
							activeAlarm += item.Name + " ";
						}
						if (alarms.Count > 0) {
							isAlarmActive = true;
							recognizer.StopListening();
							volumeService.SetUserLedBrightness(100);
							LightsOn();
							foreach (AlarmItem item in alarms) {
								ProcessActions(item.OnActions);
							}
							volumeService.SetUserLedBrightness(0);
							isAlarmActive = false;
						}

						alarms = clockAlarms.FindOff(DateTime.Now);
						activeAlarm = "";
						foreach (AlarmItem item in alarms) {
							activeAlarm += item.Name + " ";
						}
						if (alarms.Count > 0) {
							isAlarmActive = true;
							recognizer.StopListening();
							volumeService.SetUserLedBrightness(100);
							foreach (AlarmItem item in alarms) {
								ProcessActions(item.OffActions);
							}
							volumeService.SetUserLedBrightness(0);
							isAlarmActive = false;
						}

						nextAlarm = "";
						DateTime nextTime = clockAlarms.NextActiveAlarm();
						if (nextTime != DateTime.MaxValue) {
							nextAlarm = nextTime.ToShortDateString() + " " + nextTime.ToShortTimeString() + ":";
							alarms = clockAlarms.FindOn(nextTime);
							foreach (AlarmItem item in alarms) {
								nextAlarm += " " + item.Name;
							}
						}
					}
				}


			} catch (Exception ex) {
				Console.WriteLine(ex.Source);
				Console.WriteLine(ex.StackTrace);
			}
		});
	}
示例#45
0
 public void SetCurrentStation(string id)
 {
     _currentStationInfo = GetStationInfo(id);
 }