public async System.Threading.Tasks.Task InsertIntoSQLiteAsync(PhoneSensorActivity obj)
        {
            try
            {
                await obj.GPSLocationAsync();

                _phoneData.mCreatedAt        = DateTimeOffset.Now;
                _phoneData.accelerometer_x   = (float)obj.XAccelerationValue;
                _phoneData.accelerometer_y   = (float)obj.YAccelerationValue;
                _phoneData.accelerometer_z   = (float)obj.YAccelerationValue;
                _phoneData.accelerometer_acc = (float)obj.AccelerationAverage;
                _phoneData.magneticfield_x   = (float)obj.XMagnetometerValue;
                _phoneData.magneticfield_y   = (float)obj.YMagnetometerValue;
                _phoneData.magneticfield_z   = (float)obj.ZMagnetometerValue;
                _phoneData.magneticfield_acc = (float)obj.MagnetometerAverage;
                _phoneData.gyroscope_x       = (float)obj.XGyroscopeValue;
                _phoneData.gyroscope_y       = (float)obj.YGyroscopeValue;
                _phoneData.gyroscope_z       = (float)obj.ZGyroscopeValue;
                _phoneData.gyroscope_acc     = (float)obj.GyroscopeAverage;
                _phoneData.gpsTimeStam       = (long)obj.GPSTime;
                _phoneData.latitude          = (float)obj.Latitude;
                _phoneData.longitude         = (float)obj.Longitude;
                _phoneData.altitude          = (float)obj.Altitude;
                _phoneData.GPSAccuracy       = (float)obj.GPSAccuracy;
                _phoneData.TimeStamp         = DateTime.Now.ToString(Constants.DATETIMEFORMAT);
                _phoneData.setuser_id(MainPage.mac);
                await FIUAssist.DatabaseManager.SensorDataService.Instance.CurrentClient.GetSyncTable("SmartPhoneSensors").InsertAsync(JObject.FromObject(_phoneData));
            }
            catch (Exception ex)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
            }
        }
Exemplo n.º 2
0
 private void CollectionService()
 {
     Task.Run(() =>
     {
         try
         {
             if (!isRunning)
             {
                 var sen = new SensorCollectionManager();
                 //sen.PhoneSensorOperationsAsync(_cts.Token);
             }
         }
         catch (Exception ex)
         {
             ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
         }
         finally
         {
             if (_cts.IsCancellationRequested)
             {
                 var message = new CancelledMessage();
                 Device.BeginInvokeOnMainThread(
                     () => MessagingCenter.Send(message, "CancelledMessage")
                     );
             }
         }
     }, _cts.Token);
 }
        private async void WoundSensorDisconnectedAsync(object sender, DeviceErrorEventArgs e)
        {
            try
            {
                await adapter.StopScanningForDevicesAsync();

                await adapter.DisconnectDeviceAsync(device);

                char4.ValueUpdated -= CharacteristicsChanged;

                //if (SensorDetailsPage.UpdateDeviceName != null)
                //{
                //    SensorDetailsPage.UpdateDeviceName("No Device");
                //}

                //if (SensorDetailsPage.UpdateConnectionStatus != null)
                //{
                //    SensorDetailsPage.UpdateConnectionStatus("Disconnected");
                //}

                var message = new NotifyMessage {
                    Message = "Disconnected from device!"
                };

                Device.BeginInvokeOnMainThread(
                    () => MessagingCenter.Send(message, "NotifyMessage")
                    );

                StaticObjects.Connected = false;

                //if (WoundPage.ConnectionDelete != null)
                //{
                //    WoundPage.ConnectionDelete(Connected);
                //}

                while (!StaticObjects.Connected)
                {
                    try
                    {
                        await adapter.StartScanningForDevicesAsync();
                    }
                    catch (Exception ex)
                    {
                        var _message = new NotifyMessage {
                            Message = "Can't find device"
                        };

                        Device.BeginInvokeOnMainThread(
                            () => MessagingCenter.Send(_message, "NotifyMessage")
                            );
                    }
                }
                //Connected = true;
            }
            catch (Exception ex)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
            }
            //await adapter.DisconnectDeviceAsync(device);
        }
        private void OnAndroidEnvironmentUnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs unhandledExceptionEventArgs)
        {
            var newExc = new System.Exception("OnAndroidEnvironmentUnhandledExceptionRaiser", unhandledExceptionEventArgs.Exception);

            ExceptionErrorLogger.writeFileOnInternalStorage(newExc.ToString());

            Console.WriteLine(newExc);
        }
        private void OnAndroidEnvironmentUnhandledThreadExceptionRaiser(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
        {
            var newExc = new System.Exception("TaskSchedulerOnUnobservedTaskException", unobservedTaskExceptionEventArgs.Exception);

            ExceptionErrorLogger.writeFileOnInternalStorage(newExc.ToString());

            Console.WriteLine(newExc);
        }
        public async Task DBOperationsAsync()
        {
            //while (StaticObjects.jobCancelled == false)
            //{
            try
            {
                //token.ThrowIfCancellationRequested();

                var message = new CollectionMessage
                {
                    Message = "Pushing Data..."
                };

                Device.BeginInvokeOnMainThread(() =>
                {
                    MessagingCenter.Send(message, "CollectionMessage");
                });

                //INSERTS INTO REMOTE LOCATION
                await SensorDataService.Instance.CurrentClient.SyncContext.PushAsync();

                //await SensorDataService.Instance.phoneSensorTable.PurgeAsync(true);
                //await SensorDataService.Instance.woundSensorTable.PurgeAsync(true);
                //await SensorDataService.Instance.watchSensorTable.PurgeAsync(true);

                //if (StaticObjects.path.Length > 8e6)
                //{
                //    await SensorDataService.Instance.phoneSensorTable.PurgeAsync(true);
                //    await SensorDataService.Instance.woundSensorTable.PurgeAsync(true);
                //    await SensorDataService.Instance.watchSensorTable.PurgeAsync(true);
                //}

                var _message = new CollectionMessage
                {
                    Message = "Push Complete. Waiting..."
                };
                Device.BeginInvokeOnMainThread(
                    () => MessagingCenter.Send(_message, "CollectionMessage")
                    );
                //Thread.Sleep(30000);
            }

            catch (Exception ex)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());

                var _message = new CollectionMessage {
                    Message = "Error Pushing"
                };
                Device.BeginInvokeOnMainThread(() => MessagingCenter.Send(_message, "CollectionMessage"));

                var message = new NotifyMessage {
                    Message = "Error pushing to cloud. The job will restart soon (Maximum 15 minutes)"
                };
                Device.BeginInvokeOnMainThread(() => MessagingCenter.Send(_message, "NotifyMessage"));
            }
            //}
        }
 static async void SyncData(WoundSensors data)
 {
     try
     {
         await FIUAssist.DatabaseManager.SensorDataService.Instance.CurrentClient.GetSyncTable("WoundSensors").InsertAsync(JObject.FromObject(data));
     }
     catch (Exception ex)
     {
         ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
     }
 }
Exemplo n.º 8
0
        public void StoreService()
        {
            Task.Run(() =>
            {
                try
                {
                    //INVOKE THE SHARED CODE
                    if (!isRunning)
                    {
                        var net = new NetworkCommunicationManager();
                        //net.DBOperations(_cts.Token);
                    }
                }
                catch (Exception ex)
                {
                    ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());

                    var message = new CollectionMessage
                    {
                        Message = "Connection Error"
                    };
                    Device.BeginInvokeOnMainThread(
                        () => MessagingCenter.Send(message, "CollectionMessage")
                        );
                }
                finally
                {
                    if (_cts.IsCancellationRequested)
                    {
                        var message = new CancelledMessage();
                        Device.BeginInvokeOnMainThread(
                            () => MessagingCenter.Send(message, "CancelledMessage")
                            );
                    }
                    else
                    {
                        StaticObjects.IsCollecting = false;
                        //var _message = new StopLongRunningTaskMessage();
                        //MessagingCenter.Send(_message, "StopLongRunningTaskMessage");

                        var message = new CollectionMessage
                        {
                            Message = "Database push resuming..."
                        };
                        Device.BeginInvokeOnMainThread(
                            () => MessagingCenter.Send(message, "CollectionMessage")
                            );
                    }
                }
            }, _cts.Token);
        }
        public override bool OnStartJob(JobParameters @params)
        {
            try
            {
                var w = new BluetoothWatchConnection();
                WatchCollectionThread = new Thread(w.ConnectToWatchAsync);
                WatchCollectionThread.Start();
            }
            catch (Exception ex)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
            }

            return(true);
        }
Exemplo n.º 10
0
        private async void BtnConnectKnown_Clicked(object sender, EventArgs e)
        {
            try
            {
                await adapter.ConnectToKnownDeviceAsync(het);

                string notif = ("You've connected to " + device.Name);
                await DisplayAlert("Notice", notif, "OK");
            }
            catch (DeviceConnectionException ex)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                await DisplayAlert("Notice", ex.Message.ToString(), "OK");
            }
        }
        public override bool OnStartJob(JobParameters @params)
        {
            Task.Run(async() =>
            {
                try
                {
                    //var w = new SensorCollectionManager();
                    //PhoneCollectionThread = new Thread(w.PhoneSensorOperationsAsync);
                    //PhoneCollectionThread.Start();
                    s = new Stopwatch();
                    s.Start();
                    PhoneSensorActivity objectValue;
                    while (s.Elapsed < TimeSpan.FromSeconds(900))
                    {
                        objectValue = PhoneSensorActivity.Instance.GetSensorActivityPhone();

                        await InsertIntoSQLiteAsync(objectValue);

                        //if (MainPage.SetPhoneData != null)
                        //{
                        //    MainPage.SetPhoneData(objectValue.GetDoubleArray());
                        //}
                        Console.WriteLine("DATA STORED LOCAL");
                        Thread.Sleep(1000);
                        //}
                        //if (PowerBILiveReport.PowerBILive != null)
                        //{
                        //var phone = string.Format(Constants.phoneData, DateTime.Now.ToString(Constants.DATETIMEFORMAT), _phoneData.accelerometer_x.ToString(), _phoneData.accelerometer_y.ToString(), _phoneData.accelerometer_z.ToString());
                        //PowerBILiveReport.PowerBILive("", PowerBILiveReport.DATATYPE.PHONE);
                        //}
                    }
                    s.Stop();
                    s.Reset();
                    JobFinished(@params, false);
                }
                catch (Exception ex)
                {
                    ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                }
            });



            return(true);
        }
        public MainPage()
        {
            InitializeComponent();

            try
            {
                if (System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces().Length > 0)
                {
                    //MAC ADDRESS/USER ID FOR PERSON
                    mac = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].GetPhysicalAddress().ToString();
                }
            }
            catch
            {
            }


            PowerBILiveReport powerBI = new PowerBILiveReport();

            SetPhoneData     = UpdatePhoneData;
            SetDeviceName    = SetName;
            StepAndHeartRate = UpdateStepCountAndHeartRate;
            DeleteGraphs     = ClearGraphs;

            ExceptionErrorLogger.CopyDatabase();

            AccelerationValues = new ObservableCollection <AccelerationViewModel>();
            MagnetometerValues = new ObservableCollection <MagnetometerViewModel>();
            GyroscopeValues    = new ObservableCollection <GyroscopeViewModel>();

            this.BindingContext = this;

            phoneSensorsThread = new Thread(Run);
            phoneSensorsThread.Start();

            DeviceName     = "No Device";
            Status         = "Disconnected";
            CollectionStat = "....";

            WireUpCollectionMessages();

            HandleReceivedMessages();

            //timer = new PollingTimer(TimeSpan.FromSeconds(30), InitiateCollection);
        }
        public void resetConnection()
        {
            //await DisplayAlert("Notice", "Disconnected from Ticwatch", "OK");
            try
            {
                if (SmartWatchPage.ClearGraphs != null)
                {
                    SmartWatchPage.ClearGraphs();
                }
            }
            catch (Exception ex)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
            }
            try
            {
                if (inputStream != null)
                {
                    inputStream.Close();
                    inputStream = null;
                }
            }
            catch (IOException ex)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
            }

            try
            {
                if (serverClientSocket != null)
                {
                    serverClientSocket.Close();
                    serverClientSocket = null;
                }
            }
            catch (IOException ex)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
            }

            ConnectToWatchAsync();
        }
        public async Task <JObject> ExecuteTableOperationAsync(IMobileServiceTableOperation operation)
        {
            try
            {
                Debug.Write(string.Format("Execute operation: {0}    {1}", operation.Kind, operation.Item));
                _log = string.Format("Execute operation: {0}    {1}", operation.Kind.ToString(), operation.Item.ToString());
                if (InsertionLog.insertLog != null)
                {
                    InsertionLog.insertLog(_log);
                }
                return(await operation.ExecuteAsync());
            }
            catch (MobileServiceConflictException ex)
            {
                await operation.Table.UpdateAsync(operation.Item);

                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                return(new JObject());
            }
        }
        public async Task Initialize()
        {
            try
            {
                switch (Xamarin.Forms.Device.RuntimePlatform)
                {
                case Xamarin.Forms.Device.iOS:
                    path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", "FIUAssist.db");
                    break;

                case Xamarin.Forms.Device.Android:
                    path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "FIUAssistDB.db ");
                    //CopyDatabase(path);
                    break;

                default:
                    throw new NotImplementedException("Platform not supported");
                }

                if (!File.Exists(path))
                {
                    File.Create(path).Dispose();
                }

                store = new MobileServiceSQLiteStore(path);
                store.DefineTable <SmartPhoneSensors>();
                store.DefineTable <WoundSensors>();
                store.DefineTable <SmartWatchSensors>();

                this.phoneSensorTable = this.CurrentClient.GetSyncTable <SmartPhoneSensors>();
                this.woundSensorTable = this.CurrentClient.GetSyncTable <WoundSensors>();
                this.watchSensorTable = this.CurrentClient.GetSyncTable <SmartWatchSensors>();

                await client.SyncContext.InitializeAsync(store, new SyncHandler());
            }
            catch (Exception ex)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
            }
        }
        private void CheckJobIntegrity(JobInfo jobInfo, JobInfo jobInfoWatch, JobInfo jobInfoPhone)
        {
            var result = jobScheduler.Schedule(jobInfo);

            if (result != JobScheduler.ResultSuccess)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage("THE JOB HAS FAILED DUE TO NO WIFI CONNECTION. NOTHING WAS COLLECTED AND NOTHING WAS PUSHED AFTER THIS STATEMENT");

                var _message = new NotifyMessage {
                    Message = "No internet connection. Please restart the app under a stable connection."
                };
                Device.BeginInvokeOnMainThread(() => { MessagingCenter.Send(_message, "NotifyMessage"); });
            }

            var result_watch = jobScheduler.Schedule(jobInfoWatch);

            if (result_watch != JobScheduler.ResultSuccess)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage("THE WATCH JOB DID NOT START. RESTART APP.");

                var _message = new ErrorMessage {
                    Message = "Job Failure"
                };
                Device.BeginInvokeOnMainThread(() => { MessagingCenter.Send(_message, "ErrorMessage"); });
            }

            var result_phone = jobScheduler.Schedule(jobInfoPhone);

            if (result_phone != JobScheduler.ResultSuccess)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage("THE PHONE JOB DID NOT START. RESTART APP.");

                var _message = new ErrorMessage {
                    Message = "Job Failure"
                };
                Device.BeginInvokeOnMainThread(() => { MessagingCenter.Send(_message, "ErrorMessage"); });
            }
        }
        public async void ConnectToWatchAsync()
        {
            isClosed   = false;
            system_ids = new Guid[] { watch_uuid };
            foreach (IDevice dev in adapter.GetSystemConnectedOrPairedDevices(system_ids))
            {
                if (dev.Name == "Ticwatch E C36B")
                {
                    try
                    {
                        // set up the server, start and stop listening for new connections
                        serverSocket = null;
                        // start listening for a new connection
                        if (!isClosed)
                        {
                            try
                            {
                                bluetooth = BluetoothAdapter.DefaultAdapter;
                                if (bluetooth == null)
                                {
                                    var message = new NotifyMessage {
                                        Message = "Bluetooth turned off or not available"
                                    };
                                    Device.BeginInvokeOnMainThread(() => MessagingCenter.Send(message, "NotifyMessage"));
                                }

                                // MY_UUID is the app's UUID string, also used by the client code
                                Console.WriteLine("Starting the server listener");
                                serverSocket = bluetooth.ListenUsingRfcommWithServiceRecord(ServiceName, UUID.FromString(Uuid));

                                // keep trying to find a client
                                while (serverClientSocket == null)
                                {
                                    serverClientSocket = await serverSocket.AcceptAsync();
                                }
                            }
                            catch (IOException ex)
                            {
                                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                                //await DisplayAlert("Notice", "Cannot connect to device. Please try again.", "OK");
                                return;
                            }
                            // If a connection was accepted
                            if (serverClientSocket != null)
                            {
                                var device = serverClientSocket.RemoteDevice;

                                bluetooth = null;
                                serverSocket.Close();
                                // Do work to manage the connection (in a separate thread)
                                try
                                {
                                    //await DisplayAlert("Notice", notif_w, "OK");
                                    isClosed = true;
                                    StartListeningAsync(serverClientSocket, cancellationToken);
                                }
                                catch (Exception ex)
                                {
                                    ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                                    //await DisplayAlert("Notice", "Error connecting to Ticwatch. Please try again.", "OK");
                                }
                            }
                        }
                        else
                        {
                            if (serverClientSocket != null)
                            {
                                serverSocket = bluetooth.ListenUsingRfcommWithServiceRecord(ServiceName, UUID.FromString(Uuid));

                                var device = serverClientSocket.RemoteDevice;

                                bluetooth = null;
                                serverSocket.Close();
                                // Do work to manage the connection (in a separate thread)
                                try
                                {
                                    //await DisplayAlert("Notice", notif_w, "OK");

                                    StartListeningAsync(serverClientSocket, cancellationToken);
                                }
                                catch (Exception ex)
                                {
                                    ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                                    //await DisplayAlert("Notice", "Error connecting to Ticwatch. Please try again.", "OK");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                    }
                }
            }
        }
Exemplo n.º 18
0
        //private void BtnStatus_Clicked(object sender, EventArgs e)
        //{
        //    var state = ble.State;
        //    this.DisplayAlert("Notice", state.ToString(), "OK !");
        //    if (state == BluetoothState.Off)
        //    {
        //        btnStatus.TextColor = Color.Red;
        //    }
        //    else
        //    {
        //        btnStatus.TextColor = Color.Green;
        //    }
        //}


        #region HETWound Connection
        private async void BtnConnect_Clicked(object sender, EventArgs e)
        {
            if (device != null)
            {
                switch (device.Name)
                {
                case "HET Wound v2.1-001":
                    //LOGIC
                    await adapter.StopScanningForDevicesAsync();

                    string notif = ("You've connected to " + device.Name);
                    await adapter.ConnectToDeviceAsync(device);

                    Service = await device.GetServiceAsync(het);

                    var char4 = await Service.GetCharacteristicAsync(char4_uuid);

                    if (MainPage.SetDeviceName != null)
                    {
                        MainPage.SetDeviceName(device.Name, "Connected");
                    }

                    char1 = await Service.GetCharacteristicAsync(char1_uuid);

                    try
                    {
                        await char1.WriteAsync(cmd_string);
                    }
                    catch
                    {
                    }

                    char4.ValueUpdated += CharacteristicsChanged;

                    btnConnect.TextColor = Color.Green;

                    await char4.StartUpdatesAsync();

                    await DisplayAlert("Notice", notif, "OK");

                    break;

                case "Ticwatch E C36B":
                    //LOGIC
                    await adapter.StopScanningForDevicesAsync();

                    string notif_w = ("You've connected to " + device.Name);
                    //await adapter.ConnectToDeviceAsync(device);
                    try
                    {
                        // set up the server, start and stop listening for new connections
                        BluetoothServerSocket serverSocket = null;
                        // start listening for a new connection
                        if (!isClosed)
                        {
                            try
                            {
                                bluetooth = BluetoothAdapter.DefaultAdapter;
                                if (bluetooth == null)
                                {
                                    Console.WriteLine("NO ADAPTER");
                                }
                                // MY_UUID is the app's UUID string, also used by the client code
                                Console.WriteLine("Starting the server listener");
                                serverSocket = bluetooth.ListenUsingRfcommWithServiceRecord(ServiceName, UUID.FromString(Uuid));

                                // keep trying to find a client

                                serverClientSocket = await serverSocket.AcceptAsync();
                            }
                            catch (IOException ex)
                            {
                                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                                await DisplayAlert("Notice", "Cannot connect to device. Please try again.", "OK");

                                return;
                            }
                            // If a connection was accepted
                            if (serverClientSocket != null)
                            {
                                var device = serverClientSocket.RemoteDevice;

                                bluetooth = null;
                                serverSocket.Close();
                                // Do work to manage the connection (in a separate thread)
                                try
                                {
                                    await DisplayAlert("Notice", notif_w, "OK");

                                    btnConnect.TextColor = Color.Green;
                                    await StartListening(serverClientSocket);
                                }
                                catch (Exception ex)
                                {
                                    ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                                    await DisplayAlert("Notice", "Error connecting to Ticwatch. Please try again.", "OK");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                    }
                    break;

                default:
                    await DisplayAlert("Notice", "Device not supported !", "OK");

                    btnConnect.TextColor = Color.Red;
                    break;
                }
            }
            else
            {
                await DisplayAlert("Notice", "No Device Selected!", "OK");

                btnConnect.TextColor = Color.Red;
            }



            //try
            //{
            //    if (Xamarin.Forms.Device.RuntimePlatform == Xamarin.Forms.Device.Android)
            //    {
            //        await adapter.StopScanningForDevicesAsync();
            //    }
            //    if (device != null && device.Name == "HET Wound v2.1-001")
            //    {
            //        string notif = ("You've connected to " + device.Name);
            //        await adapter.ConnectToDeviceAsync(device);

            //        Service = await device.GetServiceAsync(het);

            //        var char4 = await Service.GetCharacteristicAsync(char4_uuid);
            //        if (MainPage.SetDeviceName != null)
            //        {
            //            MainPage.SetDeviceName(device.Name, "Connected");
            //        }

            //        char1 = await Service.GetCharacteristicAsync(char1_uuid);

            //        try
            //        {
            //            await char1.WriteAsync(cmd_string);
            //        }
            //        catch
            //        {

            //        }

            //        char4.ValueUpdated += CharacteristicsChanged;

            //        btnConnect.TextColor = Color.Green;

            //        await char4.StartUpdatesAsync();

            //        await DisplayAlert("Notice", notif, "OK");

            //    }
            //    else
            //    {
            //        await DisplayAlert("Notice", "Device not supported !", "OK");
            //        btnConnect.TextColor = Color.Red;
            //    }
            //}
            //catch(DeviceConnectionException ex)
            //{
            //   await  DisplayAlert("Notice", ex.Message.ToString(), "OK");
            //    btnConnect.TextColor = Color.Red;
            //}
        }
Exemplo n.º 19
0
        private async Task StartListening(BluetoothSocket socket)
        {
            smartWatchSensors = new SmartWatchSensors();
            // Get the BluetoothSocket input and output streams
            try
            {
                inputStream = socket.InputStream;
                //ConnectionStates.watchConnected = true;
            }
            catch (IOException ex)
            {
                ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                resetConnection();
            }

            const int BUFFER_SIZE = 1024;

            byte[] buffer = new byte[BUFFER_SIZE];
            int    bytes  = 0;
            int    b      = BUFFER_SIZE;

            // Keep listening to the InputStream while connected
            while (true)
            {
                try
                {
                    // Read from the input stream
                    bool available = inputStream.IsDataAvailable();

                    if (available)
                    {
                        if (serverClientSocket == null || !serverClientSocket.IsConnected)
                        {
                            resetConnection();
                            break;
                        }
                        int i = 0;
                        while (serverClientSocket != null)
                        {
                            var size = await inputStream.ReadAsync(buffer, 0, buffer.Length);

                            i = 0;
                            if (size > 0)
                            {
                                while (size > i)
                                {
                                    if (buffer[i] == '$')
                                    {
                                        if (buffer[i + 1] == '~' && buffer[i + 2] == '!')
                                        {
                                            resetConnection();
                                            return;
                                        }
                                        int length     = buffer[i + 1] << 24 | (buffer[i + 2] & 0xFF) << 16 | (buffer[i + 3] & 0xFF) << 8 | (buffer[i + 4] & 0xFF);
                                        var stringRead = Encoding.UTF8.GetString(buffer, i + 5, i + length + 5);
                                        var startIndex = stringRead.IndexOf("{");
                                        var endIndex   = stringRead.IndexOf("}") + 1;
                                        try
                                        {
                                            var response   = stringRead.Remove(endIndex, stringRead.Length - endIndex).Remove(0, startIndex);
                                            var jsonObject = JsonConvert.DeserializeObject <SensorDataJson>(response);
                                            var watchData  = SensorActivityWatch.GetSensorActivityWatchFromJson(jsonObject);
                                            if (SmartWatchPage.SetWatchData != null)
                                            {
                                                SmartWatchPage.SetWatchData(SensorActivityWatch.GetDoubleArray(jsonObject));
                                            }
                                            if (MainPage.StepAndHeartRate != null)
                                            {
                                                MainPage.StepAndHeartRate(SensorActivityWatch.GetDoubleArray(jsonObject));
                                            }

                                            smartWatchSensors = ConvertJsonToSmartWatchSensor(jsonObject, smartWatchSensors);
                                            await FIUAssist.DatabaseManager.SensorDataService.Instance.CurrentClient.GetSyncTable("SmartWatchSensors").InsertAsync(JObject.FromObject(smartWatchSensors));

                                            //var dataWatch = string.Format(Constants.smartwatchdata, DateTime.Now.ToString(Constants.DATETIMEFORMAT), watchData.XAccelerationValue.ToString(), watchData.YAccelerationValue.ToString(), watchData.ZAccelerationValue.ToString(), watchData.HeartRateValue.ToString(), watchData.StepCountValue.ToString());
                                            //if (PowerBILive != null)
                                            //{
                                            //    PowerBILive(dataWatch, NetworkCommunicationManager.DATATYPE.WATCH);
                                            //}
                                        }
                                        catch (Exception ex)
                                        {
                                            ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                                            resetConnection();
                                        }
                                        i += length + 4;
                                    }
                                    i += size;
                                }
                            }
                        }
                    }
                }
                catch (IOException ex)
                {
                    ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                    resetConnection();
                    return;
                }
            }
        }
Exemplo n.º 20
0
        public override bool OnStartJob(JobParameters jobParameters)
        {
            Task.Run(async() =>
            {
                try
                {
                    //token.ThrowIfCancellationRequested();

                    var message = new CollectionMessage
                    {
                        Message = "Pushing Data..."
                    };

                    Device.BeginInvokeOnMainThread(() =>
                    {
                        MessagingCenter.Send(message, "CollectionMessage");
                    });

                    //INSERTS INTO REMOTE LOCATION
                    await SensorDataService.Instance.CurrentClient.SyncContext.PushAsync();
                    //await SensorDataService.Instance.phoneSensorTable.PurgeAsync(true);
                    //await SensorDataService.Instance.woundSensorTable.PurgeAsync(true);
                    //await SensorDataService.Instance.watchSensorTable.PurgeAsync(true);

                    //if (StaticObjects.path.Length > 8e6)
                    //{
                    //    await SensorDataService.Instance.phoneSensorTable.PurgeAsync(true);
                    //    await SensorDataService.Instance.woundSensorTable.PurgeAsync(true);
                    //    await SensorDataService.Instance.watchSensorTable.PurgeAsync(true);
                    //}

                    var _message = new CollectionMessage
                    {
                        Message = "Push Complete. Waiting..."
                    };
                    Device.BeginInvokeOnMainThread(
                        () => MessagingCenter.Send(_message, "CollectionMessage")
                        );
                    //Thread.Sleep(30000);
                }

                catch (Exception ex)
                {
                    ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());

                    var _message = new CollectionMessage {
                        Message = "Error Pushing"
                    };
                    Device.BeginInvokeOnMainThread(() => MessagingCenter.Send(_message, "CollectionMessage"));

                    var message = new NotifyMessage {
                        Message = "Error pushing to cloud. The job will restart soon (Maximum 15 minutes)"
                    };
                    Device.BeginInvokeOnMainThread(() => MessagingCenter.Send(_message, "NotifyMessage"));
                }
            });


            //Task.Run(async () =>
            //{

            //    try
            //    {
            //        if (!isRunning)
            //        {
            //            var sen = new SensorCollectionManager();
            //            await sen.PhoneSensorOperations(_cts.Token);
            //        }

            //    }
            //    catch (Exception ex)
            //    {
            //        ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
            //    }
            //    finally
            //    {
            //        if (_cts.IsCancellationRequested)
            //        {
            //            var message = new CancelledMessage();
            //            Device.BeginInvokeOnMainThread(
            //                () => MessagingCenter.Send(message, "CancelledMessage")
            //            );
            //        }
            //    }

            //    JobFinished(jobParameters, false);
            //});

            return(true);
        }
        public void ScaleReadyData()
        {
            while (StaticObjects.jobCancelled == false)
            {
                if (data_packets.Count > 0)
                {
                    var _data = data_packets.Dequeue();

                    try
                    {
                        //Stopwatch watch = new Stopwatch();
                        //watch.Start();
                        if (_data != null)
                        {
                            if (wound == null)
                            {
                                wound = new WoundSensors();
                            }

                            int channel = _data[0];

                            float bias = (float)Math.Round((_data[1] - 1) * -0.05, 1);

                            float voltage = ((_data[2] & 0xff) << 8) | (_data[3] & 0xff);

                            float temp           = ((_data[6] & 0xff) << 8) | (_data[7] & 0xff);
                            float batteryOut     = (float)(((_data[4] & 0xff) << 8) | (_data[5] & 0xff));
                            float batteryVoltage = (batteryOut) / (float)(435.0);
                            float current        = (float)((voltage) / 32767.0 * 2.048);


                            float temperature = (float)Math.Round((temp) / 4096.0 * 3.3, 3);

                            wound.user_id          = MainPage.mac;
                            wound.mChannel         = channel;
                            wound.mTemperature     = temperature;
                            wound.mBattery_voltage = batteryVoltage;
                            wound.mBias            = bias;
                            wound.mLmpoutput       = current;
                            wound.mTimeStamp       = (System.DateTime.Now.ToString(Constants.DATETIMEFORMAT));
                            //woundData = ConvertWoundSensor(woundData, wound);

                            if (WoundPage.SetWoundData != null)
                            {
                                WoundPage.SetWoundData(wound.GetDoubleArray());
                            }


                            SyncData(wound);


                            //if (PowerBILive != null)
                            //{
                            //    var dataWound = string.Format(Constants.wounddata, DateTime.Now.ToString(Constants.DATETIMEFORMAT), woundData.Channel.ToString(), woundData.Lmpoutput.ToString(), woundData.Temperature.ToString());
                            //    PowerBILive(dataWound, NetworkCommunicationManager.DATATYPE.WOUND);
                            //}
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionErrorLogger.writeFileOnInternalStorage(ex.ToString());
                    }
                }
            }
        }