Ejemplo n.º 1
0
        public List <DeviceModels> GetDevice(int UID)
        {
            List <DeviceModels> DeviceModelsList = new List <DeviceModels>();
            DeviceModels        deviceModels     = new DeviceModels();

            deviceModels.UID = UID;
            if (!string.IsNullOrEmpty(Convert.ToString(deviceModels.UID)))
            {
                DataTable dtSubjectList = new DataTable();
                dtSubjectList = deviceModels.Get();
                if (dtSubjectList.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtSubjectList.Rows)
                    {
                        DeviceModels deviceModelsTypes = new DeviceModels();
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["UID"])))
                        {
                            deviceModelsTypes.UID = Convert.ToInt32(dr["UID"]);
                        }

                        if (!string.IsNullOrEmpty(Convert.ToString(dr["DeviceId"])))
                        {
                            deviceModelsTypes.DeviceID = Convert.ToString(dr["DeviceId"]);
                        }

                        DeviceModelsList.Add(deviceModelsTypes);
                    }
                }
            }
            return(DeviceModelsList);
        }
        public async Task <ActionResult> ButtonZ(DeviceModels device)
        {
            db.Entry(device).State = EntityState.Modified;
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
        public static Image ImageModel(DeviceModels model)
        {
            switch (model)
            {
            case DeviceModels.iDAccess:
                return(Resources.ic_idaccess);

            case DeviceModels.iDFit:
                return(Resources.ic_idfit);

            case DeviceModels.iDLight:
                return(Resources.ic_idlight);

            case DeviceModels.iDAccessProx:
                return(Resources.ic_idaccessprox);

            case DeviceModels.iDBlock:
                return(Resources.ic_idblock);

            case DeviceModels.iDBox:
                return(Resources.ic_idbox);

            case DeviceModels.iDFlex:
                return(Resources.ic_idflex);
            }
            return(null);
        }
Ejemplo n.º 4
0
        //  POST api/<controller>
        public void Post([FromBody] DeviceModels content)
        {
            string mac = content.macadress;

            /*  string timing = DateTime.Today.ToShortTimeString();
             * ContentPageModels ccontentPage = new ContentPageModels();
             * ccontentPage.date_article = DateTime.Today.Date;
             * ccontentPage.content_text = "papi api+" + c;
             * ccontentPage.content_article = "King " + timing + "!!!now";
             * db.Entry(ccontentPage).State = EntityState.Added;
             * db.SaveChanges();*/
            ///////////////////////////////////////////////

            List <DeviceModels> device = db.Devices.ToList();

            foreach (var x in device)
            {
                if (x.macadress == mac)
                {
                    x.last_activ_time = DateTime.Now;
                    x.status          = content.status;
                    x.type_device     = content.type_device;
                    db.Entry(x).State = EntityState.Modified;
                }
            }
            db.SaveChanges();
        }
        public async Task <ActionResult> ButtonChange(int?id)
        {
            if (id == null)
            {
                return(HttpNotFound());
            }
            DeviceModels device = await db.Devices.FindAsync(id);

            if (device != null)
            {
                device.last_activ_time  = DateTime.Today.Date;
                device.last_activ_time += DateTime.Now.TimeOfDay;
                var prodevice = device;
                if (prodevice.status == "1")
                {
                    device.status = "0";
                }
                else
                {
                    device.status = "1";
                }
                db.Entry(device).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(HttpNotFound());
        }
        private void ExecuteDeleteDevice(DeviceModel device)
        {
            var result = DeviceModels.Remove(device);

            if (!result)
            {
                Application.Current.MainPage.DisplayAlert("Error", $"Unable to delete '{device.Name}'", "OK");
            }
        }
Ejemplo n.º 7
0
 public DeviceModelsTest()
 {
     this.storage            = new Mock <IStorageAdapterClient>();
     this.logger             = new Mock <ILogger>();
     this.customDeviceModels = new Mock <ICustomDeviceModels>();
     this.stockDeviceModels  = new Mock <IStockDeviceModels>();
     this.target             = new DeviceModels(
         this.customDeviceModels.Object,
         this.stockDeviceModels.Object,
         this.logger.Object);
 }
        // POST: odata/DeviceModels
        public async Task <IHttpActionResult> Post(DeviceModels deviceModels)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // TODO: Add create logic here.

            // return Created(deviceModels);
            return(StatusCode(HttpStatusCode.NotImplemented));
        }
Ejemplo n.º 9
0
        private async Task <DeviceModels> GetDevice()
        {
            var device = new DeviceModels();

            using (var client = new HttpClient())
            {
                client.BaseAddress = new System.Uri("http://localhost:4413/");
                var response = await client.GetAsync("api/App");

                device.macadress = response.IsSuccessStatusCode? await response.Content.ReadAsStringAsync():string.Empty;
            }
            return(device);
        }
Ejemplo n.º 10
0
        private void ExecuteAddTasmotaDevice()
        {
            if (!ValidDeviceCreationFields())
            {
                return;
            }

            DeviceModels.Add(new TasmotaDeviceModel
            {
                Name = DeviceName,
                IP   = DeviceIP
            });
            ClearDeviceCreationFields();
        }
Ejemplo n.º 11
0
 private void AddTestData()
 {
     DeviceModels.Add(new TasmotaDeviceModel
     {
         Name = "Tasmota Test Device",
         IP   = "192.168.178.72"
     });
     DeviceModels.Add(new HueBridgeDeviceModel
     {
         Name   = "Hue Bridge Test Device",
         ApiKey = "us2DTzQ985xyf-Jo0A6Asmn0FsQeuGEaVriIrFgS",
         IP     = "192.168.178.73"
     });
 }
        public async Task <ActionResult> ButtonZ(int?id)
        {
            if (id == null)
            {
                return(HttpNotFound());
            }
            DeviceModels device = await db.Devices.FindAsync(id);

            if (device != null)
            {
                return(View(device));
            }
            return(HttpNotFound());
        }
Ejemplo n.º 13
0
        public void ChangeS(DeviceModels device)
        {
            string changerevers = device.status;

            if (changerevers == "1")
            {
                changerevers = "0";
            }
            changerevers           = "1";
            device.status          = changerevers;
            device.last_activ_time = DateTime.Today.Date;;
            db.Entry(device).State = EntityState.Added;
            db.SaveChanges();
        }
Ejemplo n.º 14
0
 private void verifyAndAppendIoTHubAuthCertificatePath(DeviceModels deviceModels, string certificatePath)
 {
     if (deviceModels.IoTHubAuthenticationType.ToLower().Equals(DeviceModels.IOTHUB_AUTH_TYPE_CERTIFICATE))
     {
         if (string.IsNullOrEmpty(certificatePath))
         {
             Logger.showError(TAG, "The certificate path should be specified for the x509 certified device.");
             throw new ArgumentNullException(nameof(certificatePath));
         }
         else
         {
             deviceModels.CertificateFileName = appendCertificateFullPath(certificatePath, deviceModels.CertificateFileName);
         }
     }
 }
Ejemplo n.º 15
0
        public IHttpActionResult SaveResult(int UID, string DeviceID)
        {
            DeviceModels deviceModels = new DeviceModels();

            deviceModels.UID      = UID;
            deviceModels.DeviceID = DeviceID;
            try
            {
                string Status = string.Empty;
                Status = deviceModels.InsertDevice();
                return(ResponseMessage(Request.CreateResponse(Status)));
            }
            catch (Exception ex)
            {
                return(ResponseMessage(Request.CreateResponse("Failed")));
            }
        }
Ejemplo n.º 16
0
        public void GetDeviceProperties(string deviceId, GetDeviceMetadataDelegate callback)
        {
            //Validate the current sitename.
            if (!CommonUtil.ValidateCurrentSiteName())
            {
                return;
            }

            var backgroundService = new BackgroundServiceUtil();

            LogService.GetLog().Debug(string.Format("Get Properties for device {0}", deviceId));
            backgroundService.RunAsync(() =>
            {
                var device_url   = GET_ATTRIBUTES_URL + "/" + deviceId;
                var httpClient   = new HttpClient(device_url, HttpMethodEnum.GET, USERNAME, PASSWORD);
                var httpresponse = httpClient.Get("");

                var deviceMetadataModel = JsonUtil.FromJson <DeviceMetadataModel>(httpresponse);
                var deviceModels        = deviceMetadataModel.deviceModels;

                if (deviceModels != null)
                {
                    DeviceModels deviceModel = null;
                    foreach (var model in deviceModels)
                    {
                        if (model.attributes != null && model.attributes.Count > 0)
                        {
                            LogService.GetLog().Debug(string.Format
                                                          ("No of Properties for device {0} retrieved : {1}", deviceId, model.attributes.Count));
                            deviceModel = model;
                            break;
                        }
                    }

                    _attributes = new Dictionary <string, Attributes>();
                    if (deviceModel != null && deviceModel.attributes != null)
                    {
                        foreach (var attribute in deviceModel.attributes)
                        {
                            _attributes.Add(attribute.description, attribute);
                        }
                    }
                    callback.Invoke(_attributes);
                }
            });
        }
Ejemplo n.º 17
0
        // POST api/<controller>
        public async Task <int> Post([FromBody] DeviceModels content)
        {
            int    vkl = 333;
            string mac = content.macadress;

            List <DeviceModels> device = await db.Devices.ToListAsync();

            foreach (var x in device)
            {
                if (x.macadress == mac)
                {
                    x.last_activ_time = DateTime.Now;
                    vkl               = Convert.ToInt32(x.status);
                    x.type_device     = "OnOff";
                    db.Entry(x).State = EntityState.Modified;
                }
            }
            await db.SaveChangesAsync();

            return(vkl);
        }
Ejemplo n.º 18
0
        private void ExecuteAddHueBridgeDevice()
        {
            if (!ValidDeviceCreationFields())
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(DeviceApiKey))
            {
                DisplayMissingValuesError("DeviceApiKey");
                return;
            }

            DeviceModels.Add(new HueBridgeDeviceModel
            {
                Name   = DeviceName,
                ApiKey = DeviceApiKey,
                IP     = DeviceIP
            });
            ClearDeviceCreationFields();
        }
Ejemplo n.º 19
0
        public async Task <IHttpActionResult> GetDeviceById(string id)
        {
            string logAPI = "[Get] " + Request.RequestUri.ToString();

            try
            {
                DeviceModels deviceModel = new DeviceModels();
                return(Ok(await deviceModel.GetIoTDeviceByDeviceId(id)));
            }
            catch (Exception ex)
            {
                switch (ex.Message)
                {
                case "404":
                    return(NotFound());
                }

                StringBuilder logMessage = LogUtility.BuildExceptionMessage(ex);
                Startup._sfAppLogger.Error(logAPI + logMessage);

                return(InternalServerError(ex));
            }
        }
Ejemplo n.º 20
0
        public async Task <IHttpActionResult> GetDeviceById(int id)
        {
            string logAPI = "[Get] " + Request.RequestUri.ToString();

            try
            {
                DeviceModels deviceModel = new DeviceModels();
                return(Ok(await deviceModel.GetIoTDeviceByDeviceId(id)));
            }
            catch (Exception ex)
            {
                switch (ex.Message)
                {
                case "404":
                    return(NotFound());
                }

                StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex);
                Global._appLogger.Error(logAPI + logMessage);

                return(Content(HttpStatusCode.InternalServerError, ex));
            }
        }
Ejemplo n.º 21
0
        private DeviceClient getAzureIoTDeviceSDKClient(DeviceModels deviceModels)
        {
            if (deviceModels.IoTHubAuthenticationType.ToLower().Equals(DeviceModels.IOTHUB_AUTH_TYPE_KEY))
            {
                string connectionString = combineIoTHubDeviceConnectionString(deviceModels.IoTHubName, deviceModels.DeviceId, deviceModels.DeviceKey);

                Logger.showDebug(TAG, "IoTHubName={0}, DeviceId={1}, DeviceKey={2}".FormatInvariant(deviceModels.IoTHubName, deviceModels.DeviceId, deviceModels.DeviceKey));
                Logger.showDebug(TAG, "IoTHubProtocol={0}".FormatInvariant(deviceModels.IoTHubProtocol));

                DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString,
                                                                                    getTransportType(deviceModels.IoTHubProtocol.ToLower()));

                return(deviceClient);
            }
            else if (deviceModels.IoTHubAuthenticationType.ToLower().Equals(DeviceModels.IOTHUB_AUTH_TYPE_CERTIFICATE))
            {
                // x509 certificate
                var x509Certificate = new X509Certificate2(deviceModels.CertificateFileName, deviceModels.CertificatePassword);

                Logger.showDebug(TAG, "CertificateFileName={0}, CertificatePassword={1}".FormatInvariant(deviceModels.CertificateFileName, deviceModels.CertificatePassword));
                Logger.showDebug(TAG, "IoTHubProtocol={0}".FormatInvariant(deviceModels.IoTHubProtocol));

                var          authMethod   = new DeviceAuthenticationWithX509Certificate(deviceModels.DeviceId, x509Certificate);
                DeviceClient deviceClient = DeviceClient.Create(
                    deviceModels.IoTHubName,
                    authMethod,
                    getTransportType(deviceModels.IoTHubProtocol.ToLower()));

                return(deviceClient);
            }
            else
            {
                Logger.showError(TAG, "Unsupported IoTHub Authentication Type {0}".FormatInvariant(deviceModels.IoTHubAuthenticationType));
                throw new InvalidOperationException("Unsupported IoTHub Authentication Type {0}".FormatInvariant(deviceModels.IoTHubAuthenticationType));
            }
        }
Ejemplo n.º 22
0
        private async Task initialzation(string certificatePath)
        {
            _restfulAPIHelper = new RestfulAPIHelper(_hwProductKey.email, _hwProductKey.password);

            // Get the Device Model
            string resp = await _restfulAPIHelper.callDeviceAPIService("GET", _hwProductKey.email, null);

            _deviceModels = DeviceModels.CreateDeviceModels(resp);

            verifyAndAppendIoTHubAuthCertificatePath(_deviceModels, _certificatePath);

            // Get the Message Schema of Device
            resp = await _restfulAPIHelper.getDeviceMessageSchemaAPIService(_hwProductKey.email);

            _messageCatalogSchemaList = MessageCatalogSchema.CreateMessageCatalogSchemaList(resp);

            _deviceClient = getAzureIoTDeviceSDKClient(_deviceModels);

            // Get SfTwin Properties Helper
            _sfTwinPropertiesHelper = new SfTwinPropertiesHelper(_deviceClient);

            // Sync System Config of Twin
            await _sfTwinPropertiesHelper.SyncAndUpdateSfTwinPropertiesFromTwin();
        }
Ejemplo n.º 23
0
        // GET : DeviceModel/Add/
        public ActionResult Add(string dealerId)
        {
            // TMSEntities db = new TMSEntities();
            //List<ProtocolServerViewModel> protocol = new List<ProtocolServerViewModel>();
            DataTable dt = Data.GetData(DataBase.Api, CommandType.StoredProcedure, "Report_ProtocolServers");
            List <ProtocolServerViewModel> Server = new List <ProtocolServerViewModel>();

            if (dt != null || dt.Rows.Count > 0)
            {
                Server = dt.AsEnumerable().Select(m => new ProtocolServerViewModel()
                {
                    ProtocolServer = Convert.ToString(m["ProtocolServer"]),
                }).ToList();
            }
            DeviceModelViewModel dealerVM = new DeviceModelViewModel();

            if (Session["UserData"] is Admin)
            {
                var deviceTypes           = Server.ToList();
                var deviceTypesSelectList =
                    new SelectList(
                        deviceTypes.Select(
                            dist => new SelectListItem()
                {
                    Text = dist.ProtocolServer, Value = dist.ProtocolServer
                }), "Value",
                        "Text");

                ViewData["DeviceTypeList"] = deviceTypesSelectList;
                var currentUser            = Session["UserData"] as Admin;
                var distributors           = GetDistributors(currentUser.UserId.ToString());
                var distributorsSelectList =
                    new SelectList(
                        distributors.Select(
                            dist => new SelectListItem()
                {
                    Text = dist.Username, Value = dist.UserId.ToString()
                }), "Value",
                        "Text");

                ViewData["DistributorList"] = distributorsSelectList;
                List <Dealer> dealers = new List <Dealer>();
                SelectList    dealersSelectList;
                if (distributors.FirstOrDefault() != null)
                {
                    dealers           = GetDealers(distributors.First().UserId.ToString());
                    dealersSelectList =
                        new SelectList(
                            dealers.Select(
                                deal => new SelectListItem()
                    {
                        Text = deal.Username, Value = deal.UserId.ToString()
                    }), "Value",
                            "Text");
                }
                else
                {
                    dealersSelectList = new SelectList(new List <SelectListItem>()
                    {
                        new SelectListItem()
                        {
                            Text = "Select", Value = "0"
                        }
                    }, "Value", "Text");
                }

                ViewData["DealerList"] = dealersSelectList;
                SelectList customersSelectList;

                if (dealers.FirstOrDefault() != null)
                {
                    //  var currentUser = Session["UserData"] as Admin;
                    var customers = GetCustomers(dealers.First().UserId.ToString());
                    customersSelectList =
                        new SelectList(
                            customers.Select(
                                cust => new SelectListItem()
                    {
                        Text = cust.Username, Value = cust.UserId.ToString()
                    }), "Value",
                            "Text");
                }
                else
                {
                    customersSelectList = new SelectList(new List <SelectListItem>()
                    {
                        new SelectListItem()
                        {
                            Text = "Select", Value = "0"
                        }
                    }, "Value", "Text");
                }

                ViewData["CustomerList"] = customersSelectList;

                if (string.IsNullOrWhiteSpace(dealerId))
                {
                    dealerVM.DeviceId = Guid.Empty;
                }
                else
                {
                    var          dealerGuid = Guid.Parse(dealerId);
                    DeviceModels customer   = devicemodelService.GetDevice(dealerGuid);
                    dealerVM          = Mapper.Map <DeviceModels, DeviceModelViewModel>(customer);
                    dealerVM.ToExpiry = 0;
                }
            }

            return(PartialView("_Add", dealerVM));
        }
Ejemplo n.º 24
0
 public static bool IsCatraca(DeviceModels model)
 {
     return(model == DeviceModels.iDBlock || model == DeviceModels.iDBlock_Balcao || model == DeviceModels.iDBlock_Braco || model == DeviceModels.iDBlock_Pne);
 }
Ejemplo n.º 25
0
 public static bool IsFlex(DeviceModels model)
 {
     return(model == DeviceModels.iDFlex || model == DeviceModels.iDAccess_Nano || model == DeviceModels.iDAccess_Pro);
 }
Ejemplo n.º 26
0
        public async Task <HttpResponseMessage> UploadPhotoFile(string id)
        {
            try
            {
                DeviceUtility deviceHelper = new DeviceUtility();

                // Check if the request contains multipart/form-data.
                if (!Request.Content.IsMimeMultipartContent())
                {
                    return(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
                }

                DeviceModels        deviceModel = new DeviceModels();
                DeviceModels.Detail iotDevice   = await deviceModel.GetIoTDeviceByDeviceId(id);

                FileUtility fileHelper = new FileUtility();
                string      root       = Path.GetTempPath();
                var         provider   = new MultipartFormDataStreamProvider(root);

                // Read the form data.
                string fileAbsoluteUri = "";
                await Request.Content.ReadAsMultipartAsync(provider);

                long logStartTimestamp = 0;

                //FormData
                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        if (key.ToLower().ToString() == "startts")
                        {
                            logStartTimestamp = long.Parse(val);
                        }
                    }
                }

                //FileData
                foreach (MultipartFileData fileData in provider.FileData)
                {
                    string formColumnName   = fileHelper.LowerAndFilterString(fileData.Headers.ContentDisposition.Name);
                    string fileExtenionName = fileHelper.LowerAndFilterString(fileData.Headers.ContentDisposition.FileName.Split('.')[1]);
                    if (formColumnName.ToLower().Equals("filename"))
                    {
                        DBHelper._IoTDevice dbhelp      = new DBHelper._IoTDevice();
                        IoTDevice           dbIoTDevice = dbhelp.GetByid(id);
                        DateTime            logStartDT  = deviceHelper.GetSpecifyTimeZoneDateTimeByTimeStamp(logStartTimestamp, dbIoTDevice.Factory.TimeZone);

                        string uploadFilePath = logStartDT.ToString("yyyy/MM/dd") + "/" + dbIoTDevice.IoTHubDeviceID + "/" + logStartTimestamp + "." + fileExtenionName;
                        fileAbsoluteUri = fileHelper.SaveFiletoStorage(fileData.LocalFileName, uploadFilePath, "log-device");
                    }
                }

                if (fileAbsoluteUri.Equals(""))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "File is empty"));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (System.Exception ex)
            {
                string logAPI = "[Post] " + Request.RequestUri.ToString();

                switch (ex.Message)
                {
                case "404":
                    return(Request.CreateResponse(HttpStatusCode.NotFound));
                }

                StringBuilder logMessage = LogUtility.BuildExceptionMessage(ex);
                Startup._sfAppLogger.Error(logAPI + logMessage);

                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Ejemplo n.º 27
0
 public void CreateDevice(DeviceModels device)
 {
     devicemodelRepository.Add(device);
 }
Ejemplo n.º 28
0
 public void UpdateDevice(DeviceModels device)
 {
     devicemodelRepository.Update(device);
 }
Ejemplo n.º 29
0
 public void DeleteDevice(DeviceModels device)
 {
     devicemodelRepository.Delete(device);
 }