Esempio n. 1
0
 public DeviceCreated(Guid aggregateId, string name, string primaryIPAddress, DeviceStatus deviceStatus, Guid customerId)
 {
     AggregateId = aggregateId;
     Name = name;
     PrimaryIPAddress = primaryIPAddress;
     DeviceStatus = deviceStatus;
     CustomerId = customerId;
 }
 /// <summary>
 /// Actualiza el estado de un dispositivo
 /// </summary>
 /// <param name="deviceId">id dispositivo (imei/android id)</param>
 /// <param name="newStatus">estado nuevo</param>
 /// <returns>observable del restulado de la operación</returns>
 public static IObservable<Device> UpdateDeviceStatus(string deviceId, DeviceStatus newStatus)
 {
     return RestEndpointFactory.Create<IDevicesEndpoint>(SessionManager
         .Instance.CurrentLoggedUser)
         .UpdateDevice(deviceId, new Device { Status = newStatus })
         .ToObservable()
         .SubscribeOn(TaskPoolScheduler.Default)
         .InterpretingErrors();
 }
Esempio n. 3
0
        public void Add(DeviceStatus status, DateTime dateTime, bool edge)
        {
            XDocument file = CheckOrOpenDataFile();
            XElement xmlData = CreateRow(status, dateTime, edge);
            file.Root.Add(xmlData);

            string fullFilePath = GetFullFilename(dateTime);
            file.Save(fullFilePath);
        }
        //[Test()]
        public void AlertDataStore()
        {
            DeviceStatusJSON status = new DeviceStatusJSON();
            status.bkupURL = "http://cozumotesttls.cloudapp.net:80/api/DeviceBackup";
            status.callHomeTimeoutData = null;
            status.callHomeTimeoutMode = "0";
            status.capture = "1";
            status.captureMode = "1";
            status.cmdChkInt = "1";
            status.cmdURL = "http://cozumotesttls.cloudapp.net:80/api/iCmd";
            string[] err = new string[1];
            err[0] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")+ "///900///bypassmode";
            status.Ssid = "43B81B4F768D0549AB4F178022DEB384";
            status.wpaPSK = "wifipassword";
            status.errorLog = err;
            status.dynCodeFormat = err;
            status.intSerial = TestGlobals.validSerial;
            status.reportURL = "http://cozumotesttls.cloudapp.net:80/api/DeviceStatus";
            status.requestTimeoutValue = "8000";
            status.revId = "52987";
            status.scanURL = "http://cozumotesttls.cloudapp.net:80/api/DeviceScan";
            status.seqNum = "87";
            status.startURL = "http://cozumotesttls.cloudapp.net:80/api/DeviceSetting";

            DeviceStatus operation = new DeviceStatus(TestGlobals.testServer, status);
            Test statusTest = new Test(operation);
            statusTest.setTestName("AlertDataStore");
            statusTest.setExpectedResult ("201");

            results.WriteLine (DateTime.Now);
            results.WriteLine ("current test: " + statusTest.ToString () + " " + statusTest.getTestName ());

            AsyncContext.Run(async () => await new HTTPSCalls().runTest(statusTest, HTTPOperation.POST));
            string statusCode = HTTPSCalls.result.Key.Property("StatusCode").Value.ToString();

            results.WriteLine("Json posted:");
            results.WriteLine(statusTest.getOperation().getJson().ToString());
            results.WriteLine("Server returned:");
            results.WriteLine(HTTPSCalls.result.Key.ToString());
            results.WriteLine(HTTPSCalls.result.Value.ToString());
            results.WriteLine ("Server: " + TestGlobals.testServer);
            results.WriteLine ("Expected result: " + statusTest.getActualResult());
            results.WriteLine ("Actual result: " + statusCode);
            results.WriteLine ("Test result: " + statusTest.result ());
            results.WriteLine ();

            Assert.AreEqual("201", statusCode);
        }
        public void AsyncHTTPSDeviceStatus()
        {
            FileStream stream;
            stream = File.Create(outputFileHTTPSAsync);
            results = new StreamWriter(stream);

            DeviceStatus operation = new DeviceStatus(TestGlobals.testServer, status);
            Test statusTest = new Test(operation);
            statusTest.setTestName("ValidSerial");
            statusTest.setExpectedResult ("201");
            statusTest.setType ("performance");

            List<Test> tests = new List<Test>();
            tests.Add(statusTest);

            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();

            // Construct started tasks
            Task<double>[] tasks = new Task<double>[TestGlobals.maxReps];
            for (int i = 0; i < TestGlobals.maxReps; i++)
            {
                System.Threading.Thread.Sleep(TestGlobals.delay);
                tasks[i] = new HTTPSCalls().runTest(statusTest, HTTPOperation.POST);
                Console.WriteLine("Test starting:" + i.ToString());
            }
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("All tests initialized, waiting on them to run as async");
            Console.WriteLine("------------------------------------------------------");
            Task.WaitAll(tasks);

            foreach (Task<double> nextResult in tasks)
            {
                results.WriteLine("Test Time," + nextResult.Result);
            }

            results.Close();
        }
Esempio n. 6
0
 public void NotOperationalWithObject()
 {
     this.OperationalStatus = this.OperationalStatus.NotOperational();
 }
Esempio n. 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="IDEController"/> class.
        /// </summary>
        /// <param name="ioBase">The io base.</param>
        /// <param name="filenames">The filenames.</param>
        public IDEController(ushort ioBase, string[] filenames)
        {
            this.ioBase = ioBase;

            numDrives = (byte)filenames.Length;
            driveFiles = new FileStream[numDrives];
            bufferData = new byte[512];
            bufferIndex = 0;
            status = DeviceStatus.Ready;

            for (int i = 0; i < numDrives; i++) {
                driveFiles[i] = new FileStream(filenames[i], FileMode.Open);
            }

            Initialize();
        }
Esempio n. 8
0
        public Device(Device parent, string name, DeviceStatus deviceStatus)
        {
            this.parent = parent;
            this.name = name;
			this.deviceStatus = deviceStatus;           
        }
Esempio n. 9
0
        public DeviceStatus ParsePosition()
        {
            if (!(new[] { "RGP", "RGL" }.Any(d => _command.StartsWith(d))))
            {
                return(null);
            }



            #region command dependent lengths attributes (RGP=47|48/RGL=45|46)
            var eventoLength = (_command.Length == 48 || _command.Length == 46 ? 3 : 2);
            var evento       = Convert.ToByte(_command.Substring(43, eventoLength));
            var hdop         = _command.Length < 47 ? 0 : Convert.ToByte(_command.Substring(43 + eventoLength, 2));
            #endregion command dependent lengths attributes

            var entradas = Convert.ToByte(_command.Substring(41, 2), 16);
            //var tipoDePos = Convert.ToSingle(_command.Substring(38, 1));
            //var edad = Convert.ToByte(_command.Substring(39, 2), 16);

            //if (edad > 300)
            //    return null;

            var time = DateTimeUtils.SafeParseFormat(_command.Substring(3, 12), "ddMMyyHHmmss");
            var lat  = Convert.ToSingle(_command.Substring(15, 8)) * (float)0.00001;
            var lon  = Convert.ToSingle(_command.Substring(23, 9)) * (float)0.00001;
            var vel  = Convert.ToSingle(_command.Substring(32, 3));
            var dir  = Convert.ToSingle(_command.Substring(35, 3)); // (0 ..359), Norte = 0, Este = 90, Sur = 180, Oeste = 270

            /*
             * Estado del posicionamiento del GPS  de la ultima posición valida
             *
             * 0 = Posicionando con solo 1 satélite.
             *
             * 1 = Posicionando con 2 satélites
             *
             * 2 = Posicionando con 3 satélites (2D).
             *
             * 3 = Posicionando con 4 o más satélites (3D).
             *
             * 4 = Posición en 2D calculada por aproximación de cuadrados mínimos.
             *
             * 5 = Posición en 3D calculada por aproximación de cuadrados mínimos.
             *
             * 6 = Posición calculada sin satélites, por velocidad, sentido y tiempo.
             *
             * 8 = Antena en corto circuito
             *
             * 9 = Antena no conectada
             *
             */


            /*
             *
             * bit 7 Ignición.
             *
             * bit 6 Fuente de poder principal.
             *
             * bit 5 Entrada digital 5
             *
             * bit 4 Entrada digital 4
             *
             * bit 3 Entrada digital 3.
             *
             * bit 2 Entrada digital 2.
             *
             * bit 1 Entrada digital 1.
             *
             * bit 0 Entrada digital 0.
             */

            var devId = (Int32?)null;

            if (_node != null)
            {
                devId = _node.Id;
            }


            GPSPoint gpoint = null;
            try
            {
                gpoint = new GPSPoint(time, lat, lon, vel, GPSPoint.SourceProviders.Unespecified, 0)
                {
                    Course         = new Course(dir),
                    HDOP           = hdop,
                    IgnitionStatus = BitHelper.AreBitsSet(entradas, 7) ? IgnitionStatus.On : IgnitionStatus.Off
                };
                if (devId != null)
                {
                    gpoint.DeviceId = devId.Value;
                }
            }
            catch (ArgumentOutOfRangeException e)
            {
                STrace.Exception(typeof(VirlocDeviceCommand).FullName, e, IdNum ?? 0, String.Format("Posición inválida {0}", getCommand()));
                gpoint = null;
            }

            var result = new DeviceStatus(devId, gpoint, evento, entradas);
            return(result);
        }
            public bool ApplyChanges([NotNull] DeviceStatus newStatus)
            {
                if (LastStatus == newStatus)
                {
                    return false;
                }

                LastStatus = newStatus;
                return true;
            }
Esempio n. 11
0
 private void OnEquipStatusChanged(object sender, PathIdEquipStatusChangedEventArgs args)
 {
     if (DeviceStatusNotifyHandler != null)
     {
         T_PathIdentifyEquip equip = CurrentEquipList.Where(it => it.Id == args.StatusInfo.equipId).FirstOrDefault();
         if (equip == null)
         {
             throw new Exception("汉王驱动在回调设备状态时发生错误:未能找到目标设备,EQUIPID=" + args.StatusInfo.equipId.ToString());
         }
         DeviceStatus statusInfo = new DeviceStatus();
         statusInfo.Device = equip;
         statusInfo.GatherTime = args.StatusInfo.currentDateTime;
         statusInfo.Status = args.StatusInfo.status;
         statusInfo.StatusDesc = args.StatusInfo.statusDes;
         DeviceStatusNotifyHandler.Invoke(this, statusInfo);
     }
 }
Esempio n. 12
0
        private void AddExpectedDevice(int id)
        {
            // Add to list if not present, get from list
            DeviceStatus device;
            if (!devices.ContainsKey(id))
            {
                devices[id] = new DeviceStatus(id);
            }
            device = devices[id];

            // Set expected flag
            if (device.Expected)
            {
                MessageBox.Show(this, "Device ID " + id + " already expected!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                device.Expected = true;
            }

            UpdateDevices();
        }
Esempio n. 13
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="device"></param>
        public NetworkDevice(IDevice device)
        {
            _NetworkId = device.Network.NetworkId;
            _NetworkDescription = device.Network.Description;
            _NodeId = device.NodeId;
            _Location = device.LocationName;
            _PollingInterval = device.PollingInterval;
            _Status = device.Status;

            // Создаём оъектный словаря устройства
            _ObjectDictionary = new List<DataObjectInfo>();

            foreach(ObjectInfo info in device.Profile.ObjectInfoList)
            {
                _ObjectDictionary.Add(new DataObjectInfo(info));
            }
        }
Esempio n. 14
0
        public bool Init()
        {
            DeviceStatus devStatus = CGAPI.DeviceInitialSDK(cameraPreviewHandle, false);

            return(devStatus == DeviceStatus.STATUS_OK);
        }
Esempio n. 15
0
        private void AddDevice(object sender, OmApiNet.OmDeviceEventArgs e)
        {
            int id = e.Device.DeviceId;
            DeviceStatus device;

            if (!devices.ContainsKey(id))
            {
                devices[id] = new DeviceStatus(id);
            }
            device = devices[id];

            if (device.Connected)
            {
                Console.WriteLine("WARNING: Device ID " + id + " already connected!");
                return;
            }

            device.Connected = true;

            UpdateDevices();
        }
        private void SetDeviceStatus(DeviceStatus status)
        {
            if (DeviceStatus != status)
            {
                DeviceStatus = status;

                if (DeviceStatus != DeviceStatus.Connected)
                {
                    BlynclightController.ResetAll();
                }

                MessageRouter.Publish(new BlyncLightDeviceStatusMessage()
                {
                    Status = status
                });
            }
        }
Esempio n. 17
0
 public void Insert(DeviceStatus status)
 {
     _table.Execute(TableOperation.Insert(new DeviceStatusEntity(status)));
 }
Esempio n. 18
0
        /// <summary>
        /// Конструктор
        /// </summary>
        internal DeviceBase(IProfile profile)
        {
            _Profile = profile;
            _LocationName = String.Empty;
            _NodeId = 1;
            _PollingInterval = 1;
            _Status = DeviceStatus.Stopped;
            // Создаём устройство на основе профиля
            _DeviceType = profile.DeviceType;
            // Создаём словарь объектов устройства
            _ObjectDictionary = new ObjectCollection(this);
            foreach (ObjectInfo info in profile.ObjectInfoList)
            {
                _ObjectDictionary.Add(new DataObject(info));
            }
            // Устанавливаем версии ПО и аппаратуры
            ProductVersion version = new ProductVersion();
            version.Version = profile.SoftwareVersion;
            SetObject(0x2001, version);
            version.Version = profile.HardwareVersion;
            SetObject(0x2002, version);

            // Пересчитвываем CRC16
            VisitingCard vc = VisitingCard;
            ushort crc = vc.GetCRC16();
            vc.CRC16 = crc;
        }
Esempio n. 19
0
        /// <summary>
        /// Identifies the drive.
        /// </summary>
        protected void IdentifyDrive()
        {
            byte drive = (byte)(((deviceHead & 0x10) != 0x10) ? 0 : 1);
            byte d = (byte)('0' + drive + 1);
            BinaryFormat data = new BinaryFormat(bufferData);

            data.Fill(0, 0, 512);

            // fixed drive and over 5Mb/sec
            data.SetUShort(0x00, 0x140);
            // Serial Number
            data.Fill(0x0A * 2, d, 20);
            data.SetByte(0x0A * 2, d);
            // Firmware version
            data.Fill(0x17 * 2, d, 8);
            data.SetChar(0x17 * 2 + 0, '1');
            data.SetChar(0x17 * 2 + 1, '.');
            data.SetChar(0x17 * 2 + 2, '0');
            // Model Number
            data.Fill(0x1B * 2, d, 40);
            data.SetChar(0x17 * 2 + 0, 'D');
            data.SetChar(0x17 * 2 + 1, 'R');
            data.SetChar(0x17 * 2 + 2, 'I');
            data.SetChar(0x17 * 2 + 3, 'V');
            data.SetChar(0x17 * 2 + 4, 'E');
            data.SetByte(0x1B * 2 + 5, d);
            // lba28
            data.SetUInt(0x3C * 2, (uint)(driveFiles[drive].Length / 512));

            commandStatus = (byte)((commandStatus | 0x08) & ~0x80); // Set DRQ (bit 3), clear BUSY (bit 7)

            status = DeviceStatus.IdentifyDrive;
        }
Esempio n. 20
0
        static void Main(string[] argv)
        {
            // the device
            Device device = null;

            // loop through accepting commands
            string line;

            while (true)
            {
                // read next line
                Console.Write("> ");
                line = Console.ReadLine().Trim();

                // parse the line
                string[] components = line.Split(' ');
                string[] args       = components.Length == 0 ? new string[0] : new string[components.Length - 1];
                string   cmd        = components.Length == 0 ? null : components[0];

                if (args.Length > 0)
                {
                    Array.Copy(components, 1, args, 0, args.Length);
                }

                // ignore empty lines
                if (cmd == null)
                {
                    continue;
                }

                // process command
                if (cmd.Equals("connect", StringComparison.CurrentCultureIgnoreCase))
                {
                    if (args.Length == 0)
                    {
                        Console.WriteLine("connect <port>");
                        continue;
                    }

                    try {
                        device = new Device(args[0]);
                        device.Connect();
                        Console.WriteLine("Connected successfully");
                    } catch (Exception ex) {
                        Console.Error.WriteLine(ex.Message);
                    }
                }
                else if (cmd.Equals("a", StringComparison.CurrentCultureIgnoreCase) || cmd.Equals("b", StringComparison.CurrentCultureIgnoreCase) ||
                         cmd.Equals("cs", StringComparison.CurrentCultureIgnoreCase))
                {
                    // check device is connected
                    if (device == null)
                    {
                        Console.WriteLine("Not connected to device");
                        continue;
                    }

                    // determine output
                    Output output = Output.A;

                    if (cmd.Equals("b", StringComparison.CurrentCultureIgnoreCase))
                    {
                        output = Output.B;
                    }
                    else if (cmd.Equals("cs", StringComparison.CurrentCultureIgnoreCase))
                    {
                        output = Output.CS;
                    }

                    try {
                        if (args.Length == 0)
                        {
                            bool value = device.GetOutput(output);
                            device.SetOutput(output, !value);
                            Console.WriteLine($"{output}: {!value}");
                        }
                        else
                        {
                            if (args[0].Equals("yes", StringComparison.CurrentCultureIgnoreCase) || args[0].Equals("on", StringComparison.CurrentCultureIgnoreCase))
                            {
                                device.SetOutput(output, true);
                            }
                            else
                            {
                                device.SetOutput(output, false);
                            }
                        }
                    } catch (Exception ex) {
                        Console.Error.WriteLine(ex.Message);
                    }
                }
                else if (cmd.Equals("status", StringComparison.CurrentCultureIgnoreCase))
                {
                    if (device == null)
                    {
                        Console.WriteLine("Not connected to device");
                        continue;
                    }

                    try {
                        DeviceStatus status = device.GetStatus();

                        Console.WriteLine($"Model: {status.Model}");
                        Console.WriteLine($"Serial Number: {status.Serial}");
                        Console.WriteLine($"Uptime: {status.Uptime}");
                        Console.WriteLine($"Voltage: {status.Voltage}V");
                        Console.WriteLine($"Current: {status.Current}A");
                        Console.WriteLine($"Temperature: {status.Temperature}°C");
                        Console.WriteLine($"A: {status.A}");
                        Console.WriteLine($"B: {status.B}");
                        Console.WriteLine($"CS: {status.ChipSelect}");
                        Console.WriteLine($"CRC: 0x{status.Crc.ToString("x4")}");
                    } catch (Exception ex) {
                        Console.Error.WriteLine(ex.Message);
                    }
                }
                else if (cmd.Equals("writef", StringComparison.CurrentCultureIgnoreCase))
                {
                    string path = string.Join(' ', args);

                    if (device == null)
                    {
                        Console.WriteLine("Not connected to device");
                        continue;
                    }
                    else if (args.Length == 0)
                    {
                        Console.WriteLine("No data in arguments");
                        continue;
                    }
                    else if (!File.Exists(path))
                    {
                        Console.WriteLine("File does not exist");
                        continue;
                    }

                    // create stopwatch to time transfer
                    Stopwatch stopwatch = new Stopwatch();

                    try {
                        byte[] fb = File.ReadAllBytes(path);

                        stopwatch.Start();
                        device.Write(fb, 0, fb.Length);

                        Console.WriteLine($"Wrote {fb.Length} bytes in {Math.Round(stopwatch.Elapsed.TotalSeconds, 3)}s");
                    } catch (Exception ex) {
                        Console.Error.WriteLine(ex.Message);
                    }
                }
                else if (cmd.Equals("read", StringComparison.CurrentCultureIgnoreCase))
                {
                    int count = 0;

                    if (device == null)
                    {
                        Console.WriteLine("Not connected to device");
                        continue;
                    }
                    else if (args.Length == 0)
                    {
                        Console.WriteLine("No data in arguments");
                        continue;
                    }
                    else if (!int.TryParse(args[0], out count))
                    {
                        Console.WriteLine("Invalid count to read");
                        continue;
                    }

                    try {
                        byte[] data = new byte[count];
                        device.Read(data, 0, data.Length);

                        Console.WriteLine(BitConverter.ToString(data));
                    } catch (Exception ex) {
                        Console.Error.WriteLine(ex.Message);
                    }
                }
                else if (cmd.Equals("help", StringComparison.CurrentCultureIgnoreCase))
                {
                    Console.WriteLine("connect <port> - connect to serial port");
                    Console.WriteLine("a [on/off] - toggle or set A output");
                    Console.WriteLine("b [on/off] - toggle or set B output");
                    Console.WriteLine("cs [on/off] - toggle or set CS output");
                    Console.WriteLine("status - get device status");
                    Console.WriteLine("writef <path> - write file to SPI");
                }
                else if (line != "quit" && line != "q" && line != "exit")
                {
                    return;
                }
            }
        }
Esempio n. 21
0
 /// <summary>
 /// Reads the LBA28 into buffer.
 /// </summary>
 protected void ReadLBA28IntoBuffer()
 {
     byte drive = (byte)(((deviceHead & 0x10) != 0x10) ? 0 : 1);
     uint lba28 = (uint)((lbaHigh << 16) | (lbaMid << 8) | (lbaLow));
     driveFiles[drive].Seek(lba28 * 512, SeekOrigin.Begin);
     driveFiles[drive].Read(bufferData, 0, 512);
     bufferIndex = 0;
     commandStatus = (byte)((commandStatus | 0x08) & ~0x80); // Set DRQ (bit 3), clear BUSY (bit 7)
     status = DeviceStatus.ReadingSector;
 }
        public virtual (ReceiptInfo, DeviceStatus) PrintReceiptBody(Receipt receipt, bool reversalReceipt = false)
        {
            var receiptInfo = new ReceiptInfo();

            var(fiscalMemorySerialNumber, deviceStatus) = GetFiscalMemorySerialNumber();
            if (!deviceStatus.Ok)
            {
                return(receiptInfo, deviceStatus);
            }

            receiptInfo.FiscalMemorySerialNumber = fiscalMemorySerialNumber;

            if (receipt.Items == null || receipt.Items.Count == 0)
            {
                deviceStatus.AddError("E410", "Receipt.Items must be not null or empty");
                return(receiptInfo, deviceStatus);
            }

            uint itemNumber = 0;

            // Receipt items
            foreach (var item in receipt.Items)
            {
                itemNumber++;
                if (item.Type == ItemType.Comment)
                {
                    (_, deviceStatus) = AddComment(receipt.UniqueSaleNumber, item.Text);
                    if (!deviceStatus.Ok)
                    {
                        deviceStatus.AddInfo($"Error occurred in Item {itemNumber}");
                        return(receiptInfo, deviceStatus);
                    }
                }
                else
                {
                    if (item.PriceModifierValue < 0m)
                    {
                        throw new StandardizedStatusMessageException("PriceModifierValue amount must be positive number", "E403");
                    }
                    if (item.PriceModifierValue != 0m && item.PriceModifierType == PriceModifierType.None)
                    {
                        throw new StandardizedStatusMessageException("PriceModifierValue must be 0 if priceModifierType is None", "E403");
                    }
                    try
                    {
                        (_, deviceStatus) = AddItem(
                            receipt.UniqueSaleNumber,
                            item.Text,
                            item.UnitPrice,
                            item.TaxGroup,
                            item.Quantity,
                            item.PriceModifierValue,
                            item.PriceModifierType,
                            reversalReceipt);
                    }
                    catch (StandardizedStatusMessageException e)
                    {
                        deviceStatus = new DeviceStatus();
                        deviceStatus.AddError(e.Code, e.Message);
                    }
                    if (!deviceStatus.Ok)
                    {
                        deviceStatus.AddInfo($"Error occurred in Item {itemNumber}");
                        return(receiptInfo, deviceStatus);
                    }
                }
            }

            // Get receipt number and amount
            string  receiptNumber;
            decimal?receiptAmount;

            (receiptNumber, receiptAmount, deviceStatus) = GetReceiptNumberAndAmount();
            if (!deviceStatus.Ok)
            {
                return(receiptInfo, deviceStatus);
            }

            receiptInfo.ReceiptNumber = receiptNumber;
            receiptInfo.ReceiptAmount = receiptAmount ?? 0m;

            // Receipt payments
            if (receipt.Payments == null || receipt.Payments.Count == 0)
            {
                deviceStatus = FullPayment();
                if (!deviceStatus.Ok)
                {
                    deviceStatus.AddInfo($"Error occurred while making full payment in cash");
                    return(receiptInfo, deviceStatus);
                }
            }
            else
            {
                uint paymentNumber = 0;
                foreach (var payment in receipt.Payments)
                {
                    paymentNumber++;

                    if (payment.PaymentType == PaymentType.Change)
                    {
                        continue;
                    }

                    try
                    {
                        (_, deviceStatus) = AddPayment(payment.Amount, payment.PaymentType);
                    }
                    catch (StandardizedStatusMessageException e)
                    {
                        deviceStatus = new DeviceStatus();
                        deviceStatus.AddError(e.Code, e.Message);
                    }

                    if (!deviceStatus.Ok)
                    {
                        deviceStatus.AddInfo($"Error occurred in Payment {paymentNumber}");
                        return(receiptInfo, deviceStatus);
                    }
                }
            }

            // Get the receipt date and time (current fiscal device date and time)
            DateTime?dateTime;

            (dateTime, deviceStatus) = GetDateTime();
            if (!deviceStatus.Ok)
            {
                return(receiptInfo, deviceStatus);
            }

            receiptInfo.ReceiptDateTime = dateTime ?? DateTime.Now;

            if (deviceStatus.Ok)
            {
                deviceStatus = FullPayment();
            }

            return(receiptInfo, deviceStatus);
        }
Esempio n. 23
0
 private void OnDeviceStatusChanged(object sender, DeviceStatus args)
 {
     string format = string.Format("【状态改变】设备:{0} 状态发生改变->{1}  时间:{2}", args.Device.EquipName,
         args.StatusDesc, args.GatherTime.ToString());
     AppendText(format);
     if (TreeNodeDict.Keys.Contains(args.Device.Id))
     {
         if (args.Status == 0)
         {
             this.Invoke((MethodInvoker)delegate
             {
                 TreeNodeDict[args.Device.Id].ImageIndex = 0;
             });
         }
         else
         {
             this.Invoke((MethodInvoker)delegate
             {
                 TreeNodeDict[args.Device.Id].ImageIndex = 1;
             });
         }
     }
 }
Esempio n. 24
0
		static RviStatus ConvertToRviStatus(DeviceStatus deviceStatus)
		{
			switch (deviceStatus)
			{
				case DeviceStatus.Connected:
					return RviStatus.Connected;
				case DeviceStatus.Connecting:
					return RviStatus.Connecting;
				case DeviceStatus.Error:
				default:
					return RviStatus.Error;
			}
		}
        public void SyncHTTPSDeviceStatus()
        {
            FileStream stream;
            stream = File.Create(outputFileHTTPSSync);
            results = new StreamWriter(stream);

            DateTime started = DateTime.Now;

            log.WriteLine ("Test Started: SyncHTTPSDeviceStatus");
            log.WriteLine ("Current Time: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.ffffff"));
            log.WriteLine ("Test Run times: " + TestGlobals.maxReps);
            log.WriteLine ("Server: " + TestGlobals.testServer);

            for (int i = 0; i < TestGlobals.maxReps; i++)
            {
                System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();

                status.seqNum = i.ToString();

                DeviceStatus operation = new DeviceStatus(TestGlobals.testServer, status);

                Test statusTest = new Test(operation);
                statusTest.setTestName("ValidSerial");
                statusTest.setExpectedResult ("201");
                statusTest.setType ("performance");

                log.WriteLine ("Test " + i + " Started at " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.ffffff"));
                timer.Start();
                AsyncContext.Run(async () => await new HTTPSCalls().runTest(statusTest, HTTPOperation.POST));
                timer.Stop();

                JObject posted = JObject.FromObject (status);
                log.WriteLine ("Json Posted:");
                log.WriteLine (posted.ToString ());

                double time = timer.Elapsed.TotalMilliseconds;
                results.WriteLine("Test Time," + time);
                log.WriteLine ("Test Lasted: " + time + "ms");

                if (i < 99)
                {
                    log.WriteLine ();
                }

                System.Threading.Thread.Sleep(TestGlobals.delay);
                //Verify Server didn't throw up
            }

            DateTime ended = DateTime.Now;
            TimeSpan lasted = ended - started;

            log.WriteLine ("Test Ended: SyncHTTPSDeviceStatus");
            log.WriteLine ("Current Time: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.ffffff"));
            log.WriteLine ("Test lasted: " + lasted);
            log.WriteLine ("\n\n");

            results.Close();
        }
 private void AddDeviceStatusHistory(PcPoolEntities ctx, int deviceInstanceId, DeviceStatus newDeviceStatus, int userId)
 {
     //var ctx=new PcPoolEntities();
     ctx.DeviceStatusHistories.Add(new PcPoolModels.DeviceStatusHistory()
     {
         DeviceInstanceID = deviceInstanceId,
         ModificationDate = DateTime.Now,
         ModifiedByUserID = userId,
         NewStatusID      = (int)newDeviceStatus
     });
 }
Esempio n. 27
0
 public SystemStatusWrapper(DeviceStatus item)
 {
     this.Item = item;
 }
Esempio n. 28
0
        public virtual DeviceStatus PrintReceiptBody(Receipt receipt)
        {
            if (receipt.Items == null || receipt.Items.Count == 0)
            {
                throw new ArgumentNullException("receipt.Items must be not null or empty");
            }

            var deviceStatus = new DeviceStatus();

            uint itemNumber = 0;

            // Receipt items
            foreach (var item in receipt.Items)
            {
                itemNumber++;
                if (item.IsComment)
                {
                    (_, deviceStatus) = AddComment(item.Text);
                    if (!deviceStatus.Ok)
                    {
                        AbortReceipt();
                        deviceStatus.Statuses.Add($"Error occurred in Item {itemNumber}");
                        return(deviceStatus);
                    }
                }
                else
                {
                    if (item.PriceModifierValue < 0m)
                    {
                        throw new ArgumentOutOfRangeException("priceModifierValue amount must be positive number");
                    }
                    if (item.PriceModifierValue != 0m && item.PriceModifierType == PriceModifierType.None)
                    {
                        throw new ArgumentOutOfRangeException("priceModifierValue must be 0 if priceModifierType is None");
                    }
                    try
                    {
                        (_, deviceStatus) = AddItem(
                            item.Text,
                            item.UnitPrice,
                            item.TaxGroup,
                            item.Quantity,
                            item.PriceModifierValue,
                            item.PriceModifierType);
                    }
                    catch (Exception e)
                    {
                        deviceStatus = new DeviceStatus();
                        deviceStatus.Statuses.Add($"Error occured while in Item {itemNumber}");
                        deviceStatus.Errors.Add(e.Message);
                        return(deviceStatus);
                    }
                    if (!deviceStatus.Ok)
                    {
                        AbortReceipt();
                        deviceStatus.Statuses.Add($"Error occurred in Item {itemNumber}");
                        return(deviceStatus);
                    }
                }
            }

            // Receipt payments
            if (receipt.Payments == null || receipt.Payments.Count == 0)
            {
                (_, deviceStatus) = FullPayment();
                if (!deviceStatus.Ok)
                {
                    AbortReceipt();
                    deviceStatus.Statuses.Add($"Error occurred while making full payment in cash and closing the receipt");
                    return(deviceStatus);
                }
            }
            else
            {
                uint paymentNumber = 0;
                foreach (var payment in receipt.Payments)
                {
                    paymentNumber++;
                    (_, deviceStatus) = AddPayment(payment.Amount, payment.PaymentType);
                    if (!deviceStatus.Ok)
                    {
                        AbortReceipt();
                        deviceStatus.Statuses.Add($"Error occurred in Payment {paymentNumber}");
                        return(deviceStatus);
                    }
                }
            }

            return(deviceStatus);
        }
 public void Connect()
 {
     deviceStatus = (DeviceStatus)deviceInterface?.Connect();
 }
        public static List <DeviceStatus> GetListDeviceStatus(int _userid)
        {
            List <DeviceStatus> lst = new List <DeviceStatus>();

            using (SqlDataReader reader = SqlHelper.ExecuteReader(ConnectData.ConnectionString, "sp_GetListDeviceStatusUser", _userid))
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        DeviceStatus data = new DeviceStatus();
                        data.DeviceID   = Convert.ToInt32(reader["DeviceID"]);
                        data.DeviceName = reader["DeviceName"].ToString();

                        object TypeShip = reader["TypeShip"];
                        if (TypeShip == DBNull.Value)
                        {
                            data.TypeShip = -1;
                        }
                        else
                        {
                            data.TypeShip = Convert.ToInt32(reader["TypeShip"]);
                        }

                        object Latitude = reader["Latitude"];
                        if (Latitude == DBNull.Value)
                        {
                            data.Latitude = -1;
                        }
                        else
                        {
                            data.Latitude = Convert.ToDecimal(reader["Latitude"]);
                        }

                        object Longitude = reader["Longitude"];
                        if (Longitude == DBNull.Value)
                        {
                            data.Longitude = -1;
                        }
                        else
                        {
                            data.Longitude = Convert.ToDecimal(reader["Longitude"]);
                        }
                        data.DirectionSN = reader["DirectionSN"].ToString();
                        data.DirectionEW = reader["DirectionEW"].ToString();

                        object TransmitTime = reader["TransmitTime"];
                        if (TransmitTime == DBNull.Value)
                        {
                            data.TransmitTime = Convert.ToDateTime(reader["DateCreate"]);
                        }
                        else
                        {
                            data.TransmitTime = Convert.ToDateTime(reader["TransmitTime"]);
                        }

                        object Speed = reader["Speed"];
                        if (Speed == DBNull.Value)
                        {
                            data.Speed = -1;
                        }
                        else
                        {
                            data.Speed = Convert.ToInt32(reader["Speed"]);
                        }

                        data.State = Convert.ToInt16(reader["StatusDeVice"]).ToString();
                        //var data = new DeviceStatus()
                        //{
                        //    DeviceID = Convert.ToInt32(reader["DeviceID"]),
                        //    DeviceName = reader["DeviceName"].ToString(),
                        //    TypeShip = Convert.ToInt32(reader["DeviceGroup"]),
                        //    Latitude = Convert.ToDecimal(reader["Latitude"]),
                        //    Longitude = Convert.ToDecimal(reader["Longitude"]),
                        //    DirectionSN = reader["DirectionSN"].ToString(),
                        //    DirectionEW = reader["DirectionEW"].ToString(),
                        //    TransmitTime = Convert.ToDateTime(reader["TransmitTime"]),
                        //    Speed = Convert.ToInt16(reader["Speed"]),

                        //};
                        lst.Add(data);
                    }
                }
            }

            return(lst);
        }
Esempio n. 31
0
        private void timerUpdate_Tick(object sender, EventArgs e)
        {
            TimeSpan elapsed = DateTime.UtcNow - lastRun;

            if (elapsed.TotalMilliseconds < 800)
            {
                return;
            }

            int  count   = listViewDevices.Items.Count;
            bool changed = false;

            // Any configuring?
            bool configuring = false;

            for (int i = 0; i < count; i++)
            {
                uint         testId = (uint)listViewDevices.Items[i].Tag;
                DeviceStatus device = devices[testId];
                if (device.Mode == DeviceStatus.DeviceMode.Configuring)
                {
                    configuring = true; break;
                }
            }

            // Update next element
            for (int i = 0; i < count; i++)
            {
                uint         testId = (uint)listViewDevices.Items[(checkIndex + i) % count].Tag;
                DeviceStatus device = devices[testId];

                // See if a charging device should be configured
                if (!configuring && device.Mode == DeviceStatus.DeviceMode.Charging && device.CanConfigure(MinBattery))
                {
                    device.StartConfigure(ProgramMode, StartDays, StartHour, DurationDays, EndHour, DebugMode);
                    changed = true;
                }
                else
                {
                    if (device.Changed)
                    {
                        changed = true; device.Changed = false;
                    }

                    if (device.Update(device.Mode != DeviceStatus.DeviceMode.Configuring, device.Mode == DeviceStatus.DeviceMode.Charging))
                    {
                        changed = true;
                    }

                    if (device.Mode == DeviceStatus.DeviceMode.Unexpected)
                    {
                        if (autoAdd)
                        {
                            AddExpectedDevice(device.Id);
                        }
                    }
                }

                // NOTE: For now, only deal with one change per iteration
                if (changed)
                {
                    break;
                }
            }

            checkIndex++;
            if (changed)
            {
                UpdateDevices();
            }

            lastRun = DateTime.UtcNow;
        }
        public void Init(string[] available, ref IDTECH_DEVICE_PID mode)
        {
            BaudRate      = int.Parse(ConfigurationManager.AppSettings["IPA.DAL.Device.COMBaudRate"]);
            DataBits      = int.Parse(ConfigurationManager.AppSettings["IPA.DAL.Device.COMDataBits"]);
            AcceptedPorts = ConfigurationManager.AppSettings["IPA.DAL.Device.AcceptedComPorts"].Split(',');

            DeviceFolder = ConfigurationManager.AppSettings["IPA.DAL.Application.Folders.Devices"];
            LoggingLevel = ConfigurationManager.AppSettings["IPA.DAL.Device.LoggingLevel"];

            deviceStatus = DeviceStatus.NoDevice;
            var devices = GetUSBDevices();

            if (devices.Count == 1)
            {
                var vendor = devices[0].Vendor;
                Device.Manufacturer = devices[0].Vendor;

                switch (devices[0].Vendor)
                {
                case DeviceManufacturer.IDTech:
                {
                    var       deviceID = devices[0].DeviceID;
                    string [] worker   = deviceID.Split('&');

                    int pidId = 0;
                    // should contain PID_XXXX...
                    if (System.Text.RegularExpressions.Regex.IsMatch(worker[1], "PID_"))
                    {
                        string [] worker2 = System.Text.RegularExpressions.Regex.Split(worker[1], @"PID_");
                        string    pid     = worker2[1].Substring(0, 4);

                        // See if device matches
                        pidId = Int32.Parse(pid);

                        switch (pidId)
                        {
                        case (int)IDTECH_DEVICE_PID.VP3000_HID:
                        case (int)IDTECH_DEVICE_PID.VP3000_KYB:
                        case (int)IDTECH_DEVICE_PID.SECUREKEY_HID:
                        case (int)IDTECH_DEVICE_PID.AUGUSTA_KYB:
                        case (int)IDTECH_DEVICE_PID.AUGUSTAS_KYB:
                        case (int)IDTECH_DEVICE_PID.AUGUSTA_HID:
                        case (int)IDTECH_DEVICE_PID.AUGUSTAS_HID:
                        case (int)IDTECH_DEVICE_PID.VP5300_HID:
                        {
                            mode = (IDTECH_DEVICE_PID)pidId;
                            break;
                        }

                        default:
                        {
                            mode = IDTECH_DEVICE_PID.UNKNOWN;
                            break;
                        }
                        }
                    }

                    deviceMode = mode;
                    if (mode == IDTECH_DEVICE_PID.AUGUSTA_HID || mode == IDTECH_DEVICE_PID.AUGUSTA_KYB ||
                        mode == IDTECH_DEVICE_PID.AUGUSTAS_HID || mode == IDTECH_DEVICE_PID.AUGUSTAS_KYB)
                    {
                        deviceInterface = new Device_Augusta(deviceMode);
                    }
                    else if (mode == IDTECH_DEVICE_PID.VP5300_HID)
                    {
                        deviceInterface = new Device_VP5300(deviceMode);
                    }

                    /*else if (mode == IDTECH_DEVICE_PID.VP3000_HID || mode == IDTECH_DEVICE_PID.VP3000_KYB)
                     * {
                     *  deviceInterface = new Device_VP3000(deviceMode);
                     * }
                     * else if (mode == IDTECH_DEVICE_PID.SECUREKEY_HID)
                     * {
                     *  deviceInterface = new Device_IDTech(deviceMode);
                     * }
                     * else
                     * {
                     *  Unknown_Device ukd = new Unknown_Device(mode);
                     *  ukd.SetConfig("PID", pidId.ToString());
                     *  deviceInterface = ukd;
                     * }*/
                    deviceInterface.OnNotification += DeviceOnNotification;
                    break;
                }

                case DeviceManufacturer.Ingenico:
                {
///                        deviceInterface = new Device_Ingenico();
///                        deviceInterface.OnNotification += DeviceOnNotification;
                    break;
                }

                default:
                {
                    throw new ArgumentOutOfRangeException(nameof(vendor), vendor, null);
                }
                }
            }
            else if (devices.Count > 1)
            {
                throw new Exception(DeviceStatus.MultipleDevice.ToString());
            }
            else
            {
                throw new Exception(DeviceStatus.NoDevice.ToString());
            }
            deviceInterface?.Init(Device.AcceptedPorts, available, Device.BaudRate, Device.DataBits);
        }
Esempio n. 33
0
        protected override void ProcessCommand(byte command, string parameter)
        {
            switch ((char)command)
            {
            case 'c': string deviceCode = OnGetDeviceCode(); break;

            case 'n':
                if (parameter == "5")
                {
                    DeviceStatus status       = OnGetDeviceStatus();
                    string       stringStatus = ((int)status).ToString();
                    byte[]       output       = new byte[2 + stringStatus.Length + 1];
                    int          i            = 0;
                    output[i++] = EscapeCharacter;
                    output[i++] = LeftBracketCharacter;
                    foreach (char c in stringStatus)
                    {
                        output[i++] = (byte)c;
                    }
                    output[i++] = (byte)'n';
                    OnOutput(output);
                }
                else
                {
                    base.ProcessCommand(command, parameter);
                }
                break;

            case '(': break;        // Set normal font

            case ')': break;        // Set alternative font

            case 'r':
                if (parameter == "")
                {
                    // Set scroll region to entire screen
                }
                else
                {
                    // Set scroll region, separated by ;
                }
                break;

            case 't':
                string[] parameters = parameter.Split(';');
                switch (parameters[0])
                {
                case "3":
                    if (parameters.Length >= 3)
                    {
                        int left, top;
                        if (int.TryParse(parameters[1], out left) && int.TryParse(parameters[2], out top))
                        {
                            OnMoveWindow(new Point(left, top));
                        }
                    }
                    break;

                case "8":
                    if (parameters.Length >= 3)
                    {
                        int rows, columns;
                        if (int.TryParse(parameters[1], out rows) && int.TryParse(parameters[2], out columns))
                        {
                            OnResizeWindow(new Size(columns, rows));
                        }
                    }
                    break;
                }
                break;

            case '!': break;        // Graphics Repeat Introducer

            default: base.ProcessCommand(command, parameter); break;
            }
        }
Esempio n. 34
0
        public void DeviceStatus_CheckAddress()
        {
            var reg = new DeviceStatus(0);

            Assert.Equal(Address.DeviceStatus, reg.Address);
        }
Esempio n. 35
0
 public void VisibleDamageWithObject()
 {
     this.OperationalStatus = this.OperationalStatus.WithVisibleDamage();
 }
Esempio n. 36
0
        /// <summary>
        /// Enable or disable devices.
        /// </summary>
        /// <param name="registryManager">An instance of <c>RegistryManager</c></param>
        /// <param name="deviceIds">The list of device ids to set the status for.</param>
        /// <param name="status">DeviceStatus enum to update to.</param>
        /// <returns>Any errors returned during the bulk update operation.</returns>
        private async Task <IEnumerable <DeviceRegistryOperationError> > SetStatuses(RegistryManager registryManager, IEnumerable <string> deviceIds, DeviceStatus status)
        {
            IEnumerable <Task <Device> > getDeviceTasks = deviceIds.Select(
                async deviceId => await registryManager.GetDeviceAsync(deviceId)
                );

            IEnumerable <Device> deviceListToUpdate = await Task.WhenAll(getDeviceTasks);

            deviceListToUpdate = deviceListToUpdate
                                 .Where(device => device.Status != status)
                                 .Select(device => { device.Status = status; return(device); }).ToList();

            if (deviceListToUpdate.Count() > 0)
            {
                BulkRegistryOperationResult updateResult = await registryManager.UpdateDevices2Async(deviceListToUpdate);

                return(GetRegistryOperationErrors(updateResult));
            }
            else
            {
                return(Enumerable.Empty <DeviceRegistryOperationError>());
            }
        }
Esempio n. 37
0
 public void RepairedWithObject()
 {
     this.OperationalStatus = this.OperationalStatus.Repaired();
 }
Esempio n. 38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WithStatus"/> class.
 /// </summary>
 /// <param name="deviceStatus">The device status.</param>
 public WithStatus(DeviceStatus deviceStatus)
 {
     this.deviceStatus = deviceStatus;
 }
Esempio n. 39
0
 /// <summary>
 /// Initializes this instance.
 /// </summary>
 /// <returns></returns>
 public bool Initialize()
 {
     lbaHigh = 0;
     lbaMid = 0;
     lbaLow = 1;
     sectorCount = 1;
     featureAndError = 1;
     commandStatus = 0;
     status = DeviceStatus.Ready;
     return true;
 }
Esempio n. 40
0
        private IMessage GetSalida(VirlocDeviceCommand dc, GPSPoint.SourceProviders provider)
        {
            var msgid = dc.MessageId ?? 0;

            DeviceStatus devStatus = dc.ParsePosition();

            Console.WriteLine(devStatus.ToString());

            /*
             * // cachear devstatus en de gpspoint
             *          var oldpos = NewestPositionReceived;
             *          if (oldpos == null ||
             *              (oldpos.Date < pos4.Date))
             *              NewestPositionReceived = pos4;
             *
             *          // If the Message Origin is no the LOG, then doesnt process it, just store on CACHE.
             *          if (dc.MessageOrigin != GTEDeviceCommand.Attributes.MessageOrigin_LOG)
             *              break;
             */

            var gpoint = devStatus.Position;

            if (gpoint == null)
            {
                return(null);
            }

            gpoint.SourceProvider = provider;
            MessageIdentifier codigo;

            switch (devStatus.FiredEventNumber)             // codigo del Evento generador del reporte
            {
            case Evento.PanicoConductor:    codigo = MessageIdentifier.DigitalInput01Closed;    break;

            case Evento.PanicoJefe:         codigo = MessageIdentifier.DigitalInput00Closed;    break;

            case Evento.IgnitionOn:         codigo = MessageIdentifier.EngineOnInternal;        break;

            case Evento.IgnitionOff:        codigo = MessageIdentifier.EngineOffInternal;           break;

            case Evento.PowerOn:            codigo = MessageIdentifier.PowerReconnected;        break;

            case Evento.SleepModeOn:        codigo = MessageIdentifier.SleepModeOn;             break;

            case Evento.GPSAntennaInShort:  codigo = MessageIdentifier.GPSAntennaShort;         break;

            case Evento.GPSAntennaDisconnected: codigo = MessageIdentifier.GPSAntennaDisconnected;  break;

            case Evento.CustomerArrivedTo:  codigo = MessageIdentifier.CustomEvent0001;         break;

            case Evento.CustomerLeaved:     codigo = MessageIdentifier.CustomEvent0002;         break;

            case Evento.Parked15Min:        codigo = MessageIdentifier.CustomEvent0003;         break;

            case Evento.NonPlannedParked2Min:   codigo = MessageIdentifier.CustomEvent0004;       break;

            case Evento.StopNotCompleted:   codigo = MessageIdentifier.CustomEvent0005;         break;

            case Evento.CustomerCodeCorrect:    codigo = MessageIdentifier.CustomEvent0006; break;

            case Evento.DoorOpenedOutsideOfStop:    codigo = MessageIdentifier.CustomEvent0007; break;

            case Evento.OperativeCodeEntered:   codigo = MessageIdentifier.CustomEvent0008; break;

            case Evento.MovementDetectedWithoutStopEnd: codigo = MessageIdentifier.CustomEvent0009; break;

            case Evento.EventualCodeEntered:    codigo = MessageIdentifier.CustomEvent0010; break;

            case Evento.StopNotice:         codigo = MessageIdentifier.CustomEvent0011; break;

            case Evento.TreasureDoorOpenWithDoorOpenIgnitionOffNotFixed:    codigo = MessageIdentifier.CustomEvent0012; break;

            case Evento.TreasureDoorOpenInPanicMode:    codigo = MessageIdentifier.CustomEvent0013; break;

            case Evento.TreasureDoorOpenOutOfCustomer:  codigo = MessageIdentifier.CustomEvent0014; break;

            case Evento.TreasureDoorOpenOutOfSequence:  codigo = MessageIdentifier.CustomEvent0015; break;

            case Evento.TreasureDoorOpenWithCorrectCode: codigo = MessageIdentifier.CustomEvent0016; break;

            case Evento.TreasureDoorOpenOutsideStop:    codigo = MessageIdentifier.CustomEvent0017; break;

            case Evento.TreasureDoorReadyButNotOpened:  codigo = MessageIdentifier.CustomEvent0018; break;

            case Evento.ForceCodeEnteredForTreasureDoorOpening: codigo = MessageIdentifier.CustomEvent0019; break;

            case Evento.TreasureDoorOpen:   codigo = MessageIdentifier.CustomEvent0020;         break;

            case Evento.AlarmDeactivatedFromVehicle:    codigo = MessageIdentifier.CustomEvent0021; break;

            case Evento.AITOffByKey:        codigo = MessageIdentifier.CustomEvent0022;         break;

            case Evento.AITOffByCode:       codigo = MessageIdentifier.CustomEvent0023;         break;

            case Evento.GabineteApertura:   codigo = MessageIdentifier.DigitalInput03Open;      break;

            case Evento.GabineteCierre:     codigo = MessageIdentifier.DigitalInput03Closed;    break;

            default:
                return(gpoint.ToPosition(Id, msgid));
            }
            return(codigo.FactoryEvent(Id, msgid, gpoint, gpoint.GetDate(), null, null));
        }
Esempio n. 41
0
        /// <summary>
        /// Reads the data port.
        /// </summary>
        /// <returns></returns>
        protected byte ReadData()
        {
            if ((status == DeviceStatus.Ready) || (status == DeviceStatus.WritingSector))
                return 0xFF;

            byte data = bufferData[bufferIndex++];

            if (bufferIndex == 512) {
                if (status == DeviceStatus.IdentifyDrive)
                    bufferIndex = 0;
                else {
                    sectorCount = (byte)(sectorCount - 1);
                    if (sectorCount != 0) {
                        ReadLBA28IntoBuffer();
                        SetLBA28(GetLBA28() + 1);
                    }
                    else
                        status = DeviceStatus.Ready;
                }
            }

            return data;
        }
Esempio n. 42
0
 public static void OnDeviceStatusReceived(SipDevice sipDevice, DeviceStatus deviceStatus)
 {
     //获取到设备状态时
 }
Esempio n. 43
0
        private void ParameterUpdate(MessageUpdater.UpdateTypes type, char address, object data)
        {
            switch (type)
            {
            case MessageUpdater.UpdateTypes.DeviceInfo:
            {
                DeviceID info = data as DeviceID;
                if ((info != null) && _deviceViewModels.ContainsKey(address))
                {
                    _dispatcher.BeginInvoke(() => _deviceViewModels[address].Description = info.Description());
                }
            }
            break;

            case MessageUpdater.UpdateTypes.MotorInfo:
            {
                MotorInfo info = data as MotorInfo;
                if ((info != null) && _deviceViewModels.ContainsKey(address))
                {
                    ELLMotorViewModel first = _deviceViewModels[address].Motors.FirstOrDefault(motor => motor.MotorID == info.MotorID);
                    if (first != null)
                    {
                        _dispatcher.BeginInvoke(() => first.UpdateInfo(info));
                    }
                }
            }
            break;

            case MessageUpdater.UpdateTypes.Status:
            {
                DeviceStatus status = data as DeviceStatus;
                if (status != null)
                {
                    switch (status.Status)
                    {
                    case DeviceStatus.DeviceStatusValues.OK:
                        break;

                    case DeviceStatus.DeviceStatusValues.Busy:
                        break;

                    default:
                        MessageBox.Show(string.Format("Device error: {0}", status.Status.GetStringValue()), "Device Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        break;
                    }
                }
            }
            break;

            case MessageUpdater.UpdateTypes.Position:
            {
                try
                {
                    decimal position = (decimal)data;
                    if (_deviceViewModels.ContainsKey(address))
                    {
                        _dispatcher.BeginInvoke(() => _deviceViewModels[address].UpdatePosition(position));
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(string.Format("Device error: status {0}", e.Message), "Device Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            break;

            case MessageUpdater.UpdateTypes.PolarizerPositions:
            {
                try
                {
                    ELLPaddlePolariser.PolarizerPaddlePositions positions = (ELLPaddlePolariser.PolarizerPaddlePositions)data;
                    if (_deviceViewModels.ContainsKey(address))
                    {
                        ELLPaddlePolariserViewModel paddleViewModel = _deviceViewModels[address] as ELLPaddlePolariserViewModel;
                        if (paddleViewModel != null)
                        {
                            _dispatcher.BeginInvoke(() => paddleViewModel.UpdatePaddlePosition(positions));
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(string.Format("Device error: status {0}", e.Message), "Device Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            break;

            case MessageUpdater.UpdateTypes.PaddlePosition:
            {
                try
                {
                    ELLPaddlePolariser.PaddlePosition position = (ELLPaddlePolariser.PaddlePosition)data;
                    if (_deviceViewModels.ContainsKey(address))
                    {
                        ELLPaddlePolariserViewModel paddleViewModel = _deviceViewModels[address] as ELLPaddlePolariserViewModel;
                        if (paddleViewModel != null)
                        {
                            _dispatcher.BeginInvoke(() => paddleViewModel.UpdatePaddlePosition(position));
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(string.Format("Device error: status {0}", e.Message), "Device Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            break;

            case MessageUpdater.UpdateTypes.HomeOffset:
            {
                try
                {
                    decimal homeOffset = (decimal)data;
                    if (_deviceViewModels.ContainsKey(address))
                    {
                        _dispatcher.BeginInvoke(() => _deviceViewModels[address].UpdateHomeOffset(homeOffset));
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(string.Format("Device error: status {0}", e.Message), "Device Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            break;

            case MessageUpdater.UpdateTypes.JogstepSize:
            {
                try
                {
                    decimal jogStep = (decimal)data;
                    if (_deviceViewModels.ContainsKey(address))
                    {
                        _dispatcher.BeginInvoke(() => _deviceViewModels[address].UpdateJogstepSize(jogStep));
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(string.Format("Device error: status {0}", e.Message), "Device Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            break;
            }
        }
Esempio n. 44
0
        /// <summary>
        /// Message消息处理
        /// </summary>
        /// <param name="localEP">本地终结点</param>
        /// <param name="remoteEP">远程终结点</param>
        /// <param name="request">sip请求</param>
        private void MessageHandle(SIPEndPoint localEP, SIPEndPoint remoteEP, SIPRequest request)
        {
            SendResponse(localEP, remoteEP, request);

            //心跳消息
            KeepAlive keepAlive = KeepAlive.Instance.Read(request.Body);

            if (keepAlive != null && keepAlive.CmdType == CommandType.Keepalive)
            {
                KeepaliveHandle(localEP, remoteEP, request, keepAlive);
                return;
            }


            //设备目录
            Catalog catalog = Catalog.Instance.Read(request.Body);

            if (catalog != null && catalog.CmdType == CommandType.Catalog)
            {
                CatalogHandle(localEP, remoteEP, request, catalog);
                return;
            }

            //录像查询
            RecordInfo record = RecordInfo.Instance.Read(request.Body);

            if (record != null && record.CmdType == CommandType.RecordInfo)
            {
                RecordInfoHandle(localEP, remoteEP, request, record);
                return;
            }

            //媒体通知
            MediaStatus mediaStatus = MediaStatus.Instance.Read(request.Body);

            if (mediaStatus != null && mediaStatus.CmdType == CommandType.MediaStatus)
            {
                MonitorKey key = new MonitorKey()
                {
                    CmdType  = CommandType.Playback,
                    DeviceID = request.Header.From.FromURI.User
                };
                MonitorService[key].ByeVideoReq();
                //取值121表示历史媒体文件发送结束(回放结束/下载结束)
                //NotifyType未找到相关文档标明所有该类型值,暂时只处理121
                if (mediaStatus.NotifyType.Equals("121"))
                {
                    if (OnMediaStatusReceived != null)
                    {
                        OnMediaStatusReceived(remoteEP, mediaStatus);
                    }
                }
                return;
            }

            //设备状态查询
            DeviceStatus deviceStatus = DeviceStatus.Instance.Read(request.Body);

            if (deviceStatus != null && deviceStatus.CmdType == CommandType.DeviceStatus)
            {
                if (OnDeviceStatusReceived != null)
                {
                    OnDeviceStatusReceived(remoteEP, deviceStatus);
                }
                return;
            }

            //设备信息查询
            DeviceInfo deviceInfo = DeviceInfo.Instance.Read(request.Body);

            if (deviceInfo != null && deviceInfo.CmdType == CommandType.DeviceInfo)
            {
                if (OnDeviceInfoReceived != null)
                {
                    OnDeviceInfoReceived(remoteEP, deviceInfo);
                }
                return;
            }

            //设备配置查询
            DeviceConfigDownload devDownload = DeviceConfigDownload.Instance.Read(request.Body);

            if (devDownload != null && devDownload.CmdType == CommandType.ConfigDownload)
            {
                if (OnDeviceConfigDownloadReceived != null)
                {
                    OnDeviceConfigDownloadReceived(remoteEP, devDownload);
                }
            }

            //预置位查询
            PresetInfo preset = PresetInfo.Instance.Read(request.Body);

            if (preset != null && preset.CmdType == CommandType.PresetQuery)
            {
                if (OnPresetQueryReceived != null)
                {
                    OnPresetQueryReceived(remoteEP, preset);
                }
            }

            //报警通知
            Alarm alarm = Alarm.Instance.Read(request.Body);

            if (alarm != null && alarm.CmdType == CommandType.Alarm)//单兵上报经纬度
            {
                if (OnAlarmReceived != null)
                {
                    OnAlarmReceived(alarm);
                }
            }
        }
Esempio n. 45
0
        private void UpdateDeviceStatus()
        {
            try
            {
                if (_deviceStatus == null)
                {
                    _deviceStatus = ReadFormStatus();
                }

                var updatedStatus = ReadDeviceStatus();

                if (_deviceStatus == updatedStatus) return;

                if (updatedStatus.Red != _deviceStatus.Red)
                {
                    UpdateLightStatus(_red, updatedStatus.Red, _deviceStatus.Red);
                }

                if (updatedStatus.Green != _deviceStatus.Green)
                {
                    UpdateLightStatus(_green, updatedStatus.Green, _deviceStatus.Green);
                }

                if (updatedStatus.BlueYellow != _deviceStatus.BlueYellow)
                {
                    UpdateLightStatus(_blueYellow, updatedStatus.BlueYellow, _deviceStatus.BlueYellow);
                }

                _deviceStatus = updatedStatus;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                throw;
            }
        }
Esempio n. 46
0
        protected virtual DeviceStatus PrintReceiptBody(Receipt receipt)
        {
            if (receipt.Items == null || receipt.Items.Count == 0)
            {
                throw new StandardizedStatusMessageException("Receipt.Items must be not null or empty", "E410");
            }

            DeviceStatus deviceStatus;

            uint itemNumber = 0;

            // Receipt items
            foreach (var item in receipt.Items)
            {
                itemNumber++;
                if (item.Type == ItemType.Comment)
                {
                    (_, deviceStatus) = AddComment(item.Text);
                    if (!deviceStatus.Ok)
                    {
                        AbortReceipt();
                        deviceStatus.AddInfo($"Error occurred in the comment of Item {itemNumber}");
                        return(deviceStatus);
                    }
                }
                else
                {
                    if (item.PriceModifierValue < 0m)
                    {
                        throw new StandardizedStatusMessageException("PriceModifierValue amount must be positive number", "E403");
                    }
                    if (item.PriceModifierValue != 0m && item.PriceModifierType == PriceModifierType.None)
                    {
                        throw new StandardizedStatusMessageException("PriceModifierValue must be 0 if priceModifierType is None", "E403");
                    }
                    try
                    {
                        (_, deviceStatus) = AddItem(
                            item.Text,
                            item.UnitPrice,
                            item.TaxGroup,
                            item.Quantity,
                            item.PriceModifierValue,
                            item.PriceModifierType);
                    }
                    catch (StandardizedStatusMessageException e)
                    {
                        deviceStatus = new DeviceStatus();
                        deviceStatus.AddError(e.Code, e.Message);
                    }
                    if (!deviceStatus.Ok)
                    {
                        AbortReceipt();
                        deviceStatus.AddInfo($"Error occurred in Item {itemNumber}");
                        return(deviceStatus);
                    }
                }
            }

            // Receipt payments
            if (receipt.Payments == null || receipt.Payments.Count == 0)
            {
                (_, deviceStatus) = FullPaymentAndCloseReceipt();
                if (!deviceStatus.Ok)
                {
                    AbortReceipt();
                    deviceStatus.AddInfo($"Error occurred while making full payment in cash and closing the receipt");
                    return(deviceStatus);
                }
            }
            else
            {
                uint paymentNumber = 0;
                foreach (var payment in receipt.Payments)
                {
                    paymentNumber++;

                    if (payment.PaymentType == PaymentType.Change)
                    {
                        continue;
                    }

                    try
                    {
                        (_, deviceStatus) = AddPayment(payment.Amount, payment.PaymentType);
                    }
                    catch (StandardizedStatusMessageException e)
                    {
                        deviceStatus = new DeviceStatus();
                        deviceStatus.AddError(e.Code, e.Message);
                    }

                    if (!deviceStatus.Ok)
                    {
                        AbortReceipt();
                        deviceStatus.AddInfo($"Error occurred in Payment {paymentNumber}");
                        return(deviceStatus);
                    }
                }
                (_, deviceStatus) = CloseReceipt();
                if (!deviceStatus.Ok)
                {
                    AbortReceipt();
                    deviceStatus.AddInfo($"Error occurred while closing the receipt");
                    return(deviceStatus);
                }
            }

            return(deviceStatus);
        }
 public DeviceMapEntry([NotNull] DeviceStatus status, [NotNull] TimerCallback entryExpiredCallback)
 {
     LastStatus = status;
     expiryTimer = new Timer(entryExpiredCallback, this, Timeout.Infinite, Timeout.Infinite);
 }
 public HouseholdDeviceUpdateStatusRequestBuilder(string udid, DeviceStatus status)
     : this()
 {
     this.Udid   = udid;
     this.Status = status;
 }
        public void MultiClientStatus()
        {
            FileStream stream;
            stream = File.Create(outputFileMultiClientStatus);
            results = new StreamWriter(stream);

            DateTime started = DateTime.Now;

            log.WriteLine ("Test Started: MultiClientDeviceStatus");
            log.WriteLine ("Current Time: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.ffffff"));
            log.WriteLine ("Server: " + TestGlobals.testServer);

            // Construct started tasks
            Task<double>[,] tasks = new Task<double>[TestGlobals.maxReps, 2];

            DateTime[] testStarted1 = new DateTime[TestGlobals.maxReps];
            DateTime[] testStarted2 = new DateTime[TestGlobals.maxReps];
            JObject[] statusPosted1 = new JObject[TestGlobals.maxReps];
            JObject[] statusPosted2 = new JObject[TestGlobals.maxReps];

            for (int i = 0; i < TestGlobals.maxReps; i++)
            {
                System.Threading.Thread.Sleep(TestGlobals.delay);

                // client 1
                status.seqNum = i.ToString();
                DeviceStatus operation1 = new DeviceStatus(TestGlobals.testServer, status);

                Test statusTest1 = new Test(operation1);
                statusTest1.setTestName("ValidSerial");
                statusTest1.setExpectedResult ("201");
                statusTest1.setType ("performance");

                tasks[i, 0] = new HTTPCalls().runTest(statusTest1, HTTPOperation.POST);
                testStarted1[i] = HTTPCalls.started;
                JObject Json1 = JObject.FromObject(status);
                statusPosted1[i] = Json1;

                // client 2
                status.seqNum = i.ToString();
                DeviceStatus operation2 = new DeviceStatus(TestGlobals.testServer, status);

                Test statusTest2 = new Test(operation2);
                statusTest2.setTestName("ValidSerial");
                statusTest2.setExpectedResult ("201");
                statusTest2.setType ("performance");

                tasks[i, 1] = new HTTPCalls().runTest(statusTest2, HTTPOperation.POST);
                testStarted2[i] = HTTPCalls.started;
                JObject Json2 = JObject.FromObject(status);
                statusPosted2[i] = Json2;

                Console.WriteLine("Test starting:" + i.ToString());
                Task.WaitAll(tasks[i, 0], tasks[i, 1]);
            }

            log.WriteLine ("Client 1:");
            for(int i = 0; i < TestGlobals.maxReps; i++)
            {
                results.WriteLine ("Test Time," + tasks[i, 0].Result);

                log.WriteLine ("Client 1 Test " + i + " Started at " + testStarted1 [i].ToString ("yyyy-MM-dd hh:mm:ss.ffffff"));
                log.WriteLine ("Json Posted:");
                log.WriteLine (statusPosted1 [i].ToString ());
                log.WriteLine ("Test Lasted: " + tasks[i, 0].Result + "ms");
                log.WriteLine ();
            }

            log.WriteLine ("Client 2:");
            for(int i = 0; i < TestGlobals.maxReps; i++)
            {
                results.WriteLine ("Test Time," + tasks[i, 1].Result);

                log.WriteLine ("Client 2 Test " + i + " Started at " + testStarted2 [i].ToString ("yyyy-MM-dd hh:mm:ss.ffffff"));
                log.WriteLine ("Json Posted:");
                log.WriteLine (statusPosted2 [i].ToString ());
                log.WriteLine ("Test Lasted: " + tasks[i, 1].Result + "ms");
                if (i < 99)
                {
                    log.WriteLine ();
                }
            }

            DateTime ended = DateTime.Now;
            TimeSpan lasted = ended - started;

            log.WriteLine ("Test Ended: MultiClientDeviceStatus");
            log.WriteLine ("Current Time: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.ffffff"));
            log.WriteLine ("Test lasted: " + lasted);
            log.WriteLine ("\n\n");

            results.Close();
        }
 public static HouseholdDeviceUpdateStatusRequestBuilder UpdateStatus(string udid, DeviceStatus status)
 {
     return(new HouseholdDeviceUpdateStatusRequestBuilder(udid, status));
 }
        public void AsyncHTTPDeviceStatus()
        {
            FileStream stream;
            stream = File.Create(outputFileHTTPAsync);
            results = new StreamWriter(stream);

            DateTime started = DateTime.Now;

            log.WriteLine ("Test Started: AsyncHTTPDeviceStatus");
            log.WriteLine ("Current Time: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.ffffff"));
            log.WriteLine ("Test Run times: " + TestGlobals.maxReps);
            log.WriteLine ("Server: " + TestGlobals.testServer);

            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();

            // Construct started tasks
            Task<double>[] tasks = new Task<double>[TestGlobals.maxReps];

            DateTime[] testStarted = new DateTime [TestGlobals.maxReps];
            JObject[] statusPosted = new JObject[TestGlobals.maxReps];

            for (int i = 0; i < TestGlobals.maxReps; i++)
            {
                System.Threading.Thread.Sleep(TestGlobals.delay);

                status.seqNum = i.ToString();
                DeviceStatus operation = new DeviceStatus(TestGlobals.testServer, status);
                Test statusTest = new Test(operation);
                statusTest.setTestName("ValidSerial");
                statusTest.setExpectedResult ("201");
                statusTest.setType ("performance");

                List<Test> tests = new List<Test>();
                tests.Add(statusTest);

                tasks[i] = new HTTPCalls().runTest(statusTest, HTTPOperation.POST);
                testStarted [i] = HTTPCalls.started;
                JObject Json = JObject.FromObject(status);
                statusPosted[i] = Json;

                Console.WriteLine("Test starting:" + i.ToString());
            }
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("All tests initialized, waiting on them to run as async");
            Console.WriteLine("------------------------------------------------------");
            Task.WaitAll(tasks);

            int seq = 0;
            foreach (Task<double> nextResult in tasks)
            {
                results.WriteLine("Test Time," + nextResult.Result);

                log.WriteLine ("Test " + seq + " Started at " + testStarted[seq].ToString("yyyy-MM-dd hh:mm:ss.ffffff"));
                log.WriteLine ("Json Posted:");
                log.WriteLine (statusPosted[seq].ToString ());
                log.WriteLine ("Test Lasted: " + nextResult.Result + "ms");
                seq++;
                if (seq < 99)
                {
                    log.WriteLine ();
                }

            }

            DateTime ended = DateTime.Now;
            TimeSpan lasted = ended - started;

            log.WriteLine ("Test Ended: AsyncHTTPDeviceStatus");
            log.WriteLine ("Current Time: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.ffffff"));
            log.WriteLine ("Test lasted: " + lasted);
            log.WriteLine ("\n\n");

            results.Close();
        }
Esempio n. 52
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            int indent = EditorGUI.indentLevel;

            EditorGUI.indentLevel = 0;

            EditorGUI.BeginProperty(position, label, property);
            Rect line = new Rect(
                position.x,
                position.y,
                position.width,
                WearableEditorConstants.SINGLE_LINE_HEIGHT);

            // Device Status
            EditorGUI.LabelField(line, DEVICE_STATUS_HEADING);
            line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT;

            Rect box = new Rect(
                line.x,
                line.y,
                line.width,
                line.height * (WearableConstants.DEVICE_STATUS_FLAGS.Length - 2));                 // Flag count less "None" and "Suspended"

            GUI.Box(box, GUIContent.none);

            var          statusValueProp = property.FindPropertyRelative(STATUS_VALUES_FIELD);
            DeviceStatus status          = statusValueProp.intValue;

            for (int i = 0; i < WearableConstants.DEVICE_STATUS_FLAGS.Length; i++)
            {
                DeviceStatusFlags flag = WearableConstants.DEVICE_STATUS_FLAGS[i];
                if (flag == DeviceStatusFlags.None ||
                    flag == DeviceStatusFlags.SensorServiceSuspended)
                {
                    continue;
                }

                using (new EditorGUI.DisabledScope(flag == DeviceStatusFlags.SensorServiceSuspended))
                {
                    bool value = EditorGUI.Toggle(
                        line,
                        flag.ToString(),
                        status.GetFlagValue(flag));

                    status.SetFlagValue(flag, value);
                }

                line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT;
            }
            statusValueProp.intValue = status;


            // Transmission period
            // No-op

            // ANR header
            line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT * 0.5f;
            EditorGUI.LabelField(line, ANR_HEADING);
            line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT;
            box     = new Rect(
                line.x,
                line.y,
                line.width,
                WearableEditorConstants.SINGLE_LINE_HEIGHT * (WearableConstants.ACTIVE_NOISE_REDUCTION_MODES.Length + 1));
            GUI.Box(box, GUIContent.none);


            // ANR current mode (read-only)
            using (new EditorGUI.DisabledScope(true))
            {
                var anrModeProperty = property.FindPropertyRelative(CURRENT_ANR_MODE_FIELD);
                var anrMode         = (ActiveNoiseReductionMode)anrModeProperty.intValue;
                EditorGUI.LabelField(line, CURRENT_ANR_MODE_LABEL, anrMode.ToString());
                line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT;
            }

            // ANR available modes
            EditorGUI.LabelField(line, AVAILABLE_ANR_MODES_HEADING);
            line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT;

            EditorGUI.indentLevel++;
            var availableAnrModesProperty = property.FindPropertyRelative(AVAILABLE_ANR_MODES_FIELD);
            int oldAnrModes = availableAnrModesProperty.intValue;
            int newAnrModes = 0;

            for (int i = 0; i < WearableConstants.ACTIVE_NOISE_REDUCTION_MODES.Length; i++)
            {
                ActiveNoiseReductionMode mode = WearableConstants.ACTIVE_NOISE_REDUCTION_MODES[i];

                if (mode == ActiveNoiseReductionMode.Invalid)
                {
                    continue;
                }

                int  flag     = (1 << (int)mode);
                bool selected = EditorGUI.Toggle(line, mode.ToString(), (flag & oldAnrModes) != 0);
                line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT;
                if (selected)
                {
                    newAnrModes |= flag;
                }
            }

            EditorGUI.indentLevel--;

            if (newAnrModes != oldAnrModes)
            {
                availableAnrModesProperty.intValue = newAnrModes;
            }

            // CNC header
            line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT * 0.5f;
            EditorGUI.LabelField(line, CNC_HEADING);
            line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT;
            box     = new Rect(
                line.x,
                line.y,
                line.width,
                WearableEditorConstants.SINGLE_LINE_HEIGHT * 3);
            GUI.Box(box, GUIContent.none);

            using (new EditorGUI.DisabledScope(true))
            {
                // CNC Level (read-only)
                var cncLevelProperty = property.FindPropertyRelative(CNC_LEVEL_FIELD);
                EditorGUI.LabelField(line, CNC_LEVEL_LABEL_TEXT, cncLevelProperty.intValue.ToString());
                line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT;

                // CNC Enabled (read-only)
                var cncEnabledProperty = property.FindPropertyRelative(CNC_ENABLED_FIELD);
                EditorGUI.Toggle(line, CNC_ENABLED_LABEL, cncEnabledProperty.boolValue);
                line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT;
            }

            // Total CNC levels
            var totalCncLevelsProperty = property.FindPropertyRelative(TOTAL_CNC_LEVELS_FIELD);

            EditorGUI.PropertyField(line, totalCncLevelsProperty, _totalCncLevelsLabel);
            line.y += WearableEditorConstants.SINGLE_LINE_HEIGHT;
            if (totalCncLevelsProperty.intValue < 0)
            {
                totalCncLevelsProperty.intValue = 0;
            }

            EditorGUI.EndProperty();
            property.serializedObject.ApplyModifiedProperties();
            EditorGUI.indentLevel = indent;
        }
Esempio n. 53
0
 public static PropertyStates NewSystemStatus(DeviceStatus systemStatus)
 {
     return new SystemStatusWrapper(systemStatus);
 }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            WearableDebugProvider provider = (WearableDebugProvider)fieldInfo.GetValue(property.serializedObject.targetObject);

            EditorGUI.BeginProperty(position, label, property);

            EditorGUILayout.HelpBox(DESCRIPTION_BOX, MessageType.None);
            EditorGUILayout.Space();

            // Virtual device config
            if (provider.ConnectedDevice.HasValue)
            {
                EditorGUILayout.HelpBox(string.Format(DEVICE_CONFIG_FIELDS_DISABLED_BOX_FORMAT, DISCONNECT_LABEL), MessageType.Info);
            }

            using (new EditorGUI.DisabledScope(provider.ConnectedDevice.HasValue))
            {
                // Device properties
                EditorGUILayout.IntSlider(
                    property.FindPropertyRelative(RSSI_FIELD),
                    WearableConstants.MINIMUM_RSSI_VALUE,
                    WearableConstants.MAXIMUM_RSSI_VALUE,
                    WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);

                EditorGUILayout.Separator();
                EditorGUILayout.PropertyField(
                    property.FindPropertyRelative(DEVICE_NAME_FIELD),
                    WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                EditorGUILayout.PropertyField(
                    property.FindPropertyRelative(UID_FIELD),
                    WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);

                // draw product and variant types based on ids
                var productIdProp = property.FindPropertyRelative(PRODUCT_ID_FIELD);
                _productType = WearableTools.GetProductType((ProductId)productIdProp.intValue);
                var variantProp = property.FindPropertyRelative(VARIANT_ID_FIELD);

                EditorGUI.BeginChangeCheck();
                _productType = (ProductType)EditorGUILayout.EnumPopup(
                    PRODUCT_TYPE_LABEL,
                    _productType
                    );
                if (EditorGUI.EndChangeCheck())
                {
                    // if we have changed the product, we need to reset the variants
                    productIdProp.intValue        = (int)WearableTools.GetProductId(_productType);
                    variantProp.intValue          = 0;
                    _editorVariantOptionsAreDirty = true;
                }

                if (_editorVariantOptionsAreDirty)
                {
                    _editorVariantMap             = GetVariantMap(_productType);
                    _editorVariantOptions         = _editorVariantMap.Keys.ToArray();
                    _editorVariantOptionsAreDirty = false;
                }

                string variantName = GetNameForProductAndVariantId(_productType, (byte)variantProp.intValue);
                var    optionIndex = Array.IndexOf(_editorVariantOptions, variantName);
                _editorVariantIndex = EditorGUILayout.Popup(
                    VARIANT_TYPE_LABEL,
                    optionIndex >= 0 ? optionIndex : 0,
                    _editorVariantOptions
                    );

                variantProp.intValue = _editorVariantMap[_editorVariantOptions[_editorVariantIndex]];

                GUILayoutTools.LineSeparator();

                // Permissions and services
                var permissionsProperty  = property.FindPropertyRelative(GRANTED_PERMISSIONS_FIELD);
                var permissionsEnumValue = EditorGUILayout.EnumFlagsField(
                    new GUIContent(GRANTED_PERMISSIONS_LABEL),
                    provider.GrantedPermissions);
                var permissionFlags = (OSPermissionFlags)Convert.ChangeType(permissionsEnumValue, typeof(OSPermissionFlags));
                permissionsProperty.intValue = (int)permissionFlags;

                var allPermissionsGranted = true;
                var allPermissionFlags    = ((OSPermissionFlags[])Enum.GetValues(typeof(OSPermissionFlags)))
                                            .Where(x => x != OSPermissionFlags.None);
                foreach (var flag in allPermissionFlags)
                {
                    if ((permissionFlags & flag) != flag)
                    {
                        allPermissionsGranted = false;
                        break;
                    }
                }

                EditorGUILayout.PropertyField(
                    property.FindPropertyRelative(GRANT_PERMISSIONS_FIELD),
                    new GUIContent(USER_GRANTED_PERMISSIONS_LABEL));

                if (allPermissionsGranted)
                {
                    EditorGUILayout.HelpBox(ALL_PERMISSIONS_GRANTED_BOX, MessageType.Info);
                }
                else if (provider.GrantPermissions)
                {
                    EditorGUILayout.HelpBox(SOME_PERMISSIONS_MISSING_BOX, MessageType.Warning);
                }
                else
                {
                    EditorGUILayout.HelpBox(SOME_PERMISSIONS_MISSING_FAIL_BOX, MessageType.Error);
                }

                var servicesProperty  = property.FindPropertyRelative(ENABLED_SERVICES_FIELD);
                var servicesEnumValue = EditorGUILayout.EnumFlagsField(
                    new GUIContent(ENABLED_SERVICES_LABEL),
                    provider.EnabledServices);
                var servicesFlag = (OSServiceFlags)Convert.ChangeType(servicesEnumValue, typeof(OSServiceFlags));
                servicesProperty.intValue = (int)servicesFlag;

                var allServicesEnabled = true;
                var allServicesFlags   = ((OSServiceFlags[])Enum.GetValues(typeof(OSServiceFlags)))
                                         .Where(x => x != OSServiceFlags.None);
                foreach (var flag in allServicesFlags)
                {
                    if ((servicesFlag & flag) != flag)
                    {
                        allServicesEnabled = false;
                        break;
                    }
                }

                if (allServicesEnabled)
                {
                    EditorGUILayout.HelpBox(ALL_SERVICES_GRANTED_BOX, MessageType.Info);
                }
                else
                {
                    EditorGUILayout.HelpBox(SOME_SERVICES_MISSING_FAIL_BOX, MessageType.Error);
                }

                GUILayoutTools.LineSeparator();

                // Firmware simulation
                EditorGUILayout.PropertyField(
                    property.FindPropertyRelative(FIRMWARE_VERSION_FIELD),
                    WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                var firmwareSufficient = property.FindPropertyRelative(BOSE_AR_ENABLED_FIELD);
                var firmwareAvailable  = property.FindPropertyRelative(FIRMWARE_UPDATE_AVAILABLE_FIELD);
                EditorGUILayout.PropertyField(firmwareSufficient, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                EditorGUILayout.PropertyField(firmwareAvailable, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);

                if (firmwareSufficient.boolValue)
                {
                    if (firmwareAvailable.boolValue)
                    {
                        EditorGUILayout.HelpBox(FIRMWARE_UPDATE_AVAILABLE_BOX, MessageType.Info);
                    }
                    else
                    {
                        EditorGUILayout.HelpBox(FIRMWARE_GOOD_BOX, MessageType.Info);
                    }
                }
                else
                {
                    if (firmwareAvailable.boolValue)
                    {
                        EditorGUILayout.HelpBox(FIRMWARE_UPDATE_REQUIRED_BOX, MessageType.Warning);
                    }
                    else
                    {
                        EditorGUILayout.HelpBox(FIRMWARE_DEVICE_NOT_SUPPORTED_BOX, MessageType.Error);
                    }
                }

                // Secure pairing
                var acceptSecurePairing = property.FindPropertyRelative(ACCEPT_SECURE_PAIRING_FIELD);
                EditorGUILayout.PropertyField(acceptSecurePairing, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                if (acceptSecurePairing.boolValue)
                {
                    EditorGUILayout.HelpBox(SECURE_PAIRING_ACCEPTED_BOX, MessageType.Info);
                }
                else
                {
                    EditorGUILayout.HelpBox(SECURE_PAIRING_REJECTED_BOX, MessageType.Error);
                }

                // Sensor and gesture availability
                var sensorFlagsProp      = property.FindPropertyRelative(SENSOR_FLAGS_FIELD);
                var sensorFlagsEnumValue = EditorGUILayout.EnumFlagsField(sensorFlagsProp.displayName, provider.AvailableSensors);
                sensorFlagsProp.intValue = (int)Convert.ChangeType(sensorFlagsEnumValue, typeof(SensorFlags));

                var gestureFlagsProp      = property.FindPropertyRelative(GESTURE_FLAGS_FIELD);
                var gestureFlagsEnumValue = EditorGUILayout.EnumFlagsField(gestureFlagsProp.displayName, provider.AvailableGestures);
                gestureFlagsProp.intValue = (int)Convert.ChangeType(gestureFlagsEnumValue, typeof(GestureFlags));
            }
            EditorGUILayout.Space();

            // Simulated delay
            var delayProp = property.FindPropertyRelative(DELAY_TIME_FIELD);

            EditorGUILayout.PropertyField(delayProp, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
            if (delayProp.floatValue < 0.0f)
            {
                delayProp.floatValue = 0.0f;
            }

            EditorGUILayout.Space();

            // Device status, ANR, and CNC via dynamic info
            GUILayoutTools.LineSeparator();
            EditorGUILayout.PropertyField(property.FindPropertyRelative(DYNAMIC_DEVICE_INFO_FIELD), WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
            GUILayoutTools.LineSeparator();

            DynamicDeviceInfo dynamicDeviceInfo = provider.GetDynamicDeviceInfo();
            DeviceStatus      status            = dynamicDeviceInfo.deviceStatus;

            using (new EditorGUI.DisabledScope(!provider.ConnectedDevice.HasValue))
            {
                bool serviceSuspended = status.GetFlagValue(DeviceStatusFlags.SensorServiceSuspended);

                // Service suspended
                using (new EditorGUI.DisabledScope(serviceSuspended))
                {
                    // Only allow selecting a reason if the service isn't suspended
                    _sensorServiceSuspendedReason = (SensorServiceSuspendedReason)EditorGUILayout.EnumPopup(
                        SENSOR_SERVICE_SUSPENSION_REASON_LABEL,
                        _sensorServiceSuspendedReason,
                        WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                }

                if (serviceSuspended)
                {
                    bool shouldResume = GUILayout.Button(RESUME_SENSOR_SERVICE_LABEL, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                    if (shouldResume)
                    {
                        provider.SimulateSensorServiceResumed();
                    }
                }
                else
                {
                    bool shouldSuspend = GUILayout.Button(SUSPEND_SENSOR_SERVICE_LABEL, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                    if (shouldSuspend)
                    {
                        provider.SimulateSensorServiceSuspended(_sensorServiceSuspendedReason);
                    }
                }
            }

            EditorGUILayout.Space();

            // Configuration results
            var sensorConfigResultProperty = property.FindPropertyRelative(SENSOR_CONFIG_RESULT_FIELD);

            EditorGUILayout.PropertyField(sensorConfigResultProperty);
            var gestureConfigResultProperty = property.FindPropertyRelative(GESTURE_CONFIG_RESULT_FIELD);

            EditorGUILayout.PropertyField(gestureConfigResultProperty);

            var sensorConfigResult  = (Result)sensorConfigResultProperty.enumValueIndex;
            var gestureConfigResult = (Result)gestureConfigResultProperty.enumValueIndex;

            if (sensorConfigResult == Result.Failure &&
                gestureConfigResult == Result.Failure)
            {
                EditorGUILayout.HelpBox(BOTH_CONFIG_WILL_FAIL_BOX, MessageType.Warning);
            }
            else if (sensorConfigResult == Result.Failure)
            {
                EditorGUILayout.HelpBox(SENSOR_CONFIG_WILL_FAIL_BOX, MessageType.Warning);
            }
            else if (gestureConfigResult == Result.Failure)
            {
                EditorGUILayout.HelpBox(GESTURE_CONFIG_WILL_FAIL_BOX, MessageType.Warning);
            }
            EditorGUILayout.Space();


            // Movement simulation
            SerializedProperty simulateMovementProperty = property.FindPropertyRelative(MOVEMENT_SIMULATION_MODE_FIELD);

            EditorGUILayout.PropertyField(simulateMovementProperty, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
            var simulatedMovementMode = (WearableDebugProvider.MovementSimulationMode)simulateMovementProperty.enumValueIndex;

            if (simulatedMovementMode == WearableDebugProvider.MovementSimulationMode.ConstantRate)
            {
                SerializedProperty rotationTypeProperty = property.FindPropertyRelative(ROTATION_TYPE_FIELD);
                EditorGUILayout.PropertyField(rotationTypeProperty, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);

                string rotationType = rotationTypeProperty.enumNames[rotationTypeProperty.enumValueIndex];
                if (rotationType == ROTATION_TYPE_EULER)
                {
                    EditorGUILayout.HelpBox(EULER_RATE_BOX, MessageType.None);
                    EditorGUILayout.PropertyField(property.FindPropertyRelative(EULER_SPIN_RATE_FIELD), WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                }
                else if (rotationType == ROTATION_TYPE_AXIS_ANGLE)
                {
                    EditorGUILayout.HelpBox(AXIS_ANGLE_BOX, MessageType.None);
                    SerializedProperty axisAngleProperty = property.FindPropertyRelative(AXIS_ANGLE_SPIN_RATE_FIELD);
                    Vector4            previousValue     = axisAngleProperty.vector4Value;
                    Vector4            newValue          = EditorGUILayout.Vector3Field(
                        AXIS_LABEL,
                        new Vector3(previousValue.x, previousValue.y, previousValue.z),
                        WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                    if (newValue.sqrMagnitude < float.Epsilon)
                    {
                        newValue.x = 1.0f;
                    }

                    newValue.w = EditorGUILayout.FloatField(RATE_LABEL, previousValue.w, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                    axisAngleProperty.vector4Value = newValue;
                }
            }
            else if (simulatedMovementMode == WearableDebugProvider.MovementSimulationMode.MobileDevice)
            {
                EditorGUILayout.HelpBox(USE_SIMULATED_MOVEMENT_MOBILE_DEVICE_HELP_BOX, MessageType.Info);
            }

            // Gesture triggers
            GUILayout.Label(GESTURES_LABEL, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
            for (int i = 0; i < WearableConstants.GESTURE_IDS.Length; i++)
            {
                GestureId gesture = WearableConstants.GESTURE_IDS[i];

                if (gesture == GestureId.None)
                {
                    continue;
                }

                using (new EditorGUI.DisabledScope(
                           !(provider.GetCachedDeviceConfiguration().GetGestureConfig(gesture).isEnabled&&
                             EditorApplication.isPlaying)))
                {
                    bool shouldTrigger = GUILayout.Button(Enum.GetName(typeof(GestureId), gesture), WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                    if (shouldTrigger)
                    {
                        provider.SimulateGesture(gesture);
                    }
                }
            }

            // Disconnect button
            EditorGUILayout.Space();
            using (new EditorGUI.DisabledScope(!provider.ConnectedDevice.HasValue))
            {
                bool shouldDisconnect = GUILayout.Button(DISCONNECT_LABEL, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
                if (shouldDisconnect)
                {
                    provider.SimulateDisconnect();
                }
            }

            // Debug Logging
            GUI.changed = false;
            var debugLoggingProp = property.FindPropertyRelative(DEBUG_LOGGING_FIELD);

            EditorGUILayout.PropertyField(debugLoggingProp, WearableEditorConstants.EMPTY_LAYOUT_OPTIONS);
            if (Application.isPlaying && GUI.changed)
            {
                var activeProvider = WearableControl.Instance.ActiveProvider;
                if (activeProvider != null)
                {
                    activeProvider.ConfigureDebugLogging();
                }
            }

            EditorGUI.EndProperty();
        }
Esempio n. 55
0
        public Device()
        {
            name = string.Empty;            
            parent = null;
			deviceStatus = DeviceStatus.Error;
        }
Esempio n. 56
0
 public static PropertyStates NewSystemStatus(DeviceStatus systemStatus)
 {
     return(new SystemStatusWrapper(systemStatus));
 }
        //[Test()]
        public void NullSerial()
        {
            DeviceStatusJSON status = new DeviceStatusJSON();
            status.bkupURL = "http://cozumotesttls.cloudapp.net:80/api/DeviceBackup";
            status.callHomeTimeoutData = null;
            status.callHomeTimeoutMode = "0";
            status.capture = "1";
            status.captureMode = "1";
            status.cmdChkInt = "1";
            status.cmdURL = "http://cozumotesttls.cloudapp.net:80/api/iCmd";
            string[] err = new string[3];
            err[0] = "asdf";
            err[1] = "wasd";
            err[2] = "qwerty";
            status.errorLog = err;
            status.reportURL = "http://cozumotesttls.cloudapp.net:80/api/DeviceStatus";
            status.requestTimeoutValue = "8000";
            status.revId = "52987";
            status.scanURL = "http://cozumotesttls.cloudapp.net:80/api/DeviceScan";
            status.seqNum = "87";
            status.startURL = "http://cozumotesttls.cloudapp.net:80/api/DeviceSetting";

            DeviceStatus operation = new DeviceStatus(TestGlobals.testServer, status);
            Test statusTest = new Test(operation);
            statusTest.setTestName("NullSerial");
            statusTest.setExpectedResult ("400");

            results.WriteLine (DateTime.Now);
            results.WriteLine ("current test: " + statusTest.ToString () + " " + statusTest.getTestName ());

            AsyncContext.Run(async () => await new HTTPSCalls().runTest(statusTest, HTTPOperation.POST));
            string statusCode = HTTPSCalls.result.Key.Property("StatusCode").Value.ToString();

            results.WriteLine("Json posted:");
            results.WriteLine (statusTest.getOperation().getJson().ToString());
            results.WriteLine ("Server: " + TestGlobals.testServer);
            results.WriteLine ("Expected result: " + statusTest.getActualResult());
            results.WriteLine ("Actual result: " + statusCode);
            results.WriteLine ("Test result: " + statusTest.result ());
            results.WriteLine ();

            Assert.AreEqual("400", statusCode);
        }
Esempio n. 58
0
 public SystemStatusWrapper(DeviceStatus item)
 {
     this.Item = item;
 }
        /// <summary>
        /// 设备状态改变回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="status"></param>
        private static void OnDeviceStatusChanged(object sender, DeviceStatus status)
        {
            T_DeviceStatusLog log = new T_DeviceStatusLog();
            log.EquipId = status.Device.Id;
            log.StatusDesc = status.StatusDesc;
            log.StatusId = status.Status.GetHashCode();
            DAL_DeviceStatus.SaveDeviceStatus(log);

            if (DeviceStatusNotifyHandler != null)
            {
                DeviceStatusNotifyHandler.Invoke(sender, status);
            }
        }
        private bool ThoroughScan()
        {
            Log(1, "Performing thorough scan.");

            // Then try if last stored connection can be opened
            if (PersistentSettings && TryConnection(_serialConnectionManagerSettings.Port, _serialConnectionManagerSettings.BaudRate) == DeviceStatus.Available)
            {
                return(true);
            }

            // Slowly walk through
            foreach (var portName in AvailableSerialPorts)
            {
                // Get baud rates collection
                var baudRateCollection = DeviceScanBaudRateSelection
                    ? SerialUtils.GetSupportedBaudRates(portName)
                    : new[] { _serialTransport.CurrentSerialSettings.BaudRate };

                //  Now loop through baud rate collection
                if (baudRateCollection.Any())
                {
                    Log(1, "Trying serial port " + portName + " using " + baudRateCollection.Length + " baud rate(s).");

                    foreach (var baudRate in baudRateCollection)
                    {
                        // Stop scanning if state was changed
                        if (ConnectionManagerMode != Mode.Scan)
                        {
                            return(false);
                        }

                        DeviceStatus status = TryConnection(portName, baudRate);
                        if (status == DeviceStatus.Available)
                        {
                            return(true);
                        }
                        if (status == DeviceStatus.IdentityMismatch)
                        {
                            break;                                          // break the loop and continue to next port.
                        }
                    }
                }

                // If port list has changed, interrupt scan and test new ports first
                if (NewPortScan())
                {
                    return(true);
                }
            }

            if (!AvailableSerialPorts.Any())
            {
                // Need to check for new ports if current ports list is empty
                if (NewPortScan())
                {
                    return(true);
                }

                // Add small delay to reduce of Quick->Thorough->Quick->Thorough scan attempts - 400ms here + 100ms in main loop = ~500ms
                Thread.Sleep(400);
            }

            return(false);
        }