Example #1
0
        private void main_Loaded(object sender, RoutedEventArgs e)
        {
            DataBase   db    = new DataBase();
            Controller ctrlr = new Controller();

            //get device ip and device id
            db.GetDeviceIp();

            //connect to controller
            ctrlr.ConnectController(db.device_ip);

            //skip when cant connect to controller
            if (ctrlr.h != IntPtr.Zero)
            {
                //get log from controller
                ctrlr.GetLog();

                //convert log to log array
                ctrlr.CreateArray();

                //insert log to database
                db.InsertDatabase(ctrlr.log);

                this.Close();
            }
            else
            {
                alert alrt = new alert();
                alrt.Show();
                this.Close();
            }
        }
Example #2
0
        public async Task <IActionResult> PutAlert(int id, alert alert)
        {
            if (id != alert.alertId)
            {
                return(BadRequest());
            }

            _context.Entry(alert).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!alertExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #3
0
        public async Task <ActionResult <alert> > PostAlert(alert alert)
        {
            _context.alert.Add(alert);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("Getalert", new { id = alert.alertId }, alert));
        }
Example #4
0
        public static void CheckTemperatures(alert toolow, alert optimal, alert toHigh)
        {
            var temperatures = 10;
            var random       = new Random();

            while (true)
            {
                var change = random.Next(-5, 5);
                temperatures += change;
                Console.WriteLine($"Temperature is at : {temperatures} C.");


                if (temperatures <= 0)
                {
                    toolow(change);
                }
                else if (temperatures > 0 && temperatures <= 10)
                {
                    optimal(change);
                }
                if (temperatures > 10)
                {
                    toHigh(change);
                }

                Thread.Sleep(500);
            }
        }
Example #5
0
 void Start()
 {
     foreach (Enemy enemy in enemies)
     {
         enemieAlert += enemy.Alert;
         allEnemies  += 1;
     }
 }
        public ActionResult DeleteConfirmed(int id)
        {
            alert alert = db.alerts.Find(id);

            db.alerts.Remove(alert);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #7
0
    void Start()
    {
        foreach (IReaction <GameObject> enemy in enemies)
        {
            enemieAlert += enemy.Chase;
            allEnemies  += 1;
        }

        foreach (IReaction <GameObject> enemy in enemies)
        {
            enemieIdle += enemy.Idle;
        }
    }
Example #8
0
        /// <summary>
        /// Seeds database with a user with two tasks to start out with
        /// </summary>
        /// <param name="userManager"></param>
        /// <param name="repository"></param>
        public static async Task SeedUsers(UserManager <reactCrashUser> userManager, ITaskRepository repository, IAlertRepository alertRepository)
        {
            reactCrashUser reactCrashUserSeed = new reactCrashUser {
                UserName = "******", Email = "*****@*****.**", EmailConfirmed = true
            };
            var isAdded = await SeedUser(userManager, reactCrashUserSeed);

            if (isAdded == IdentityResult.Success)
            {
                reactCrashUser reactCrashUserSeedReversed = new reactCrashUser {
                    UserName = "******", Email = "*****@*****.**", EmailConfirmed = true
                };
                isAdded = await SeedUser(userManager, reactCrashUserSeedReversed);

                try
                {
                    Collaboration collab = new Collaboration();
                    collab.user = reactCrashUserSeedReversed;
                    comment sampleComment = new comment {
                        date = DateTime.Now, text = "Test", user = reactCrashUserSeed
                    };
                    List <comment> sampleComments = new List <comment>();
                    sampleComments.Add(sampleComment);
                    List <TaskEntity> taskEntities = new List <TaskEntity>
                    {
                        new TaskEntity {
                            details = "foo", location = "bar", text = "foobar", task_date = DateTime.Now, reminder = false, user = reactCrashUserSeed, is_completed = true, date_completed = DateTime.Now, comments = sampleComments
                        },
                        new TaskEntity {
                            details = "bar", location = "foo", text = "barfoo", task_date = DateTime.Now.AddDays(3), user = reactCrashUserSeed, reminder = true, is_completed = false
                        }
                    };

                    collab.task = taskEntities[0];
                    taskEntities[0].collaboratorations = new List <Collaboration>()
                    {
                        collab
                    };
                    var result = await repository.AddTasks(taskEntities);

                    alert a = new alert {
                        date = DateTime.Now, message = "Created", user = userManager.Users.FirstOrDefault(u => u.UserName == "*****@*****.**")
                    };
                    var alertResult = await alertRepository.CreateAlert(a);
                }
                catch (Exception e)
                {
                    var message = e.Message;
                }
            }
        }
Example #9
0
 public ActionResult Edit([Bind(Include = "id,type,concern,flag,priority,entity,notes,reported")] alert alert)
 {
     if (ModelState.IsValid)
     {
         db.Entry(alert).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.entity   = new SelectList(db.entities, "id", "entityname", alert.entity);
     ViewBag.flag     = new SelectList(db.flags, "id", "flagname", alert.flag);
     ViewBag.priority = new SelectList(db.priorities, "id", "priorityname", alert.priority);
     ViewBag.type     = new SelectList(db.types, "id", "typename", alert.type);
     return(View(alert));
 }
Example #10
0
        public async Task <long> CreateAlert(alert a)
        {
            var user = await _context.Users.Where(u => u.Id == a.user.Id).FirstOrDefaultAsync();

            if (user != null)
            {
                a.user = user;
            }
            await _context.Alerts.AddAsync(a);

            await _context.SaveChangesAsync();

            return(a.id);
        }
Example #11
0
        public async Task <int> AddCollaboration(reactCrashUser user, TaskEntity task)
        {
            await _context.Collaborations.AddAsync(new Collaboration { task = task, user = user });

            alert a = new alert
            {
                date    = DateTime.Now,
                message = $"{user.UserName} has been added a collaborator to {task.text}",
                user    = task.user
            };
            await _context.Alerts.AddAsync(a);

            return(await _context.SaveChangesAsync());
        }
        // GET: alerts/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            alert alert = db.alerts.Find(id);

            if (alert == null)
            {
                return(HttpNotFound());
            }
            return(View(alert));
        }
Example #13
0
        public ActionResult UpdateAlert(int id)                      // get: admin page
        {                                                            //  shows a form to update a alert
            ViewBag.Group = "Admin";
            alert loadAlert = alertObj.getAlertByID(id);

            if (loadAlert == null)
            {
                return(View());
            }
            else
            {
                return(View(loadAlert));
            }
        }
Example #14
0
        public ActionResult DeleteAlert(int id)                 // get : admin page
        {                                                       // shows the record that has been requested to be deleted
            ViewBag.Group = "Admin";
            alert loadAlert = alertObj.getAlertByID(id);

            if (loadAlert == null)
            {
                return(View());
            }
            else
            {
                TempData["id"] = id;
                return(View(loadAlert));
            }
        }
Example #15
0
 public static DBAlert AlertToDbAlert(alert source)
 {
     if (source == null)
     {
         return(null);
     }
     return(new DBAlert()
     {
         Idalert = source.idalert,
         Content = source.content,
         Mode_idmode = source.mode_idmode,
         AlertDefinition_idalertType = source.alertDefinition_idalertType,
         Title = source.title,
         CreationDate = source.dateAlertCreation
     });
 }
        public alert LoginProc(UserLogin data)
        {
            var res = new alert();

            try
            {
                conn.ConnectionString = Config.ConStr;
                using (var connection = conn)
                {
                    connection.Open();
                    string sql = "exec SP_LoginProc " +
                                 "@Username='******'," +
                                 "@Password='******'," +
                                 "@Category='" + data.Platform + "'";
                    using (var command = new SqlCommand(sql, connection))
                    {
                        command.CommandTimeout = 0;
                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Type           type  = res.GetType();
                                PropertyInfo[] props = type.GetProperties();
                                foreach (var p in props)
                                {
                                    if (null != p && p.CanWrite)
                                    {
                                        if (p.Name != "" && p.Name != "Error")
                                        {
                                            p.SetValue(res, reader[p.Name].ToString(), null);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                res.message = "Function LoginProc, Error Syntax : " + ex.Message;
                res.status  = "error";
                res.title   = "Sorry we will fixing this bugs";
            }
            return(res);
        }
Example #17
0
        public ActionResult UpdateAlert(int id, alert updAlert)     // form values are sent to db to be updated
        {
            ViewBag.Group = "Admin";
            if (ModelState.IsValid)
            {
                try
                {
                    alertObj.commitUpdateAlert(id, updAlert.alertTitle, updAlert.alertLevel, updAlert.alertDescription, (DateTime)updAlert.alertTimeline);
                    return(RedirectToAction("Index"));
                }
                catch
                {
                    return(View());
                }
            }

            return(View());
        }
        public ActionResult Create([Bind(Include = "id,type,concern,flag,priority,entity,notes,reported,coin")] alert alert)
        {
            if (ModelState.IsValid)
            {
                db.alerts.Add(alert);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            alert x = new alert();


            ViewBag.coin     = new SelectList(db.coins, "id", "coinname", alert.coin);
            ViewBag.entity   = new SelectList(db.entities, "id", "entityname", alert.entity);
            ViewBag.flag     = new SelectList(db.flags, "id", "flagname", alert.flag);
            ViewBag.priority = new SelectList(db.priorities, "id", "priorityname", alert.priority);
            ViewBag.type     = new SelectList(db.types, "id", "typename", alert.type);
            return(View(alert));
        }
Example #19
0
        // GET: alerts/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            alert alert = db.alerts.Find(id);

            if (alert == null)
            {
                return(HttpNotFound());
            }
            ViewBag.entity   = new SelectList(db.entities, "id", "entityname", alert.entity);
            ViewBag.flag     = new SelectList(db.flags, "id", "flagname", alert.flag);
            ViewBag.priority = new SelectList(db.priorities, "id", "priorityname", alert.priority);
            ViewBag.type     = new SelectList(db.types, "id", "typename", alert.type);
            return(View(alert));
        }
Example #20
0
        public ActionResult AddAlert(alert newAlert)        // post : admin page, form values are insertrd in the database
        {                                                   // the alert status by default is set to false
            newAlert.alertStatus = false;
            ViewBag.Group        = "Admin";
            if (ModelState.IsValid)
            {
                try
                {
                    alertObj.commitInsertAlert(newAlert);
                    return(RedirectToAction("Index"));
                }
                catch
                {
                    return(View());
                }
            }

            return(View());
        }
        ///
        /// GET all Alerts [Alert_2020]
        ///
        public List <alert> get_AlertsDB()
        {
            List <alert>  alert_list = new List <alert>();
            SqlConnection con        = null;

            try
            {
                con = connect("DBConnectionString");

                String     query = "SELECT * FROM [Alert_2020]";
                SqlCommand cmd   = new SqlCommand(query, con);
                cmd.CommandTimeout = 480;                                              // enlarge T.O

                SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); // the connection will close as reading completes

                while (dr.Read())
                {
                    alert alert_to_add = new alert();

                    alert_to_add.AlertID     = Convert.ToInt32(dr["Alert_id"]);
                    alert_to_add.Type        = (string)dr["type"];
                    alert_to_add.Date        = Convert.ToDateTime(dr["date"]);
                    alert_to_add.Description = (string)dr["description"];
                    alert_to_add.Notes       = (string)dr["notes"];

                    alert_list.Add(alert_to_add);
                }

                return(alert_list);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
        public async Task <IActionResult> SignIn_proccess([Bind("Username,Password,Platform")] UserLogin data)
        {
            Config.ConStr = _configuration.GetConnectionString("Db");
            var r = new alert();

            try
            {
                if (ModelState.IsValid)
                {
                    r = f.LoginProc(data);
                    if (r.status == "success")
                    {
                        string UserId = f.GetIDUser(data);
                        if (UserId != "")
                        {
                            HttpContext.Session.SetString("_UserId", UserId);
                        }
                        else
                        {
                            HttpContext.Session.Clear();
                        }

                        return(await Task.Run(() => Json(new { isValid = true, message = r.message, title = r.title })));
                    }
                    else
                    {
                        return(await Task.Run(() => Json(new { isValid = false, message = r.message, title = r.title })));
                    }
                }
                else
                {
                    return(await Task.Run(() => Json(new { isValid = false, message = r.message, title = r.title })));
                }
            }
            catch (Exception ex)
            {
                return(await Task.Run(() => Json(new { isValid = false, message = "Error Syntax : " + ex.Message, title = "Error" })));
            }
        }
        public HttpResponseMessage Delete([FromBody] string alert_id) // delete from tbl ased on alert_id
        {
            int   numEffected = 0;
            alert al          = new alert();

            try
            {
                numEffected = al.delete_line(Convert.ToInt32(alert_id));

                if (numEffected > 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, numEffected));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found"));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
        [HttpPut] // edit batch DATE OR BeerType
        public HttpResponseMessage Put(object[] st)
        {
            int   numEffected = 0;
            alert al          = new alert();

            try
            {
                numEffected = al.Update(Convert.ToInt32(st[0]), (string)st[1]);

                if (numEffected > 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, numEffected));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found"));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Example #25
0
        public ServiceManager(
            NodeContainer container, CacheStorage storage, Logger logger, TimerManager timerManager,
            BoundServiceManager boundServiceManager,
            machoNet machoNet,
            objectCaching objectCaching,
            alert alert,
            authentication authentication,
            character character,
            userSvc userSvc,
            charmgr charmgr,
            config config,
            dogmaIM dogmaIM,
            invbroker invbroker,
            warRegistry warRegistry,
            station station,
            map map,
            account account,
            skillMgr skillMgr,
            contractMgr contractMgr,
            corpStationMgr corpStationMgr,
            bookmark bookmark,
            LSC LSC,
            onlineStatus onlineStatus,
            billMgr billMgr,
            facWarMgr facWarMgr,
            corporationSvc corporationSvc,
            clientStatsMgr clientStatsMgr,
            voiceMgr voiceMgr,
            standing2 standing2,
            tutorialSvc tutorialSvc,
            agentMgr agentMgr,
            corpRegistry corpRegistry,
            marketProxy marketProxy,
            stationSvc stationSvc,
            certificateMgr certificateMgr,
            jumpCloneSvc jumpCloneSvc,
            LPSvc LPSvc,
            lookupSvc lookupSvc,
            insuranceSvc insuranceSvc,
            slash slash,
            ship ship,
            corpmgr corpmgr,
            repairSvc repairSvc,
            reprocessingSvc reprocessingSvc,
            ramProxy ramProxy,
            factory factory)
        {
            this.Container           = container;
            this.CacheStorage        = storage;
            this.BoundServiceManager = boundServiceManager;
            this.TimerManager        = timerManager;
            this.Logger = logger;
            this.Log    = this.Logger.CreateLogChannel("ServiceManager");

            // store all the services
            this.machoNet        = machoNet;
            this.objectCaching   = objectCaching;
            this.alert           = alert;
            this.authentication  = authentication;
            this.character       = character;
            this.userSvc         = userSvc;
            this.charmgr         = charmgr;
            this.config          = config;
            this.dogmaIM         = dogmaIM;
            this.invbroker       = invbroker;
            this.warRegistry     = warRegistry;
            this.station         = station;
            this.map             = map;
            this.account         = account;
            this.skillMgr        = skillMgr;
            this.contractMgr     = contractMgr;
            this.corpStationMgr  = corpStationMgr;
            this.bookmark        = bookmark;
            this.LSC             = LSC;
            this.onlineStatus    = onlineStatus;
            this.billMgr         = billMgr;
            this.facWarMgr       = facWarMgr;
            this.corporationSvc  = corporationSvc;
            this.clientStatsMgr  = clientStatsMgr;
            this.voiceMgr        = voiceMgr;
            this.standing2       = standing2;
            this.tutorialSvc     = tutorialSvc;
            this.agentMgr        = agentMgr;
            this.corpRegistry    = corpRegistry;
            this.marketProxy     = marketProxy;
            this.stationSvc      = stationSvc;
            this.certificateMgr  = certificateMgr;
            this.jumpCloneSvc    = jumpCloneSvc;
            this.LPSvc           = LPSvc;
            this.lookupSvc       = lookupSvc;
            this.insuranceSvc    = insuranceSvc;
            this.slash           = slash;
            this.ship            = ship;
            this.corpmgr         = corpmgr;
            this.repairSvc       = repairSvc;
            this.reprocessingSvc = reprocessingSvc;
            this.ramProxy        = ramProxy;
            this.factory         = factory;
        }
        public List <alert> Get()
        {
            alert al = new alert();

            return(al.get_Alerts());
        }
        private static void ProcessMatch(Mobile from, bool highOnly, PlayerMobile pm1, PlayerMobile pm2)
        {
            try
            {               // sanity
                if (from == null || pm1 == null || pm2 == null)
                {
                    return;                     // wtf
                }
                NetState ns1 = pm1.NetState;
                NetState ns2 = pm2.NetState;

                if (ns1 == null || ns2 == null)
                {
                    return;                     // logged out / disconnected
                }
                if (ns1.Address == null || ns1.Mobile == null || ns2.Address == null || ns2.Mobile == null)
                {
                    return;                     // still logging in?
                }
                if (ns1.Account == null || ns2.Account == null)
                {
                    return;                     // error state .. ignore this account
                }
                if (ns1.Account as Server.Accounting.Account == null || ns2.Account as Server.Accounting.Account == null)
                {
                    return;                     // error state .. ignore this account
                }
                Server.Accounting.Account pm1Account = (Server.Accounting.Account)ns1.Account;
                int    pm1HWInfo = pm1Account.HardwareHash;                     // most recent hardware info
                string pm1Name   = string.Format("{0}/{1}", pm1Account.Username, ns1.Mobile.Name);

                Server.Accounting.Account pm2Account = (Server.Accounting.Account)ns2.Account;
                int    pm2HWInfo = pm2Account.HardwareHash;                     // most recent hardware info
                string pm2Name   = string.Format("{0}/{1}", pm2Account.Username, ns2.Mobile.Name);

                alert alarm = alert.LOW;
                if (pm1HWInfo == 0 && pm2HWInfo == 0 && ns1.Version == ns2.Version)
                {
                    // unknown hardware, same client version
                    if (LineOfSight(pm1, pm2))
                    {
                        alarm = alert.MEDIUM;
                    }
                }
                else if (pm1HWInfo == 0 || pm2HWInfo == 0 && ns1.Version == ns2.Version)
                {
                    // unknown hardware, same client version
                    if (LineOfSight(pm1, pm2))
                    {
                        alarm = alert.MEDIUM;
                    }
                }
                // we don't care about 'bad hardware' here as long as it matches!

                /*else if ((pm1HWInfo != null && pm2HWInfo != null) && (pm1HWInfo.CpuClockSpeed == 0 || pm1HWInfo.OSMajor == 0 || pm2HWInfo.CpuClockSpeed == 0 || pm2HWInfo.OSMajor == 0))
                 * {
                 *      // unknown hardware
                 *      if (LineOfSight(pm1, pm2))
                 *              alarm = alert.MEDIUM;
                 * }*/
                else if ((pm1HWInfo != 0 && pm2HWInfo != 0) && pm1HWInfo == pm2HWInfo /*Server.Commands.MultiClientCommand.IsSameHWInfo(pm1HWInfo, pm2HWInfo)*/)
                {
                    // same hardware
                    alarm = alert.MEDIUM;
                    if (LineOfSight(pm1, pm2) && ns1.Version == ns2.Version)
                    {
                        alarm = alert.HIGH;
                    }
                }
                else
                {
                    // different hardware
                    if (LineOfSight(pm1, pm2) && ns1.Version == ns2.Version)
                    {
                        alarm = alert.MEDIUM;
                    }
                }

                // caller wants to filter to HIGH alarms only
                if (highOnly == true && alarm != alert.HIGH)
                {
                    return;
                }

                from.SendMessage(String.Format("{0}, {1}, Alarm({2})", pm1Name, pm2Name, alarm.ToString()));
            }
            catch (Exception ex)
            {
                LogHelper.LogException(ex);
            }
        }
Example #28
0
        static void Main(string[] args)
        {
            WebRequest wr = WebRequest.Create("https://fogos.pt/new/fires");

            wr.Method = "GET";
            wr.Proxy  = GetProxy();
            WebResponse response = wr.GetResponse();
            var         sr       = new StreamReader(response.GetResponseStream());
            var         myStr    = sr.ReadToEnd();
            JObject     jo       = JObject.Parse(myStr);
            string      xml      = string.Empty;

            if (jo.Value <bool>("success"))
            {
                JArray data   = jo.Value <JArray>("data");
                alert  oAlert = new alert();
                oAlert.identifier = Guid.NewGuid().ToString();
                oAlert.msgType    = alertMsgType.Alert;
                oAlert.scope      = alertScope.Public;
                oAlert.sender     = "https://fogos.pt";
                oAlert.sent       = DateTime.UtcNow;
                oAlert.status     = alertStatus.Actual;
                List <alertInfo> infoList = new List <alertInfo>();
                foreach (var item in data)
                {
                    alertInfo info = new alertInfo();
                    info.category    = new[] { alertInfoCategory.Fire };
                    info.certainty   = alertInfoCertainty.Observed;
                    info.description = item.Value <string>("location");
                    info.language    = "pt-PT";
                    info.description = string.Format("Status:{0}-Homens:{1}-M.Aereos:{2}", item.Value <string>("status"), item.Value <string>("man"), item.Value <string>("aerial"));
                    if (item.Value <bool>("important"))
                    {
                        info.description += item.Value <string>("extra");
                    }
                    int raio = 0;
                    switch (item.Value <string>("statusCode"))
                    {
                    case "10":
                    case "9":
                        info.severity = alertInfoSeverity.Minor;
                        break;

                    case "8":
                    case "7":
                        info.severity = alertInfoSeverity.Moderate;
                        raio          = 1;
                        break;

                    case "5":
                        info.severity = alertInfoSeverity.Severe;
                        raio          = 3;
                        if (item.Value <bool>("important"))
                        {
                            info.severity = alertInfoSeverity.Extreme;
                            raio          = 5;
                        }
                        break;
                    }
                    info.@event  = "Ocorrencia";
                    info.urgency = alertInfoUrgency.Immediate;
                    info.expires = DateTime.Now.AddDays(1);
                    info.web     = "https://fogos.pt";
                    List <alertInfoArea> areaList = new List <alertInfoArea>();
                    alertInfoArea        area     = new alertInfoArea();
                    area.circle   = new[] { string.Format("{0},{1} {2}", item.Value <string>("lat"), item.Value <string>("lng"), raio) };
                    area.areaDesc = info.description;
                    areaList.Add(area);
                    info.area = areaList.ToArray();

                    infoList.Add(info);

                    //  break;
                }
                oAlert.info = infoList.ToArray();
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(alert));

                using (StringWriter xw = new Utf8StringWriter())
                {
                    xmlSerializer.Serialize(xw, oAlert);
                    xml = xw.ToString();
                }
            }

            Console.Write(xml);
            Console.ReadKey();
        }
Example #29
0
 public aps()
 {
     alert = new alert();
 }
        public static int nowInterval            = 0;  //目前已经来了几次
        public static void PutAirData()
        {
            OpentsdbClient client   = new OpentsdbClient(opentsdburl);
            string         phone    = "15064113079";
            string         password = "******";

            try
            {
                //获取空气数据的列表
                List <airData> airDataList  = GetSensorDataByApiBLL.getAirData(phone, password);
                int            numPutToTSDB = 0;//这一次for循环存的设备数
                for (int i = 0; i < airDataList.Count; i++)
                {
                    //以下if用于判断i设备的数据时间戳是否变化,没变化不再执行写入
                    if (lastTimeStamp[i] == null)
                    {
                        lastTimeStamp[i] = airDataList[i].data[0].timestamp;
                        numPutToTSDB++;
                    }
                    else
                    {
                        if (lastTimeStamp[i].Equals(airDataList[i].data[0].timestamp))
                        {
                            continue;
                        }
                        else
                        {
                            lastTimeStamp[i] = airDataList[i].data[0].timestamp;
                            numPutToTSDB++;
                        }
                    }
                    Dictionary <string, string> tagMap = new Dictionary <string, string>();
                    tagMap.Add("deviceId", airDataList[i].deviceId);
                    string datatime     = ConvertToTime(airDataList[i].data[0].timestamp).ToString("yyyyMMdd HH:mm:ss");
                    var    realDatatime = DateTimeUtil.parse(datatime, "yyyyMMdd HH:mm:ss");
                    //public bool putData(string metric, DateTime timestamp, string value, Dictionary<string, string> tagMap)
                    // AsyncHandleAlarmPolicies1(string deviceId, string air, string curValue, DateTime now)

                    client.putData("pm2d5", realDatatime, airDataList[i].data[0].data.pm2d5, tagMap);

                    client.putData("pm10", realDatatime, airDataList[i].data[0].data.pm10, tagMap);

                    client.putData("temperature", realDatatime, airDataList[i].data[0].data.temperature, tagMap);

                    client.putData("humidity", realDatatime, airDataList[i].data[0].data.humidity, tagMap);

                    client.putData("pm1d0", realDatatime, airDataList[i].data[0].data.pm1d0, tagMap);

                    client.putData("co2", realDatatime, airDataList[i].data[0].data.co2, tagMap);

                    double air = double.Parse(airDataList[i].data[0].data.tvoc);
                    air = air * 92.14 / 22400;//单位ppb转mg/m3的方法
                    client.putData("tvoc", realDatatime, air.ToString(), tagMap);

                    client.putData("ch2o", realDatatime, airDataList[i].data[0].data.ch2o, tagMap);

                    client.putData("rssi", realDatatime, airDataList[i].data[0].data.rssi, tagMap);

                    if (nowInterval >= intervalToAlert)
                    {
                        alert al = new alert();
                        al.AsyncHandleAlarmPolicies1(airDataList[i].deviceId, "pm2d5", airDataList[i].data[0].data.pm2d5, realDatatime);
                        al.AsyncHandleAlarmPolicies1(airDataList[i].deviceId, "pm10", airDataList[i].data[0].data.pm10, realDatatime);
                        al.AsyncHandleAlarmPolicies1(airDataList[i].deviceId, "temperature", airDataList[i].data[0].data.temperature, realDatatime);
                        al.AsyncHandleAlarmPolicies1(airDataList[i].deviceId, "humidity", airDataList[i].data[0].data.humidity, realDatatime);
                        al.AsyncHandleAlarmPolicies1(airDataList[i].deviceId, "pm1d0", airDataList[i].data[0].data.pm1d0, realDatatime);
                        al.AsyncHandleAlarmPolicies1(airDataList[i].deviceId, "co2", airDataList[i].data[0].data.co2, realDatatime);
                        al.AsyncHandleAlarmPolicies1(airDataList[i].deviceId, "tvoc", air.ToString(), realDatatime);
                        al.AsyncHandleAlarmPolicies1(airDataList[i].deviceId, "ch2o", airDataList[i].data[0].data.ch2o, realDatatime);
                        al.AsyncHandleAlarmPolicies1(airDataList[i].deviceId, "rssi", airDataList[i].data[0].data.rssi, realDatatime);
                    }
                }
                log.InfoFormat("{0}devices put to TSDB this time!", numPutToTSDB);
                nowInterval++;//执行完一次for循环就算存了一次数据
                if (nowInterval > intervalToAlert)
                {
                    nowInterval = 0;
                }
            }
            catch (Exception e)
            {
                log.Info("采集程序出异常啦!" + e.Message);

                // storeairdata2opentsdb.getdataservicestart();
            }
        }