Ejemplo n.º 1
0
 private void PostSocketRead(Int32 length)
 {
     try
     {
         var buffer = new Byte[length];
         var asyncOperationWithProgress = _socket.InputStream.ReadAsync(buffer.AsBuffer(), (UInt32)length, InputStreamOptions.Partial);
         asyncOperationWithProgress.Completed += (info, status) =>
         {
             switch (status)
             {
             case AsyncStatus.Completed:
             case AsyncStatus.Error:
             {
                 try
                 {
                     IBuffer results = info.GetResults();
                     OnDataReadCompletion(results.Length, DataReader.FromBuffer(results));
                 }
                 catch (Exception exception)
                 {
                     Debug.WriteLine(String.Concat("Read operation failed:  ", exception.Message));
                 }
                 break;
             }
             }
         };
     }
     catch (Exception exception1)
     {
         Debug.WriteLine(String.Concat("failed to post a read failed with error:  ", exception1.Message));
     }
 }
Ejemplo n.º 2
0
        public IBuffer AsBuffer(String MACAddress, DataMode DataMode)
        {
            Byte[] buffer = new Byte[20];

            // copiamos el entero del uid a los cuatro primeros
            Array.Copy(BitConverter.GetBytes(this.uid), buffer, 4);
            buffer[4] = (byte)(male ? 1 : 0);
            buffer[5] = this.age;
            buffer[6] = this.height;
            buffer[7] = this.weight;
            buffer[8] = (byte)DataMode;
            Array.Copy(Encoding.UTF8.GetBytes(this.alias), 0, buffer, 9, this.alias.Length);

            Byte[] crcBuffer = new Byte[19];
            Array.Copy(buffer, crcBuffer, 19);
            Int32 CRC = crc(crcBuffer);

            string macEnd  = MACAddress.Substring(MACAddress.Length - 2, 2);
            Int16  crcaddr = Int16.Parse(macEnd, System.Globalization.NumberStyles.HexNumber);

            CRC        = (CRC ^ crcaddr) & 0xFF;
            buffer[19] = (byte)CRC;

            return(buffer.AsBuffer());
        }
Ejemplo n.º 3
0
        private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var decompressed = await ApplicationData.Current.LocalFolder
                               .CreateFileAsync("decompressed.txt",
                                                CreationCollisionOption
                                                .ReplaceExisting);

            var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("compressed.zip");

            var decompressor = new Decompressor(stream.AsInputStream());

            var bytes  = new Byte[100000];
            var buffer = bytes.AsBuffer();

            var buf = await decompressor.ReadAsync(buffer, 999999, InputStreamOptions.None);

            await FileIO.WriteBufferAsync(decompressed, buf);

            await SimpleDialog(string.Format("Decompressed {0} bytes to {1}",
                                             _compressedText.Length,
                                             buf.Length));

            BigText.Text = new String(Encoding.UTF8.GetChars(buf.ToArray()));

            DecompressButton.IsEnabled = false;
        }
Ejemplo n.º 4
0
 public async void StartVibration(byte Type)
 {
     // el 0 vibra dos veces con todos los leds (color del tema)
     // el 1 vibra ¿sin parar? y deja el led central fijo (azul)
     // el 2 en adelante no parece que haga nada
     Byte[] buffer = new Byte[] { MiBand.CP_START_VIBRATION, Type };
     await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());
 }
Ejemplo n.º 5
0
        public async Task <bool> SyncConfirm(DateTime timeStamp, int rawLength)
        {
            Byte[] buffer = new Byte[9] {
                MiBand.CP_CONFIRM_SYNC,
                (byte)(-2000 + timeStamp.Year), (byte)(timeStamp.Month - 1), (byte)timeStamp.Day,
                (byte)timeStamp.Hour, (byte)timeStamp.Minute, (byte)timeStamp.Second,
                (byte)(rawLength & 0xFF), (byte)((rawLength >> 8) & 0xFF)
            };
            bool ret = await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());

            return(ret);
        }
Ejemplo n.º 6
0
        public async Task <bool> SetAlarm(Alarm Alarm)
        {
            Debug.WriteLine("[miband] escribiendo alarma");
            if (!Alarm.Valid)
            {
                return(false);
            }
            Byte[] buffer = new Byte[] { MiBand.CP_SET_ALARM, Alarm.ID, (byte)(Alarm.Enabled ? 1 : 0),
                                         (byte)(Alarm.When.Year - 2000), (byte)Alarm.When.Month, (byte)Alarm.When.Day,
                                         (byte)Alarm.When.Hour, (byte)Alarm.When.Minute, (byte)Alarm.When.Second,
                                         (byte)(Alarm.Smart ? 30 : 0), Alarm.Repeat };

            bool ret = await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());

            if (ret)
            {
                Debug.WriteLine("[miband] alarma escrita");
                SettingSet("Alarm" + (Alarm.ID + 1), Alarm.ToSetting());
            }
            return(ret);
        }
Ejemplo n.º 7
0
        /// <summary>
        ///    Calculates the frequency values for the tactile device. </summary>
        ///

        /*private void CalcFrequenciesForTactile()
         * {
         *  double   max  = double.MinValue;    // max gradient
         *  double   last = MyValues[0].Y;      // last    y-value
         *  double   cur  = MyValues[0].Y;                // current y-value
         *  double   next = 0;
         *  double[] grad = new double[MAX_POINTS - 1];     // list of all gradients
         *
         *  for (int i = 0; i < MyValues.Count - 1; i++)
         *  {
         *      //cur     = MyValues[i].Y;
         *      //grad[i] = cur - last;
         *      //max     = Math.Abs(grad[i]) > max ? Math.Abs(grad[i]) : max;
         *      //last    = cur;
         *
         *      next    = MyValues[i + 1].Y;
         *      grad[i] = next - cur;
         *      max     = Math.Abs(grad[i]) > max ? Math.Abs(grad[i]) : max;
         *      cur     = next;
         *  }
         *
         *  if (max != 0)
         *  {
         *      for (int i = 0; i < MyValues.Count() - 1; i++)
         *          // tl;dr: freq = [( m / m_max ) * freq_max] + freq_null
         *          frequencies[i] = (Int16)
         *            Math.Round(IA_TACTILE_NULFREQ + (grad[i] * IA_TACTILE_MAXFREQ / max));
         *  }
         *  else // constant graph
         *  {
         *      for (int i = 1; i < MyValues.Count(); i++)
         *          frequencies[i - 1] = IA_TACTILE_NULFREQ;
         *  }
         *
         *  return;
         * }*/

        /// <summary>
        ///    Sends the frequency data based on the graph to
        ///    the connected device and starts the simulation. </summary>
        ///
        private async void SendGraph()
        {
            Byte[] writerValues  = new Byte[NumPoints];
            Byte[] writerValues2 = new Byte[NumPoints];
            Byte[] writerMode    = { Mode };

            Byte[] myTestByte = { 0x14, 0x00, 0x24, 0x00, 0x13, 0x00, 0x23, 0x00, 0x12, 0x00, 0x22, 0x00, 0x11, 0x00, 0x21, 0x00, 0x14, 0x00, 0x24, 0x00 };

            for (int i = 0; i < myTestByte.Length; i++)
            {
                writerValues2[i] = (Byte)myTestByte.ElementAt(i);
            }

            if (myTestByte.Length < MAX_POINTS - 1) // add 'end of data' byte if needed
            {
                writerValues2[myTestByte.Length] = IA_TACTILE_EOD;
            }


            for (int i = 0; i < frequencies.Length; i++)
            {
                writerValues[i] = (Byte)frequencies.ElementAt(i);
            }

            if (frequencies.Length < MAX_POINTS - 1) // add 'end of data' byte if needed
            {
                writerValues[frequencies.Length] = IA_TACTILE_EOD;
            }


            /* status1= */
            await CurrentFreqCharacteristic.characteristic.WriteValueAsync(writerValues2.AsBuffer());

            /* status2= */ await CurrentModeCharacteristic.characteristic.WriteValueAsync(writerMode.AsBuffer());

            // if ((status1 & status2) != GattCommunicationStatus.Success)
            // TODO: Error prompt "simulation data transmission failed!"
        }
Ejemplo n.º 8
0
        private static void Compute()
        {
            if (Debugger.IsAttached)
            {
                Debug.WriteLine(ApplicationData.Current.LocalSettings.Values["Result"]);
                Debug.Write(ApplicationData.Current.LocalSettings.Values["Time"]);
            }
            else
            {
                const String initialText = "wdmpOY6OosH6ltmhqxQAkt6yWRkiokDPgZCnsYHIgvNI9eClMEl7xTkxCW6uOlLU";
                var          input       = Encoding.ASCII.GetBytes(initialText);

                var sw = Stopwatch.StartNew();

                for (var i = 0; i < 1000000; i++)
                {
                    var hasher = new Sha256();
                    hasher.AddData(input, 0, (UInt32)input.Length);
                    var hash = hasher.GetHash();
                    input = new Byte[hash.Length * 4];
                    for (var j = 0; j < hash.Length; j++)
                    {
                        var temp = BitConverter.GetBytes(hash[j]);
                        input[4 * j + 0] = temp[3];
                        input[4 * j + 1] = temp[2];
                        input[4 * j + 2] = temp[1];
                        input[4 * j + 3] = temp[0];
                    }
                    input = Encoding.ASCII.GetBytes(Convert.ToBase64String(input));
                }

                GC.Collect(2, GCCollectionMode.Forced, true);

                sw.Stop();

                ApplicationData.Current.LocalSettings.Values["Result"] = CryptographicBuffer.EncodeToHexString(input.AsBuffer());
                ApplicationData.Current.LocalSettings.Values["Time"]   = sw.ElapsedMilliseconds;

                CoreApplication.Exit();
            }
        }
Ejemplo n.º 9
0
        public async Task <bool> SyncStop()
        {
            Byte[] buffer = new Byte[] { MiBand.CP_STOP_SYNC };
            bool   ret    = await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());

            return(ret);
        }
Ejemplo n.º 10
0
        public async Task <bool> FetchData()
        {
            Byte[] buffer = new Byte[] { MiBand.CP_FETCH_DATA };
            bool   ret    = await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());

            return(ret);
        }
Ejemplo n.º 11
0
        public async Task <bool> SetWearLocation(WearLocation Location)
        {
            Byte[] buffer = new Byte[] { MiBand.CP_SET_WEAR_LOCATION, (byte)Location };
            bool   ret    = await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());

            if (ret)
            {
                SettingSet("WearLocation", (int)Location);
            }
            return(ret);
        }
Ejemplo n.º 12
0
 public async void SelfTest()
 {
     Byte[] buffer = new Byte[] { MiBand.TEST_SELFTEST, 0x02 };
     await writeToCharacteristic(MiBand.UUID_CHAR_TEST, buffer.AsBuffer());
 }
Ejemplo n.º 13
0
 public async void RemoteDisconnect()
 {
     Byte[] buffer = new Byte[] { MiBand.TEST_REMOTE_DISCONNECT };
     await writeToCharacteristic(MiBand.UUID_CHAR_TEST, buffer.AsBuffer());
 }
Ejemplo n.º 14
0
 public async void Reboot()
 {
     Byte[] buffer = new Byte[] { MiBand.CP_REBOOT };
     await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());
 }
Ejemplo n.º 15
0
        public async Task <bool> RealTimeStepsNotifications(bool Enable)
        {
            Byte[] buffer = new Byte[] { MiBand.CP_NOTIFY_REALTIMESTEPS, (byte)(Enable ? 0x01 : 0x00) };
            bool   ret    = await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());

            return(ret);
        }
Ejemplo n.º 16
0
        public async Task <bool> SetGoal(int Steps)
        {
            Debug.WriteLine("[miband] escribiendo objetivo");
            // ToDo el segundo no se que es, pero puede variar
            Byte[] buffer = new Byte[] { MiBand.CP_SET_GOAL, 0x00, (byte)(Steps & 0xFF), (byte)((Steps >> 8) & 0xFF) };
            bool   ret    = await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());

            if (ret)
            {
                SettingSet("DailyGoal", Steps);
                Debug.WriteLine("[miband] objetivo escrito");
            }
            return(ret);
        }
Ejemplo n.º 17
0
        public async Task <bool> SetCurrentSteps(int Steps)
        {
            Byte[] buffer = new Byte[] { MiBand.CP_SET_REALTIMESTEPS, (byte)(Steps & 0xFF), (byte)((Steps >> 8) & 0xFF) };
            bool   ret    = await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());

            if (ret)
            {
                SettingSet("CurrentSteps", Steps);
            }
            return(ret);
        }
Ejemplo n.º 18
0
        public async Task <bool> SetColorTheme(ColorTheme Theme, bool Advertise)
        {
            Debug.WriteLine("[miband] cambiando esquema de color");
            Byte[] buffer = new Byte[] { MiBand.CP_SET_THEME, Theme.R, Theme.G, Theme.B, (byte)(Advertise ? 0x01 : 0x00) };
            bool   ret    = await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());

            if (ret)
            {
                SettingSet("ColorTheme", Theme.ToInt32());
                Debug.WriteLine("[miband] esquema de color cambiado");
            }
            else
            {
                Debug.WriteLine("[miband] error al cambiar esquema de color");
            }
            return(ret);
        }
Ejemplo n.º 19
0
 public async void StopVibration()
 {
     Byte[] buffer = new Byte[] { MiBand.CP_STOP_VIBRATION };
     await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());
 }
Ejemplo n.º 20
0
        private async Task <bool> SensorDataNotifications(bool Enable)
        {
            Byte[] buffer = new Byte[] { MiBand.CP_NOTIFY_SENSORDATA, (byte)(Enable ? 0x01 : 0x00) };
            bool   ret    = await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());

            return(ret);
        }
Ejemplo n.º 21
0
 public async Task <bool> SetDateTime(DateTime Date)
 {
     Debug.WriteLine("[miband] escribiendo fecha");
     Byte[] buffer = new Byte[] { (byte)((Date.Year - 2000) & 0xFF), (byte)(Date.Month - 1), (byte)Date.Day, (byte)Date.Hour, (byte)Date.Minute, (byte)Date.Second };
     return(await writeToCharacteristic(MiBand.UUID_CHAR_DATE_TIME, buffer.AsBuffer()));
 }
Ejemplo n.º 22
0
        // imagino que esto es para que sea visible o no a traves de bluetooth para otros
        public async Task <bool> EnableConnectedBroadcast(bool Enable)
        {
            Byte[] buffer = new Byte[] { (byte)(Enable ? 0x01 : 0x00) };
            bool   ret    = await writeToCharacteristic(MiBand.UUID_CHAR_DEVICE_NAME, buffer.AsBuffer());

            return(ret);
        }
Ejemplo n.º 23
0
 public async void FactoryReset()
 {
     Byte[] buffer = new Byte[] { MiBand.CP_FACTORY_RESET };
     await writeToCharacteristic(MiBand.UUID_CHAR_CONTROL_POINT, buffer.AsBuffer());
 }
Ejemplo n.º 24
0
        private void Setup(string ip)
        {
            string xml = "";

            if (this.cascadeClassifier == null)
            {
                Task.Run(async() => {
                    StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.DocumentsLibrary);
                    var sampleFile = (StorageFile)await picturesLibrary.TryGetItemAsync(@"cascades\haarcascade_mcs_upperbody.xml");
                    if (sampleFile != null)
                    {
                        using (var inputStream = await sampleFile.OpenReadAsync()) {
                            Byte[] bytes = new Byte[inputStream.Size];
                            var buffer   = await inputStream.ReadAsync(bytes.AsBuffer(), (uint)inputStream.Size, Windows.Storage.Streams.InputStreamOptions.None);
                            bytes        = buffer.ToArray();
                            xml          = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                        }
                    }
                }).Wait();
                this.cascadeClassifier = new HaarRuntimeComponent.Class1(xml);
            }

            if (this.requestHandlers == null)
            {
                this.requestHandlers = new Dictionary <string, Func <byte[], bool> >()
                {
                    { "/kinect/request/facetrack/bounds", HandleRequestFaceTrackBounds }
                };
            }

            if (this.client == null)
            {
                this.client = new MqttClient(ip);
                this.client.ProtocolVersion         = MqttProtocolVersion.Version_3_1;
                this.client.MqttMsgPublishReceived += this.onMqttReceive;
                this.client.Subscribe(this.requestHandlers.Keys.ToArray(), Enumerable.Repeat(MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, this.requestHandlers.Count).ToArray());
                this.client.Connect(Guid.NewGuid().ToString());
            }

            if (this.frames == null)
            {
                this.frames = new Dictionary <MediaFrameSourceKind, MediaFrameReference>()
                {
                    { MediaFrameSourceKind.Color, null },
                    { MediaFrameSourceKind.Depth, null }
                }
            }
            ;

            if (this.mediaCapture == null)
            {
                // select device with both color and depth streams
                var cameras  = Task.Run(async() => { return(await MediaFrameSourceGroup.FindAllAsync()); });
                var eligible = cameras.Result.Select(c => new {
                    Group       = c,
                    SourceInfos = new MediaFrameSourceInfo[] {
                        c.SourceInfos.FirstOrDefault(info => info.SourceKind == MediaFrameSourceKind.Color),
                        c.SourceInfos.FirstOrDefault(info => info.SourceKind == MediaFrameSourceKind.Depth)
                    }
                }).Where(c => c.SourceInfos[0] != null && c.SourceInfos[1] != null).ToList();
                if (eligible.Count == 0)
                {
                    return;
                }
                var selected = eligible[0];

                // open device
                this.mediaCapture = new MediaCapture();
                Task.Run(async() => {
                    await this.mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings {
                        SourceGroup          = selected.Group,
                        SharingMode          = MediaCaptureSharingMode.SharedReadOnly,
                        StreamingCaptureMode = StreamingCaptureMode.Video,
                        MemoryPreference     = MediaCaptureMemoryPreference.Cpu
                    });
                }).Wait();

                // set stream callbacks
                for (int i = 0; i < selected.SourceInfos.Length; ++i)
                {
                    MediaFrameSourceInfo info        = selected.SourceInfos[i];
                    MediaFrameSource     frameSource = null;
                    if (this.mediaCapture.FrameSources.TryGetValue(info.Id, out frameSource))
                    {
                        var frameReader = Task.Run(async() => { return(await this.mediaCapture.CreateFrameReaderAsync(frameSource)); });
                        frameReader.Result.FrameArrived += FrameReader_FrameArrived;
                        var status = Task.Run(async() => { return(await frameReader.Result.StartAsync()); });
                        if (status.Result != MediaFrameReaderStartStatus.Success)
                        {
                            return;
                        }
                    }
                }
            }

            // start clock
            this.appClock.Start();
        }