diff --git a/.github/ISSUE_TEMPLATE b/.github/ISSUE_TEMPLATE deleted file mode 100644 index 372126193..000000000 --- a/.github/ISSUE_TEMPLATE +++ /dev/null @@ -1,23 +0,0 @@ -**Actual Behaviour** - - - -**Expected Behaviour** - - - -**Steps to reproduce it** - - - -**LogCat for the issue** - - - -**Screenshots of the issue** - - - -**Would you like to work on the issue?** - - diff --git a/.github/PULL_REQUEST_TEMPLATE b/.github/PULL_REQUEST_TEMPLATE deleted file mode 100644 index ffcde23e8..000000000 --- a/.github/PULL_REQUEST_TEMPLATE +++ /dev/null @@ -1,13 +0,0 @@ -Fixes # - -## Changes -- - -## Screenshots / Recordings - - -**Checklist**: -- [ ] **No hard coding**: I have used resources from `strings.xml`, `dimens.xml` and `colors.xml` without hard coding any value. -- [ ] **No end of file edits**: No modifications done at end of resource files `strings.xml`, `dimens.xml` or `colors.xml`. -- [ ] **Code reformatting**: I have reformatted code and fixed indentation in every file included in this pull request. -- [ ] **No extra space**: My code does not contain any extra lines or extra spaces than the ones that are necessary. \ No newline at end of file diff --git a/.github/actions/android/action.yml b/.github/actions/android/action.yml new file mode 100644 index 000000000..542de7eba --- /dev/null +++ b/.github/actions/android/action.yml @@ -0,0 +1,60 @@ +name: "Android Workflow" + +inputs: + STORE_PASS: + description: 'Store Password' + required: false + default: '' + ALIAS: + description: 'Certificate Alias' + required: false + default: '' + KEY_PASS: + description: 'Key Password' + required: false + default: '' + VERSION_NAME: + description: 'Version Name to be used for build' + required: false + default: '1.0.0' + VERSION_CODE: + description: 'Version Code to be used for build' + required: true + default: '1' + +runs: + using: "composite" + steps: + - name: Set up Java + uses: actions/setup-java@v4 + with: + java-version: 17 + distribution: 'adopt' + cache: 'gradle' + + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + cache: true + flutter-version-file: pubspec.yaml + + - name: Build Android APK/AAB + shell: bash + env: + STORE_PASS: ${{ inputs.STORE_PASS }} + ALIAS: ${{ inputs.ALIAS }} + KEY_PASS: ${{ inputs.KEY_PASS }} + VERSION_NAME: ${{inputs.VERSION_NAME}} + VERSION_CODE: ${{inputs.VERSION_CODE}} + run: | + flutter build apk --debug --build-name $VERSION_NAME --build-number $VERSION_CODE + flutter build apk --profile --build-name $VERSION_NAME --build-number $VERSION_CODE + flutter build apk --build-name $VERSION_NAME --build-number $VERSION_CODE + flutter build appbundle --build-name $VERSION_NAME --build-number $VERSION_CODE + + - name: Store APK file + uses: actions/upload-artifact@v4 + with: + name: apk-files + path: | + build/app/outputs/flutter-apk/app-profile.apk \ No newline at end of file diff --git a/.github/actions/common/action.yml b/.github/actions/common/action.yml new file mode 100644 index 000000000..2fcb8f2c6 --- /dev/null +++ b/.github/actions/common/action.yml @@ -0,0 +1,28 @@ +name: "Common Workflow" + +runs: + using: "composite" + steps: + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + cache: true + flutter-version-file: pubspec.yaml + + - name: Fetch Flutter Dependencies + shell: bash + run: | + flutter pub get + dart format lib/l10n/ + + - name: Validate Code Format + shell: bash + run: dart format --output=none --set-exit-if-changed . + + - name: Analyze Code + shell: bash + run: flutter analyze + + - name: Run tests + shell: bash + run: flutter test \ No newline at end of file diff --git a/.github/actions/ios/action.yml b/.github/actions/ios/action.yml new file mode 100644 index 000000000..665fa11b3 --- /dev/null +++ b/.github/actions/ios/action.yml @@ -0,0 +1,45 @@ +name: "iOS Workflow" + +inputs: + VERSION_NAME: + description: 'Version Name to be used for build' + required: false + default: '1.0.0' + VERSION_CODE: + description: 'Version Code to be used for build' + required: true + default: '1' + +runs: + using: "composite" + steps: + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + cache: true + flutter-version-file: pubspec.yaml + + - name: Update Podfile + shell: bash + run: | + cd ./iOS + flutter pub get + pod install --repo-update + + - name: Build iOS IPA (No code signing for PRs) + if: ${{ github.event_name == 'pull_request' }} + shell: bash + env: + VERSION_NAME: ${{ inputs.VERSION_NAME }} + VERSION_CODE: ${{ inputs.VERSION_CODE }} + run: | + flutter build ipa --no-codesign --build-name $VERSION_NAME --build-number $VERSION_CODE + + - name: Build iOS IPA (With Code Signing) + if: ${{ github.event_name != 'pull_request' }} + shell: bash + env: + VERSION_NAME: ${{ inputs.VERSION_NAME }} + VERSION_CODE: ${{ inputs.VERSION_CODE }} + run: | + flutter build ipa --build-name $VERSION_NAME --build-number $VERSION_CODE \ No newline at end of file diff --git a/.github/actions/linux/action.yml b/.github/actions/linux/action.yml new file mode 100644 index 000000000..e8addd340 --- /dev/null +++ b/.github/actions/linux/action.yml @@ -0,0 +1,76 @@ +name: "Linux Workflow" + +inputs: + VERSION_NAME: + description: 'Version Name to be used for build' + required: false + default: '1.0.0' + VERSION_CODE: + description: 'Version Code to be used for build' + required: true + default: '1' + +runs: + using: "composite" + steps: + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + cache: true + flutter-version-file: pubspec.yaml + + - name: Install dependencies + shell: bash + run: | + sudo apt-get update + sudo apt-get install -y \ + clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev + + - name: Build Linux App + shell: bash + run: | + flutter config --enable-linux-desktop + source linux/prep.sh + flutter build linux --build-name ${{ inputs.VERSION_NAME }} --build-number ${{ inputs.VERSION_CODE }} + + - name: Install fpm + shell: bash + run: | + sudo apt-get install -y ruby ruby-dev build-essential + sudo gem install --no-document fpm + + - name: Build .deb package + shell: bash + run: | + fpm -s dir -t deb \ + -n pslab \ + -v ${{ inputs.VERSION_NAME }} \ + --prefix=/ \ + --depends libusb-1.0-0 \ + build/linux/x64/release/bundle/bin/=/usr/bin \ + build/linux/x64/release/bundle/lib/pslab/=/usr/lib/pslab \ + build/linux/x64/release/bundle/share/pslab/=/usr/share/pslab \ + linux/pslab.desktop=/usr/share/applications/pslab.desktop \ + linux/assets/pslab.png=/usr/share/icons/hicolor/512x512/apps/pslab.png \ + linux/99-pslab.rules=/etc/udev/rules.d/99-pslab.rules + + - name: Build .rpm package + shell: bash + run: | + fpm -s dir -t rpm \ + -n pslab \ + -v ${{ inputs.VERSION_NAME }} \ + --prefix=/ \ + --depends libusb-1.0-0 \ + build/linux/x64/release/bundle/bin/=/usr/bin \ + build/linux/x64/release/bundle/lib/pslab/=/usr/lib/pslab \ + build/linux/x64/release/bundle/share/pslab/=/usr/share/pslab \ + linux/pslab.desktop=/usr/share/applications/pslab.desktop \ + linux/assets/pslab.png=/usr/share/icons/hicolor/512x512/apps/pslab.png \ + linux/99-pslab.rules=/etc/udev/rules.d/99-pslab.rules + + - name: Store Packages + uses: actions/upload-artifact@v4 + with: + name: linux-packages + path: "*.deb\n*.rpm" \ No newline at end of file diff --git a/.github/actions/macos/action.yml b/.github/actions/macos/action.yml new file mode 100644 index 000000000..e857d7f24 --- /dev/null +++ b/.github/actions/macos/action.yml @@ -0,0 +1,50 @@ +name: "macOS Workflow" + +inputs: + VERSION_NAME: + description: 'Version Name to be used for build' + required: false + default: '1.0.0' + VERSION_CODE: + description: 'Version Code to be used for build' + required: true + default: '1' + +runs: + using: "composite" + steps: + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + cache: true + flutter-version-file: pubspec.yaml + + - name: Update Podfile + shell: bash + run: | + cd ./macos + flutter pub get + pod install --repo-update + + - name: Build macOS App + shell: bash + env: + VERSION_NAME: ${{ inputs.VERSION_NAME }} + VERSION_CODE: ${{ inputs.VERSION_CODE }} + run: | + flutter config --enable-macos-desktop + flutter build macos --build-name $VERSION_NAME --build-number $VERSION_CODE + + - name: Package into dmg + shell: bash + run: | + brew install node + npm install -g appdmg + + appdmg appdmg.json pslab-${{ inputs.VERSION_NAME }}+${{ inputs.VERSION_CODE }}.dmg + + - name: Store App file + uses: actions/upload-artifact@v4 + with: + name: macos-app + path: pslab-${{ inputs.VERSION_NAME }}+${{ inputs.VERSION_CODE }}.dmg \ No newline at end of file diff --git a/.github/actions/screenshot-android/action.yml b/.github/actions/screenshot-android/action.yml new file mode 100644 index 000000000..0e13c7f2d --- /dev/null +++ b/.github/actions/screenshot-android/action.yml @@ -0,0 +1,97 @@ +name: "Android Screenshots Workflow" + +inputs: + ANDROID_EMULATOR_API: + description: 'Emulator API to be used when running tests' + required: false + default: 34 + ANDROID_EMULATOR_ARCH: + description: 'Emulator architecture to be used when running tests' + required: false + default: x86_64 + +runs: + using: "composite" + steps: + - name: Set up Java + uses: actions/setup-java@v4 + with: + java-version: 17 + distribution: 'adopt' + cache: 'gradle' + + - name: Enable KVM group perms + shell: bash + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + + - name: Cache AVD + uses: actions/cache@v4 + id: avd-cache + with: + path: | + ~/.android/avd/* + ~/.android/adb* + key: avd-${{ inputs.ANDROID_EMULATOR_API }}-${{ inputs.ANDROID_EMULATOR_ARCH }} + + - name: Create AVD and Cache Snapshot + if: steps.avd-cache.outputs.cache-hit != 'true' + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: ${{ inputs.ANDROID_EMULATOR_API }} + arch: ${{ inputs.ANDROID_EMULATOR_ARCH }} + profile: pixel_6 + avd-name: pixel_6 + force-avd-creation: false + emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none + disable-animations: false + script: echo "Generated AVD snapshot for caching." + + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + cache: true + flutter-version-file: pubspec.yaml + + - name: Create Android Screenshots + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: ${{ inputs.ANDROID_EMULATOR_API }} + arch: ${{ inputs.ANDROID_EMULATOR_ARCH }} + profile: pixel_6 + avd-name: pixel_6 + force-avd-creation: false + emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none + disable-animations: true + script: | + DEVICE_NAME="Pixel 6" flutter drive --driver=test_integration/test_driver.dart --target=test_integration/screenshots.dart -d emulator + + - name: Update Fastlane Metadata + if: ${{ github.event_name == 'push' }} + shell: bash + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + + cd ./android + git clone --branch=fastlane-android --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} fastlane + cd fastlane + + rm -rf metadata/android/en-US/images/phoneScreenshots/* + cp -r ../../screenshots/. metadata/android/en-US/images/phoneScreenshots/ + + # Force push to fastlane branch + git checkout --orphan temporary + git add --all . + git commit -am "[Auto] Update screenshots ($(date +%Y-%m-%d.%H:%M:%S))" + git branch -D fastlane-android + git branch -m fastlane-android + git push --force origin fastlane-android + + - name: Upload Screenshots + uses: actions/upload-artifact@v4 + with: + name: Android Screenshots + path: screenshots/* diff --git a/.github/actions/screenshot-ipad/action.yml b/.github/actions/screenshot-ipad/action.yml new file mode 100644 index 000000000..222919430 --- /dev/null +++ b/.github/actions/screenshot-ipad/action.yml @@ -0,0 +1,63 @@ +name: "iPad Screenshots Workflow" + +inputs: + IPAD_DEVICE_MODEL: + description: 'Model of the iPad device to be used when running tests' + required: false + default: iPad Pro 13-inch (M4) + +runs: + using: "composite" + steps: + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + cache: true + flutter-version-file: pubspec.yaml + + - name: Update Podfile + shell: bash + run: | + cd ./iOS + flutter pub get + pod install --repo-update + + - name: Create iPad Simulator + id: ipad_sim + uses: futureware-tech/simulator-action@v4 + with: + model: ${{ inputs.IPAD_DEVICE_MODEL }} + wait_for_boot: true + + - name: Capture iPad Screenshots + shell: bash + run: | + DEVICE_NAME="${{ inputs.IPAD_DEVICE_MODEL }}" flutter drive --driver=test_integration/test_driver.dart --target=test_integration/screenshots.dart -d "${{ steps.ipad_sim.outputs.udid }}" + + - name: Update Fastlane Metadata + if: ${{ github.event_name == 'push' }} + shell: bash + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + + cd ./iOS + git clone --branch=fastlane-ios --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} fastlane + cd fastlane + + rm -rf screenshots/iPad* + cp -r ../../screenshots/. screenshots/ + + # Force push to fastlane branch + git checkout --orphan temporary + git add --all . + git commit -am "[Auto] Update screenshots ($(date +%Y-%m-%d.%H:%M:%S))" + git branch -D fastlane-ios + git branch -m fastlane-ios + git push --force origin fastlane-ios + + - name: Upload Screenshots + uses: actions/upload-artifact@v4 + with: + name: iPad Screenshots + path: screenshots/* \ No newline at end of file diff --git a/.github/actions/screenshot-iphone/action.yml b/.github/actions/screenshot-iphone/action.yml new file mode 100644 index 000000000..49201001f --- /dev/null +++ b/.github/actions/screenshot-iphone/action.yml @@ -0,0 +1,63 @@ +name: "iPhone Screenshots Workflow" + +inputs: + IPHONE_DEVICE_MODEL: + description: 'Model of the iPhone device to be used when running tests' + required: false + default: iPhone 16 Pro Max + +runs: + using: "composite" + steps: + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + cache: true + flutter-version-file: pubspec.yaml + + - name: Update Podfile + shell: bash + run: | + cd ./iOS + flutter pub get + pod install --repo-update + + - name: Create iPhone Simulator + id: iphone_sim + uses: futureware-tech/simulator-action@v4 + with: + model: ${{ inputs.IPHONE_DEVICE_MODEL }} + wait_for_boot: true + + - name: Capture iPhone Screenshots + shell: bash + run: | + DEVICE_NAME="${{ inputs.IPHONE_DEVICE_MODEL }}" flutter drive --driver=test_integration/test_driver.dart --target=test_integration/screenshots.dart -d "${{ steps.iphone_sim.outputs.udid }}" + + - name: Update Fastlane Metadata + if: ${{ github.event_name == 'push' }} + shell: bash + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + + cd ./iOS + git clone --branch=fastlane-ios --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} fastlane + cd fastlane + + rm -rf screenshots/iPhone* + cp -r ../../screenshots/. screenshots/ + + # Force push to fastlane branch + git checkout --orphan temporary + git add --all . + git commit -am "[Auto] Update screenshots ($(date +%Y-%m-%d.%H:%M:%S))" + git branch -D fastlane-ios + git branch -m fastlane-ios + git push --force origin fastlane-ios + + - name: Upload Screenshots + uses: actions/upload-artifact@v4 + with: + name: iPhone Screenshots + path: screenshots/* \ No newline at end of file diff --git a/.github/actions/windows/action.yml b/.github/actions/windows/action.yml new file mode 100644 index 000000000..cb883dbdd --- /dev/null +++ b/.github/actions/windows/action.yml @@ -0,0 +1,49 @@ +name: "Windows Workflow" + +inputs: + VERSION_NAME: + description: 'Version Name to be used for build' + required: false + default: '1.0.0' + VERSION_CODE: + description: 'Version Code to be used for build' + required: true + default: '1' + +runs: + using: "composite" + steps: + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + cache: true + flutter-version-file: pubspec.yaml + + - name: Build Windows App + shell: pwsh + run: | + flutter config --enable-windows-desktop + flutter build windows --build-name ${{ inputs.VERSION_NAME }} --build-number ${{ inputs.VERSION_CODE }} + + - name: Build iss script + id: build-iss + shell: pwsh + run: | + # Update version in pubspec.yaml for iss script + (Get-Content pubspec.yaml) -replace '^version: .*', "version: ${{ inputs.VERSION_NAME }}+${{ inputs.VERSION_CODE }}" | Set-Content pubspec.yaml + + dart run inno_bundle:build --no-app --release --no-installer + echo $(dart run inno_bundle:build --envs --no-hf) | Out-File -FilePath $Env:GITHUB_OUTPUT -Encoding utf8 -Append + + - name: Build Installer + shell: pwsh + run: | + choco install innosetup --version=6.4.0 -y + $iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\iscc.exe" + & "$iscc" /O+ "build\windows\x64\installer\Release\inno-script.iss" + + - name: Store Installer + uses: actions/upload-artifact@v4 + with: + name: windows-installer + path: build/windows/x64/installer/Release/${{ steps.build-iss.outputs.APP_NAME_CAMEL_CASE }}-x86_64-${{ steps.build-iss.outputs.APP_VERSION }}-Installer.exe \ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 6c34404be..f27299660 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,17 +1,21 @@ version: 2 + +enable-beta-ecosystems: true updates: - - package-ecosystem: "github-actions" + - package-ecosystem: "pub" directory: "/" schedule: - interval: "weekly" - reviewers: - - "mariobehling" - - "cloudypadmal" - + interval: "daily" - package-ecosystem: "gradle" - directory: "/" + directory: "/android/" + schedule: + interval: "daily" + - package-ecosystem: "github-actions" + directories: + - "/.github/workflows" + - "/.github/actions/android" + - "/.github/actions/common" + - "/.github/actions/ios" + - "/.github/actions/screenshot-android" schedule: - interval: "weekly" - reviewers: - - "mariobehling" - - "cloudypadmal" \ No newline at end of file + interval: "daily" \ No newline at end of file diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml index 1e99245e1..01f483170 100644 --- a/.github/release-drafter.yml +++ b/.github/release-drafter.yml @@ -9,7 +9,7 @@ categories: - title: ':bug: Bug Fixes' label: 'Fix' - title: ':wrench: Maintenance' - labels: + labels: - 'Chore' - title: ':page_facing_up: Documentation' label: 'Documentation' @@ -21,7 +21,7 @@ exclude-labels: - 'Dependencies' - 'Chore' template: |- - ## Changes - $CHANGES - - This release was made possible thanks to $CONTRIBUTORS + ## Changes + $CHANGES + + This release was made possible thanks to $CONTRIBUTORS \ No newline at end of file diff --git a/.github/workflows/clean-screenshots.yml b/.github/workflows/clean-screenshots.yml new file mode 100644 index 000000000..cea7f835f --- /dev/null +++ b/.github/workflows/clean-screenshots.yml @@ -0,0 +1,42 @@ +name: Clean PR Screenshots + +on: + schedule: + - cron: '0 3 * * 0' + workflow_dispatch: + +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + +jobs: + cleanup: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + ref: pr-screenshots + + - name: Delete screenshots from closed PRs + run: | + open_prs=$(gh pr list --state open --json number -q '.[].number') + + for file in *.png; do + pr_num=$(echo "$file" | cut -d'_' -f1) + if ! echo "$open_prs" | grep -qw "$pr_num"; then + rm "$file" + fi + done + + - name: Commit and push changes + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + + # Force push to pr-screenshots branch + git checkout --orphan temporary + git add --all . + git commit -am "[Auto] Clean screenshots ($(date +%Y-%m-%d.%H:%M:%S))" + git branch -D pr-screenshots + git branch -m pr-screenshots + git push --force origin pr-screenshots diff --git a/.github/workflows/flutter_upgrade.yml b/.github/workflows/flutter_upgrade.yml new file mode 100644 index 000000000..0ba439d5c --- /dev/null +++ b/.github/workflows/flutter_upgrade.yml @@ -0,0 +1,60 @@ +name: Flutter Upgrade Check + +on: + schedule: + - cron: "0 0 * * 1" + workflow_dispatch: + +jobs: + check-flutter-upgrade: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v5 + + - name: Read Flutter version from pubspec.yaml + id: read-version + run: | + FLUTTER_VERSION=$(yq '.environment.flutter' pubspec.yaml) + echo "Current Flutter version: $FLUTTER_VERSION" + echo "flutter_version=$FLUTTER_VERSION" >> $GITHUB_ENV + + - name: Get latest stable Flutter version + id: check-latest + run: | + LATEST_VERSION=$(curl -s https://storage.googleapis.com/flutter_infra_release/releases/releases_linux.json | jq -r '.releases[] | select(.channel == "stable") | .version' | head -n 1) + echo "Latest stable Flutter version: $LATEST_VERSION" + echo "latest_flutter_version=$LATEST_VERSION" >> $GITHUB_ENV + + - name: Compare versions and update pubspec.yaml if needed + id: update-version + run: | + if [ "$flutter_version" != "$latest_flutter_version" ]; then + echo "Updating Flutter version in pubspec.yaml..." + sed -i "s/flutter:\s*'${flutter_version}'/flutter: '${latest_flutter_version}'/" pubspec.yaml + git --no-pager diff + echo "update_needed=true" >> $GITHUB_ENV + else + echo "Flutter is up to date." + echo "update_needed=false" >> $GITHUB_ENV + fi + + - name: Commit and create PR if update is needed + if: env.update_needed == 'true' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + git config --global user.name "dependabot[bot]" + git config --global user.email "49699333+dependabot[bot]@users.noreply.github.com" + + BRANCH_NAME="flutter-upgrade-${{ env.latest_flutter_version }}" + git checkout -b $BRANCH_NAME + git add pubspec.yaml + git commit -m "chore: Upgrade Flutter to ${{ env.latest_flutter_version }}" + git push origin -f $BRANCH_NAME + + PR_URL=$(gh pr create --title "chore(deps): upgrade Flutter to ${{ env.latest_flutter_version }}" \ + --body "This PR updates Flutter version in pubspec.yaml to the latest stable release." \ + --base development \ + --head $BRANCH_NAME) diff --git a/.github/workflows/pull-request-closed.yml b/.github/workflows/pull-request-closed.yml new file mode 100644 index 000000000..1dfcfa7b0 --- /dev/null +++ b/.github/workflows/pull-request-closed.yml @@ -0,0 +1,33 @@ +name: Delete Screenshots + +on: + pull_request_target: + branches: [ "flutter" ] + types: + - closed + +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + +jobs: + delete_screenshots: + name: Delete Screenshots + runs-on: ubuntu-latest + steps: + - name: Delete Screenshots + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + + git clone --branch=pr-screenshots --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} pr-screenshots + cd pr-screenshots + + rm -f ${{ github.event.number }}_*.png + + # Force push to pr-screenshots branch + git checkout --orphan temporary + git add --all . + git commit -am "[Auto] Delete screenshots for #${{ github.event.number }} ($(date +%Y-%m-%d.%H:%M:%S))" + git branch -D pr-screenshots + git branch -m pr-screenshots + git push --force origin pr-screenshots diff --git a/.github/workflows/pull-request-comment.yml b/.github/workflows/pull-request-comment.yml index 4254262f9..aa792faef 100644 --- a/.github/workflows/pull-request-comment.yml +++ b/.github/workflows/pull-request-comment.yml @@ -12,8 +12,9 @@ jobs: if: > github.event.workflow_run.event == 'pull_request' steps: - - name: Download artifact - uses: actions/github-script@v6 + - name: Download artifacts + id: download-artifacts + uses: actions/github-script@v7 with: script: | var artifacts = await github.rest.actions.listWorkflowRunArtifacts({ @@ -21,26 +22,103 @@ jobs: repo: context.repo.repo, run_id: ${{github.event.workflow_run.id }}, }); - var matchArtifact = artifacts.data.artifacts.filter((artifact) => { + + var pr = artifacts.data.artifacts.filter((artifact) => { return artifact.name == "pr" })[0]; var download = await github.rest.actions.downloadArtifact({ owner: context.repo.owner, repo: context.repo.repo, - artifact_id: matchArtifact.id, + artifact_id: pr.id, archive_format: 'zip', }); var fs = require('fs'); fs.writeFileSync('${{github.workspace}}/pr.zip', Buffer.from(download.data)); - - run: unzip pr.zip - - name: Build success - if: ${{ github.event.workflow_run.conclusion == 'success' }} - uses: actions/github-script@v6 + var androidScreenshots = artifacts.data.artifacts.filter((artifact) => { + return artifact.name == "Android Screenshots" + })[0]; + var downloadAndroidScreenshots = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: androidScreenshots.id, + archive_format: 'zip', + }); + + fs.writeFileSync('${{github.workspace}}/androidScreenshots.zip', Buffer.from(downloadAndroidScreenshots.data)); + + var iPadScreenshots = artifacts.data.artifacts.filter((artifact) => { + return artifact.name == "iPad Screenshots" + })[0]; + var downloadiPadScreenshots = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: iPadScreenshots.id, + archive_format: 'zip', + }); + + fs.writeFileSync('${{github.workspace}}/iPadScreenshots.zip', Buffer.from(downloadiPadScreenshots.data)); + + var iPhoneScreenshots = artifacts.data.artifacts.filter((artifact) => { + return artifact.name == "iPhone Screenshots" + })[0]; + var downloadiPhoneScreenshots = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: iPhoneScreenshots.id, + archive_format: 'zip', + }); + + fs.writeFileSync('${{github.workspace}}/iPhoneScreenshots.zip', Buffer.from(downloadiPhoneScreenshots.data)); + + - name: Unzip Artifacts + shell: bash + run: | + unzip pr.zip + mkdir screenshots + unzip androidScreenshots.zip -d screenshots/ + unzip iPadScreenshots.zip -d screenshots/ + unzip iPhoneScreenshots.zip -d screenshots/ + + - name: Fetch PR Number + id: fetch-pr-number + uses: actions/github-script@v7 with: script: | var fs = require('fs') var issue_number = Number(fs.readFileSync('./NR')); + core.setOutput("pr_number", issue_number); + + - name: Update PR Screenshots + shell: bash + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + + git clone --branch=pr-screenshots --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} pr-screenshots + cd pr-screenshots + + for file in ../screenshots/*; do + if [[ -f "$file" ]]; then + filename=$(basename "$file") + cp -f "$file" "./${{ steps.fetch-pr-number.outputs.pr_number }}_${filename}" + fi + done + + # Force push to pr-screenshots branch + git checkout --orphan temporary + git add --all . + git commit -am "[Auto] Update screenshots for #${{ steps.fetch-pr-number.outputs.pr_number }} ($(date +%Y-%m-%d.%H:%M:%S))" + git branch -D pr-screenshots + git branch -m pr-screenshots + git push --force origin pr-screenshots + + - name: Build success + if: ${{ github.event.workflow_run.conclusion == 'success' }} + uses: actions/github-script@v7 + with: + script: | + var issue_number = ${{ steps.fetch-pr-number.outputs.pr_number }}; const owner = context.repo.owner; const repo = context.repo.repo; var artifacts = await github.rest.actions.listWorkflowRunArtifacts({ @@ -66,8 +144,81 @@ jobs: break; } } + + var statusText = `Build successful. APKs to test: ${artifact_url}.`; + + var androidScreenshots = ` +
+ Android Screenshots + + + + + + + + + + + + +
+ +
+
+ `; + + var iPhoneScreenshots = ` +
+ iPhone Screenshots + + + + + + + + + + + + +
+ +
+
+ `; + + var iPadScreenshots = ` +
+ iPad Screenshots + + + + + + + + + + + + +
+ +
+
+ `; - const body = `Build successful. APKs to test: ${artifact_url}`; + const body = ` + ## Build Status + ${statusText} + + ## Screenshots + ${androidScreenshots} + ${iPhoneScreenshots} + ${iPadScreenshots} + `; if (comment_id) { await github.rest.issues.updateComment({ @@ -87,11 +238,10 @@ jobs: - name: Build failed if: ${{ github.event.workflow_run.conclusion == 'failure' }} - uses: actions/github-script@v6 + uses: actions/github-script@v7 with: script: | - var fs = require('fs') - var issue_number = Number(fs.readFileSync('./NR')); + var issue_number = ${{ steps.fetch-pr-number.outputs.pr_number }}; const owner = context.repo.owner; const repo = context.repo.repo; @@ -109,7 +259,13 @@ jobs: } } - const body = `Build failed`; + const body = ` + ## Build Status + _Build workflow failed. Please check the logs for more information._ + + ## Screenshots + _Not able to fetch screenshots._ + `; if (comment_id) { await github.rest.issues.updateComment({ diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index f22605252..57ec4c7bd 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -2,41 +2,141 @@ name: Build on: pull_request: - branches: - - master - - development + branches: ["flutter"] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + ANDROID_EMULATOR_API: 34 + ANDROID_EMULATOR_ARCH: x86_64 + IPHONE_DEVICE_MODEL: iPhone 16 Pro Max + IPAD_DEVICE_MODEL: iPad Pro 13-inch (M4) jobs: - build: + common: + name: Common Build runs-on: ubuntu-latest - steps: - - name: Download repository - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - - name: Setup Java - uses: actions/setup-java@v3 - with: - distribution: 'adopt' - java-version: '17' + - name: Common Workflow + uses: ./.github/actions/common - name: Save PR number run: | mkdir -p ./pr echo ${{ github.event.number }} > ./pr/NR - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: pr path: pr/ - - name: Build with Gradle - run: | - bash ./gradlew build --stacktrace + android: + name: Android Flutter Build + needs: common + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Android Workflow + uses: ./.github/actions/android + + ios: + name: iOS Flutter Build + needs: common + runs-on: macos-latest + steps: + - name: Set up Xcode + uses: maxim-lobanov/setup-xcode@v1.6.0 + with: + xcode-version: '16.4.0' + + - uses: actions/checkout@v4 + + - name: iOS Workflow + uses: ./.github/actions/ios + + screenshots-android: + name: Screenshots (Android) + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + + - name: Android Screenshot Workflow + uses: ./.github/actions/screenshot-android + with: + ANDROID_EMULATOR_API: ${{ env.ANDROID_EMULATOR_API }} + ANDROID_EMULATOR_ARCH: ${{ env.ANDROID_EMULATOR_ARCH }} + + screenshots-iphone: + name: Screenshots (iPhone) + runs-on: macos-latest + timeout-minutes: 30 + steps: + - name: Set up Xcode + uses: maxim-lobanov/setup-xcode@v1.6.0 + with: + xcode-version: '16.4.0' + + - uses: actions/checkout@v4 + + - name: iPhone Screenshot Workflow + uses: ./.github/actions/screenshot-iphone + with: + IPHONE_DEVICE_MODEL: ${{ env.IPHONE_DEVICE_MODEL }} + + screenshots-ipad: + name: Screenshots (iPad) + runs-on: macos-latest + timeout-minutes: 30 + steps: + - name: Set up Xcode + uses: maxim-lobanov/setup-xcode@v1.6.0 + with: + xcode-version: '16.4.0' + + - uses: actions/checkout@v4 + + - name: iPad Screenshot Workflow + uses: ./.github/actions/screenshot-ipad + with: + IPAD_DEVICE_MODEL: ${{ env.IPAD_DEVICE_MODEL }} + + windows: + name: Windows Flutter Build + needs: common + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - name: Windows Workflow + uses: ./.github/actions/windows + + linux: + name: Linux Flutter Build + needs: common + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 - - name: Store APK file - uses: actions/upload-artifact@v3 + - name: Linux Workflow + uses: ./.github/actions/linux + + macos: + name: macOS Flutter Build + needs: common + runs-on: macos-latest + steps: + - name: Set up Xcode + uses: maxim-lobanov/setup-xcode@v1.6.0 with: - name: apk-files - path: | - app/build/outputs/apk/debug/app-debug.apk \ No newline at end of file + xcode-version: '16.4.0' + + - uses: actions/checkout@v4 + + - name: macOS Workflow + uses: ./.github/actions/macos \ No newline at end of file diff --git a/.github/workflows/push-event.yml b/.github/workflows/push-event.yml index 001336c00..1a016fdff 100644 --- a/.github/workflows/push-event.yml +++ b/.github/workflows/push-event.yml @@ -2,166 +2,382 @@ name: Push on: push: - branches: - - master - - development + branches: [ "flutter" ] env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + ANDROID_EMULATOR_API: 34 + ANDROID_EMULATOR_ARCH: x86_64 + IPHONE_DEVICE_MODEL: iPhone 16 Pro Max + IPAD_DEVICE_MODEL: iPad Pro 13-inch (M4) jobs: - build: + common: + name: Common Build runs-on: ubuntu-latest outputs: - branch: ${{ steps.branch-name.outputs.current_branch }} - + VERSION_NAME: ${{ steps.flutter-version.outputs.VERSION_NAME }} + VERSION_CODE: ${{ steps.flutter-version.outputs.VERSION_CODE }} steps: - - name: Download repository - uses: actions/checkout@v3 - - - uses: actions/cache@v4 - with: - path: | - ~/.gradle/caches - ~/.gradle/wrapper - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*') }} - restore-keys: | - ${{ runner.os }}-gradle- - - - name: Setup Ruby - if: ${{ github.repository == 'fossasia/pslab-android' }} - uses: ruby/setup-ruby@v1 - with: - ruby-version: '3.3' - bundler-cache: true - - - name: Prepare Bundler - if: ${{ github.repository == 'fossasia/pslab-android' }} - run: | - bundle config path vendor/bundle - bundle install --jobs 4 --retry 3 + - uses: actions/checkout@v4 - - name: Setup Java - uses: actions/setup-java@v3 - with: - distribution: 'adopt' - java-version: '17' + - name: Common Workflow + uses: ./.github/actions/common - name: Hydrate and Update Version - id: android-version + id: flutter-version run: | git config --global user.name "github-actions[bot]" git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" - git clone --branch=version --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} version + # Get commit message + commit_message=$(git log -1 --pretty=format:"%s") + + git clone --branch=version https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} version cd version # Read and increment version name IFS='.' read -r major minor patch < versionName.txt - current_patch_version_name="$major.$minor.$patch" - echo "VERSION_NAME=$current_patch_version_name" >> $GITHUB_OUTPUT - - next_patch=$((patch + 1)) - next_patch_version_name="$major.$minor.$next_patch" - echo "$next_patch_version_name" > versionName.txt + + if [[ "$commit_message" =~ ^feat: ]]; then + next_minor=$((minor + 1)) + next_patch=0 + else + next_minor=$((minor)) + next_patch=$((patch + 1)) + fi + next_version_name="$major.$next_minor.$next_patch" + echo "VERSION_NAME=$next_version_name" >> $GITHUB_OUTPUT + echo "$next_version_name" > versionName.txt # Read and increment version code read -r version_code < versionCode.txt - echo "VERSION_CODE=$version_code" >> $GITHUB_OUTPUT new_version_code=$((version_code + 1)) + echo "VERSION_CODE=$new_version_code" >> $GITHUB_OUTPUT echo "$new_version_code" > versionCode.txt # Force push to version branch git checkout --orphan temporary git add --all . - git commit -am "[Auto] Update versionName: $next_patch_version_name & versionCode: $new_version_code ($(date +%Y-%m-%d.%H:%M:%S))" + git commit -am "[Auto] Update versionName: $next_version_name & versionCode: $new_version_code ($(date +%Y-%m-%d.%H:%M:%S))" git branch -D version git branch -m version git push --force origin version + android: + name: Android Flutter Build + needs: common + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Prepare Build Keys + if: ${{ github.repository == 'fossasia/pslab-app' }} env: ENCRYPTED_F10B5E0E5262_IV: ${{ secrets.ENCRYPTED_F10B5E0E5262_IV }} ENCRYPTED_F10B5E0E5262_KEY: ${{ secrets.ENCRYPTED_F10B5E0E5262_KEY }} run: | - bash scripts/prep-key.sh + bash scripts/prep-android-key.sh - - name: Build with Gradle - env: + - name: Android Workflow + uses: ./.github/actions/android + with: STORE_PASS: ${{ secrets.STORE_PASS }} ALIAS: ${{ secrets.ALIAS }} KEY_PASS: ${{ secrets.KEY_PASS }} - VERSION_CODE: ${{ steps.android-version.outputs.VERSION_CODE }} - VERSION_NAME: ${{ steps.android-version.outputs.VERSION_NAME }} - run: | - bash ./gradlew build --stacktrace - bash ./gradlew bundle --stacktrace + VERSION_NAME: ${{needs.common.outputs.VERSION_NAME}} + VERSION_CODE: ${{needs.common.outputs.VERSION_CODE}} - - name: Upload APK Debug + - name: Upload APK uses: actions/upload-artifact@v4 with: - name: APK Debug generated - path: app/build/outputs/apk/debug - - - name: Upload APK Release - uses: actions/upload-artifact@v4 - with: - name: APK Release generated - path: app/build/outputs/apk/release + name: APK Generated + path: build/app/outputs/flutter-apk - name: Upload AAB Release uses: actions/upload-artifact@v4 with: - name: AAB Release generated - path: app/build/outputs/bundle/release + name: AAB Generated + path: build/app/outputs/bundle - - name: Upload APK/AAB's to apk branch + - name: Upload APK/AAB to apk branch + if: ${{ github.repository == 'fossasia/pslab-app' }} run: | git config --global user.name "github-actions[bot]" git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" - - git clone --branch=apk --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} apk + + git clone --branch=apk https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} apk cd apk - if [[ ${{ github.ref_name }} =~ ^(master)$ ]]; then - rm -rf * - else - rm -rf pslab-dev* - fi - ls - - find ../app/build/outputs -type f \( -name '*.apk' -o -name '*.aab' \) -exec cp -v {} . \; - branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}} - + + echo "Removing previous files from branch" + + rm -rf pslab-$branch* + + ls + + echo "Copying new build files" + + find ../build/app/outputs/flutter-apk -type f \( -name '*release.apk' -o -name '*release.aab' \) -exec cp -v {} . \; + find ../build/app/outputs/bundle -type f \( -name '*release.apk' -o -name '*release.aab' \) -exec cp -v {} . \; + + ls + + echo "Renaming new build files" + for file in app*; do mv $file pslab-$branch-${file#*-} done - + + ls + + echo "Pushing to apk branch" + git checkout --orphan temporary git add --all . - git commit -am "[Auto] Update APK/AAB's from $branch ($(date +%Y-%m-%d.%H:%M:%S))" + git commit -am "[Auto] Update APK/AABs from $branch ($(date +%Y-%m-%d.%H:%M:%S))" git branch -D apk git branch -m apk git push --force origin apk - name: Update app in Open Testing track - if: ${{ github.repository == 'fossasia/pslab-android' }} + if: ${{ github.repository == 'fossasia/pslab-app' }} run: | - git clone --branch=fastlane --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} fastlane - bundle exec fastlane uploadToOpenTesting + git clone --branch=fastlane-android --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} fastlane + fastlane uploadToOpenTesting if [[ $? -ne 0 ]]; then exit 1 fi + ios: + name: iOS Flutter Build + needs: common + runs-on: macos-latest + steps: + - name: Set up Xcode + uses: maxim-lobanov/setup-xcode@v1.6.0 + with: + xcode-version: '16.4.0' + + - uses: actions/checkout@v4 + + - name: Prepare Build Keys + if: ${{ github.repository == 'fossasia/pslab-app' }} + env: + ENCRYPTED_IOS_IV: ${{ secrets.ENCRYPTED_IOS_IV }} + ENCRYPTED_IOS_KEY: ${{ secrets.ENCRYPTED_IOS_KEY }} + run: | + bash scripts/prep-ios-key.sh + + - name: Setup Certs + if: ${{ github.repository == 'fossasia/pslab-app' }} + env: + MATCH_PASSWORD: ${{ secrets.MATCH_PASSWORD }} + MATCH_GIT_BASIC_AUTHORIZATION: ${{ secrets.MATCH_GIT_BASIC_AUTHORIZATION }} + run: | + cd ./iOS + git clone --branch=fastlane-ios --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} fastlane + fastlane setupCertificates + if [[ $? -ne 0 ]]; then + exit 1 + fi + + - name: iOS Workflow + uses: ./.github/actions/ios + with: + VERSION_NAME: ${{needs.common.outputs.VERSION_NAME}} + VERSION_CODE: ${{needs.common.outputs.VERSION_CODE}} + + - name: Push app to testflight + if: ${{ github.repository == 'fossasia/pslab-app' }} + run: | + cd ./iOS + fastlane uploadToBeta + if [[ $? -ne 0 ]]; then + exit 1 + fi + + update-release: + name: Update Draft Release + needs: [ common, android, ios, windows, linux, macos ] + runs-on: ubuntu-latest + steps: - name: Run Release Drafter - id: run-release-drafter uses: release-drafter/release-drafter@v6 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + version: ${{ needs.common.outputs.VERSION_NAME }} + + screenshots-android: + name: Screenshots (Android) + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + + - name: Android Screenshot Workflow + uses: ./.github/actions/screenshot-android + with: + ANDROID_EMULATOR_API: ${{ env.ANDROID_EMULATOR_API }} + ANDROID_EMULATOR_ARCH: ${{ env.ANDROID_EMULATOR_ARCH }} + + screenshots-iphone: + name: Screenshots (iPhone) + runs-on: macos-latest + timeout-minutes: 30 + steps: + - name: Set up Xcode + uses: maxim-lobanov/setup-xcode@v1.6.0 + with: + xcode-version: '16.4.0' + + - uses: actions/checkout@v4 + + - name: iPhone Screenshot Workflow + uses: ./.github/actions/screenshot-iphone + with: + IPHONE_DEVICE_MODEL: ${{ env.IPHONE_DEVICE_MODEL }} + + screenshots-ipad: + name: Screenshots (iPad) + runs-on: macos-latest + timeout-minutes: 30 + steps: + - name: Set up Xcode + uses: maxim-lobanov/setup-xcode@v1.6.0 with: - version: ${{ steps.android-version.outputs.VERSION_NAME }} + xcode-version: '16.4.0' + + - uses: actions/checkout@v4 + + - name: iPad Screenshot Workflow + uses: ./.github/actions/screenshot-ipad + with: + IPAD_DEVICE_MODEL: ${{ env.IPAD_DEVICE_MODEL }} + + windows: + name: Windows Flutter Build + needs: common + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 - - name: Create and Upload Assets + - name: Windows Workflow + uses: ./.github/actions/windows + with: + VERSION_NAME: ${{needs.common.outputs.VERSION_NAME}} + VERSION_CODE: ${{needs.common.outputs.VERSION_CODE}} + + - name: Upload installer to apk branch + if: ${{ github.repository == 'fossasia/pslab-app' }} + shell: bash run: | - echo "${{ steps.android-version.outputs.VERSION_CODE }}" > ./versionCode.txt - gh release upload ${{ steps.run-release-drafter.outputs.tag_name }} apk/pslab-development-release.apk ./versionCode.txt --clobber \ No newline at end of file + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + + git clone --branch=apk https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} apk + cd apk + + branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}} + + echo "Removing previous files from branch" + + rm -rf *.exe + + echo "Copying new build files" + + cp -v ../build/windows/x64/installer/Release/*.exe . + + echo "Pushing to apk branch" + + git checkout --orphan temporary + git add --all . + git commit -am "[Auto] Update Windows Installer from $branch ($(date +%Y-%m-%d.%H:%M:%S))" + git branch -D apk + git branch -m apk + git push --force origin apk + + linux: + name: Linux Flutter Build + needs: common + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Linux Workflow + uses: ./.github/actions/linux + with: + VERSION_NAME: ${{needs.common.outputs.VERSION_NAME}} + VERSION_CODE: ${{needs.common.outputs.VERSION_CODE}} + + - name: Upload packages to apk branch + if: ${{ github.repository == 'fossasia/pslab-app' }} + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + + git clone --branch=apk https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} apk + cd apk + + branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}} + + echo "Removing previous files from branch" + + rm -rf *.deb *.rpm + + echo "Copying new build files" + + cp -v ../*.deb . + cp -v ../*.rpm . + + echo "Pushing to apk branch" + + git checkout --orphan temporary + git add --all . + git commit -am "[Auto] Update Linux Packages from $branch ($(date +%Y-%m-%d.%H:%M:%S))" + git branch -D apk + git branch -m apk + git push --force origin apk + + macos: + name: macOS Flutter Build + needs: common + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + + - name: macOS Workflow + uses: ./.github/actions/macos + with: + VERSION_NAME: ${{needs.common.outputs.VERSION_NAME}} + VERSION_CODE: ${{needs.common.outputs.VERSION_CODE}} + + - name: Upload dmg to apk branch + if: ${{ github.repository == 'fossasia/pslab-app' }} + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + + git clone --branch=apk https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} apk + cd apk + + branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}} + + echo "Removing previous files from branch" + + rm -rf *.dmg + + echo "Copying new build files" + + cp -v ../*.dmg . + + echo "Pushing to apk branch" + + git checkout --orphan temporary + git add --all . + git commit -am "[Auto] Update macOS DMG from $branch ($(date +%Y-%m-%d.%H:%M:%S))" + git branch -D apk + git branch -m apk + git push --force origin apk diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 776227049..cc5bd3354 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,38 +2,36 @@ name: Release on: release: - types: [published] + types: [ published ] env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} jobs: release: - if: ${{ github.repository == 'fossasia/pslab-android' }} + name: Release + if: ${{ github.repository == 'fossasia/pslab-app' }} runs-on: ubuntu-latest steps: - name: Download repository uses: actions/checkout@v4 - - name: Setup Ruby - uses: ruby/setup-ruby@v1 - with: - ruby-version: '3.3' - bundler-cache: true - - - name: Prepare Bundler - run: | - bundle config path vendor/bundle - bundle install --jobs 4 --retry 3 - - - name: Prepare Build Keys + - name: Prepare Secrets (Android) env: ENCRYPTED_F10B5E0E5262_IV: ${{ secrets.ENCRYPTED_F10B5E0E5262_IV }} ENCRYPTED_F10B5E0E5262_KEY: ${{ secrets.ENCRYPTED_F10B5E0E5262_KEY }} run: | - bash scripts/prep-key.sh - + bash scripts/prep-android-key.sh + + - name: Prepare Secrets (iOS) + if: ${{ github.repository == 'fossasia/pslab-app' }} + env: + ENCRYPTED_IOS_IV: ${{ secrets.ENCRYPTED_IOS_IV }} + ENCRYPTED_IOS_KEY: ${{ secrets.ENCRYPTED_IOS_KEY }} + run: | + bash scripts/prep-ios-key.sh + - name: Download Assets id: download-assets run: | @@ -41,27 +39,55 @@ jobs: read -r version_code < versionCode.txt echo "VERSION_CODE=$version_code" >> $GITHUB_OUTPUT - - name: Add Changelogs to fastlane branch - run: | git config --global user.name "github-actions[bot]" git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + + - name: Update Fastlane Metadata (Android) + run: | + cd ./android + git clone --branch=fastlane-android --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} fastlane + cd fastlane - git clone --branch=fastlane --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} fastlane + printf "%s" "${{ github.event.release.body }}" > "metadata/android/en-US/changelogs/${{ steps.download-assets.outputs.VERSION_CODE }}.txt" + + # Force push to fastlane branch + git checkout --orphan temporary + git add --all . + git commit -am "[Auto] Update changelogs for versionCode: ${{ steps.download-assets.outputs.VERSION_CODE }} ($(date +%Y-%m-%d.%H:%M:%S))" + git branch -D fastlane-android + git branch -m fastlane-android + git push --force origin fastlane-android + + - name: Push version to production (Android) + run: | + cd ./android + fastlane promoteToProduction version_code:${{ steps.download-assets.outputs.VERSION_CODE }} + if [[ $? -ne 0 ]]; then + exit 1 + fi + + - name: Update Fastlane Metadata (iOS) + run: | + cd ./iOS + git clone --branch=fastlane-ios --depth=1 https://${{ github.repository_owner }}:${{ github.token }}@github.com/${{ github.repository }} fastlane cd fastlane - echo "${{ github.event.release.body }}" > metadata/android/en-US/changelogs/${{ steps.download-assets.outputs.VERSION_CODE }}.txt + printf "%s" "${{ github.event.release.body }}" > "metadata/en-US/release_notes.txt" # Force push to fastlane branch git checkout --orphan temporary git add --all . - git commit -am "[Auto] Add changelogs for versionCode: ${{ steps.download-assets.outputs.VERSION_CODE }} ($(date +%Y-%m-%d.%H:%M:%S))" - git branch -D fastlane - git branch -m fastlane - git push --force origin fastlane + git commit -am "[Auto] Update changelogs for versionCode: ${{ steps.download-assets.outputs.VERSION_CODE }} ($(date +%Y-%m-%d.%H:%M:%S))" + git branch -D fastlane-ios + git branch -m fastlane-ios + git push --force origin fastlane-ios - - name: Push version to production + - name: Push version to production (iOS) run: | - bundle exec fastlane promoteToProduction version_code:${{ steps.download-assets.outputs.VERSION_CODE }} + cd ./iOS + VERSION_TAG="${{ github.event.release.tag_name }}" + CLEAN_VERSION="${VERSION_TAG#v}" + fastlane promoteToProduction build_number:${{ steps.download-assets.outputs.VERSION_CODE }} version_name:${CLEAN_VERSION} if [[ $? -ne 0 ]]; then exit 1 - fi \ No newline at end of file + fi \ No newline at end of file diff --git a/.github/workflows/semantic_lint.yml b/.github/workflows/semantic_lint.yml new file mode 100644 index 000000000..8ac66440a --- /dev/null +++ b/.github/workflows/semantic_lint.yml @@ -0,0 +1,23 @@ +name: "Semantic Validation" + +on: + pull_request_target: + types: + - opened + - edited + - synchronize + +permissions: + pull-requests: write + +jobs: + main: + name: Validate PR title + runs-on: ubuntu-latest + steps: + - uses: amannn/action-semantic-pull-request@v5 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + ignoreLabels: | + chore(deps) \ No newline at end of file diff --git a/.gitignore b/.gitignore index ebd6fc5e7..666fc6a56 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,66 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ .gradle /local.properties .DS_Store -/build /captures -**/.idea/** -**/*.iml + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# macOS +**/Flutter/ephemeral/ +**/Pods/ +**/macos/Flutter/GeneratedPluginRegistrant.swift +**/macos/Flutter/ephemeral +**/xcuserdata/ + +# Windows +**/windows/flutter/ephemeral/ +**/windows/flutter/generated_plugin_registrant.cc +**/windows/flutter/generated_plugin_registrant.h +**/windows/flutter/generated_plugins.cmake + +# Linux +**/linux/flutter/ephemeral/ +**/linux/flutter/generated_plugin_registrant.cc +**/linux/flutter/generated_plugin_registrant.h +**/linux/flutter/generated_plugins.cmake + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + diff --git a/.metadata b/.metadata new file mode 100644 index 000000000..c2aa44bdb --- /dev/null +++ b/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "603104015dd692ea3403755b55d07813d5cf8965" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 603104015dd692ea3403755b55d07813d5cf8965 + base_revision: 603104015dd692ea3403755b55d07813d5cf8965 + - platform: android + create_revision: 603104015dd692ea3403755b55d07813d5cf8965 + base_revision: 603104015dd692ea3403755b55d07813d5cf8965 + - platform: ios + create_revision: 603104015dd692ea3403755b55d07813d5cf8965 + base_revision: 603104015dd692ea3403755b55d07813d5cf8965 + - platform: linux + create_revision: 603104015dd692ea3403755b55d07813d5cf8965 + base_revision: 603104015dd692ea3403755b55d07813d5cf8965 + - platform: macos + create_revision: 603104015dd692ea3403755b55d07813d5cf8965 + base_revision: 603104015dd692ea3403755b55d07813d5cf8965 + - platform: web + create_revision: 603104015dd692ea3403755b55d07813d5cf8965 + base_revision: 603104015dd692ea3403755b55d07813d5cf8965 + - platform: windows + create_revision: 603104015dd692ea3403755b55d07813d5cf8965 + base_revision: 603104015dd692ea3403755b55d07813d5cf8965 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000..cc9dce56b --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,13 @@ +{ + // See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations. + // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp + + // List of extensions which should be recommended for users of this workspace. + "recommendations": [ + "dart-code.flutter" + ], + // List of extensions recommended by VS Code that should not be recommended for users of this workspace. + "unwantedRecommendations": [ + + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..7ce62c2d4 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "[dart]": { + "editor.defaultFormatter": "Dart-Code.dart-code", + "editor.formatOnSave": true, + } +} \ No newline at end of file diff --git a/Gemfile b/Gemfile index b4298691b..adc90d98c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,3 +1,3 @@ -source "https://rubygems.org" - +source "https://rubygems.org" + gem "fastlane" \ No newline at end of file diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/README.md b/README.md index 754d243ca..8435f40c2 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,7 @@ Repository for the PSLab Android App for performing experiments with the [Pocket Science Lab](https://pslab.io) open-hardware platform. [![Build](https://github.com/fossasia/pslab-android/actions/workflows/pull-request.yml/badge.svg)](https://github.com/fossasia/pslab-android/actions/workflows/pull-request.yml) -[![Codacy Badge](https://app.codacy.com/project/badge/Grade/3383ddffb53b4c82a822f3a5991fe0a1)](https://www.codacy.com/gh/fossasia/pslab-android/dashboard?utm_source=github.com&utm_medium=referral&utm_content=fossasia/pslab-android&utm_campaign=Badge_Grade) [![Mailing List](https://img.shields.io/badge/Mailing%20List-FOSSASIA-blue.svg)](https://groups.google.com/forum/#!forum/pslab-fossasia) -![Minimum API Level](https://img.shields.io/badge/Min%20API%20Level-23-green) -![Maximum API Level](https://img.shields.io/badge/Max%20API%20Level-31-orange) ![GitHub repo size](https://img.shields.io/github/repo-size/fossasia/pslab-android) [![Gitter](https://badges.gitter.im/fossasia/pslab.svg)](https://gitter.im/fossasia/pslab?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![Twitter Follow](https://img.shields.io/twitter/follow/pslabio.svg?style=social&label=Follow&maxAge=2592000?style=flat-square)](https://twitter.com/pslabio) diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 000000000..ed1e6ed52 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,24 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 000000000..6588a5c68 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks +fastlane.json diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 000000000..9b048de01 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,82 @@ +plugins { + id "com.android.application" + id "kotlin-android" + id "dev.flutter.flutter-gradle-plugin" +} + +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +def KEYSTORE_FILE = rootProject.file('../scripts/pslab.jks') +def GITHUB_BUILD = System.getenv("GITHUB_ACTIONS") == "true" && KEYSTORE_FILE.exists() +def LOCAL_KEY_PRESENT = project.hasProperty('SIGNING_KEY_FILE') && rootProject.file(SIGNING_KEY_FILE).exists() + +android { + namespace = "io.pslab" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "io.pslab" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutterVersionCode.toInteger() + versionName = flutterVersionName + } + + signingConfigs { + if (GITHUB_BUILD) { + release { + storeFile KEYSTORE_FILE + storePassword System.getenv("STORE_PASS") + keyAlias System.getenv("ALIAS") + keyPassword System.getenv("KEY_PASS") + } + } else if (LOCAL_KEY_PRESENT) { + release { + storeFile rootProject.file(SIGNING_KEY_FILE) + storePassword STORE_PASS + keyAlias ALIAS + keyPassword KEY_PASS + } + } + } + + buildTypes { + release { + if (LOCAL_KEY_PRESENT || GITHUB_BUILD) + signingConfig = signingConfigs.release + } + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..aaf6c3b5a --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/io/pslab/MainActivity.java b/android/app/src/main/java/io/pslab/MainActivity.java new file mode 100644 index 000000000..5ad9edee1 --- /dev/null +++ b/android/app/src/main/java/io/pslab/MainActivity.java @@ -0,0 +1,166 @@ +package io.pslab; + +import android.content.Context; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; +import android.os.Bundle; +import android.util.Log; + +import androidx.annotation.NonNull; + +import io.flutter.embedding.android.FlutterActivity; +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.plugin.common.EventChannel; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; + +public class MainActivity extends FlutterActivity implements SensorEventListener { + private static final String TEMPERATURE_CHANNEL = "io.pslab/temperature"; + private static final String TEMPERATURE_STREAM = "io.pslab/temperature_stream"; + private static final String TAG = "MainActivity"; + private SensorManager sensorManager; + private Sensor temperatureSensor; + private EventChannel.EventSink temperatureEventSink; + private boolean isListening = false; + private float currentTemperature = 0.0f; + + @Override + public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { + super.configureFlutterEngine(flutterEngine); + + sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); + if (sensorManager != null) { + temperatureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); + } + + MethodChannel temperatureChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), TEMPERATURE_CHANNEL); + temperatureChannel.setMethodCallHandler(this::handleMethodCall); + + EventChannel temperatureEventChannel = new EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), TEMPERATURE_STREAM); + temperatureEventChannel.setStreamHandler(new EventChannel.StreamHandler() { + @Override + public void onListen(Object arguments, EventChannel.EventSink events) { + temperatureEventSink = events; + startTemperatureUpdates(); + } + + @Override + public void onCancel(Object arguments) { + temperatureEventSink = null; + stopTemperatureUpdates(); + } + }); + } + + private void handleMethodCall(MethodCall call, MethodChannel.Result result) { + switch (call.method) { + case "isTemperatureSensorAvailable": + result.success(temperatureSensor != null); + break; + case "getCurrentTemperature": + result.success((double) currentTemperature); + break; + case "startTemperatureUpdates": + if (startTemperatureUpdates()) { + result.success(true); + } else { + result.error("SENSOR_ERROR", "Failed to start temperature updates", null); + } + break; + case "stopTemperatureUpdates": + stopTemperatureUpdates(); + result.success(true); + break; + default: + result.notImplemented(); + break; + } + } + + private boolean startTemperatureUpdates() { + if (temperatureSensor == null || sensorManager == null) { + Log.e(TAG, "Temperature sensor not available"); + return false; + } + + if (!isListening) { + boolean registered = sensorManager.registerListener(this, temperatureSensor, SensorManager.SENSOR_DELAY_NORMAL); + if (registered) { + isListening = true; + Log.d(TAG, "Temperature sensor listener registered"); + + if (currentTemperature != 0.0f && temperatureEventSink != null) { + Log.d(TAG, "Sending initial temperature to Flutter: " + currentTemperature); + temperatureEventSink.success((double) currentTemperature); + } + + return true; + } else { + Log.e(TAG, "Failed to register temperature sensor listener"); + return false; + } + } + return true; + } + + private void stopTemperatureUpdates() { + if (isListening && sensorManager != null) { + sensorManager.unregisterListener(this, temperatureSensor); + isListening = false; + Log.d(TAG, "Temperature sensor listener unregistered"); + } + } + + @Override + public void onSensorChanged(SensorEvent event) { + if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE) { + float temperature = event.values[0]; + + if (isValidTemperature(temperature)) { + currentTemperature = temperature; + Log.d(TAG, "Temperature updated: " + currentTemperature + "°C"); + + if (temperatureEventSink != null) { + Log.d(TAG, "Sending temperature to Flutter: " + currentTemperature); + temperatureEventSink.success((double) currentTemperature); + } + } else { + Log.w(TAG, "Invalid temperature reading: " + temperature + " - ignoring"); + } + } + } + + private boolean isValidTemperature(float temperature) { + if (Float.isNaN(temperature) || Float.isInfinite(temperature)) return false; + return temperature >= -273.15f && temperature <= 200f && Math.abs(temperature) <= 1e10f; + } + + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) { + Log.d(TAG, "Sensor accuracy changed: " + accuracy); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + stopTemperatureUpdates(); + } + + @Override + protected void onPause() { + super.onPause(); + if (isListening && sensorManager != null) { + sensorManager.unregisterListener(this); + } + } + + @Override + protected void onResume() { + super.onResume(); + if (isListening && temperatureSensor != null && sensorManager != null) { + sensorManager.registerListener(this, temperatureSensor, SensorManager.SENSOR_DELAY_NORMAL); + } + } +} \ No newline at end of file diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 000000000..f74085f3f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 000000000..304732f88 --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launcher_icon.png b/android/app/src/main/res/drawable/launcher_icon.png new file mode 100644 index 000000000..891f3a5de Binary files /dev/null and b/android/app/src/main/res/drawable/launcher_icon.png differ diff --git a/app/src/main/res/drawable/app_icon_round.png b/android/app/src/main/res/drawable/launcher_icon_round.png similarity index 100% rename from app/src/main/res/drawable/app_icon_round.png rename to android/app/src/main/res/drawable/launcher_icon_round.png diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 000000000..06952be74 --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 000000000..cb1ef8805 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/app/src/main/res/xml/device_filter.xml b/android/app/src/main/res/xml/device_filter.xml similarity index 100% rename from app/src/main/res/xml/device_filter.xml rename to android/app/src/main/res/xml/device_filter.xml diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 000000000..d2ffbffa4 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,18 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = "../build" +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean", Delete) { + delete rootProject.buildDir +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 000000000..259717082 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties similarity index 80% rename from gradle/wrapper/gradle-wrapper.properties rename to android/gradle/wrapper/gradle-wrapper.properties index a7eee07cf..53aec7034 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Mon May 13 19:46:35 IST 2024 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-all.zip diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 000000000..af73326a5 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,25 @@ +pluginManagement { + def flutterSdkPath = { + def properties = new Properties() + file("local.properties").withInputStream { properties.load(it) } + def flutterSdkPath = properties.getProperty("flutter.sdk") + assert flutterSdkPath != null, "flutter.sdk not set in local.properties" + return flutterSdkPath + }() + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.12.2" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false +} + +include ":app" diff --git a/app/.gitignore b/app/.gitignore deleted file mode 100644 index 796b96d1c..000000000 --- a/app/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/app/build.gradle.kts b/app/build.gradle.kts deleted file mode 100644 index e7f307843..000000000 --- a/app/build.gradle.kts +++ /dev/null @@ -1,122 +0,0 @@ -plugins { - id("com.android.application") - id("com.google.android.gms.oss-licenses-plugin") -} - -apply(plugin = "realm-android") - -val KEYSTORE_FILE = rootProject.file("scripts/pslab.jks") -val GITHUB_BUILD = System.getenv("GITHUB_ACTIONS") == "true" && KEYSTORE_FILE.exists() - -android { - namespace = "io.pslab" - compileSdk = 34 - - defaultConfig { - applicationId = "io.pslab" - minSdk = 24 - targetSdk = 34 - versionCode = System.getenv("VERSION_CODE")?.toInt() ?: 1 - versionName = System.getenv("VERSION_NAME") ?: "1.0.0" - resConfigs("en", "ru", "ar", "si", "pl") - } - - signingConfigs { - if (GITHUB_BUILD) { - register("release") { - storeFile = KEYSTORE_FILE - storePassword = System.getenv("STORE_PASS") - keyAlias = System.getenv("ALIAS") - keyPassword = System.getenv("KEY_PASS") - } - } - } - - buildTypes { - debug { - versionNameSuffix = "Version: " - resValue("string", "version", "${versionNameSuffix}${defaultConfig.versionName}") - } - release { - isMinifyEnabled = false - proguardFiles( - getDefaultProguardFile("proguard-android.txt"), - "proguard-rules.pro" - ) - resValue("string", "version", "${defaultConfig.versionName}") - signingConfig = if (GITHUB_BUILD) signingConfigs.getByName("release") else null - } - } - lint { - abortOnError = false - } - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - buildFeatures { - buildConfig = true - } -} - - -dependencies { - - // Android stock libraries - implementation("androidx.appcompat:appcompat:1.7.0") - implementation("androidx.cardview:cardview:1.0.0") - implementation("androidx.recyclerview:recyclerview:1.3.2") - implementation("com.google.android.material:material:1.12.0") - implementation("androidx.preference:preference:1.2.1") - implementation("androidx.browser:browser:1.8.0") - implementation("androidx.constraintlayout:constraintlayout:2.1.4") - - // Custom tools libraries - implementation("com.github.PhilJay:MPAndroidChart:v3.1.0") - implementation("com.github.bmelnychuk:atv:1.2.9") - implementation("de.hdodenhof:circleimageview:3.1.0") - implementation("com.github.devlight:navigationtabstrip:1.0.4") - implementation("com.afollestad.material-dialogs", "commons", "0.9.6.0") - implementation("com.github.mik3y:usb-serial-for-android:3.7.3") - implementation("com.github.medyo:android-about-page:1.3") - implementation("com.github.tiagohm.MarkdownView:library:0.19.0") - implementation("com.github.mirrajabi:search-dialog:1.2.4") - implementation(files("../libs/croller-release.aar")) - implementation("com.github.BeppiMenozzi:Knob:1.9.0") - implementation("com.github.warkiz:IndicatorSeekBar:v2.1.1") - implementation("com.github.Vatican-Cameos:CarouselPicker:1.2") - implementation("com.github.anastr:speedviewlib:1.6.1") - implementation("com.github.GoodieBag:ProtractorView:v1.2") - implementation("com.github.Triggertrap:SeekArc:v1.1") - - // Apache commons - implementation("org.apache.commons:commons-math3:3.6.1") - implementation("org.apache.commons:commons-lang3:3.14.0") - - // Picasso - implementation("com.squareup.picasso:picasso:2.71828") - - // OKHTTP - implementation("com.squareup.okhttp3:okhttp:4.12.0") - - // ButterKnife - val butterKnifeVersion = "10.2.3" - annotationProcessor("com.jakewharton:butterknife-compiler:$butterKnifeVersion") - implementation("com.jakewharton:butterknife:$butterKnifeVersion") - - // Map libraries - implementation("org.osmdroid:osmdroid-android:6.1.18") - implementation("org.osmdroid:osmdroid-mapsforge:6.1.18") - implementation("org.osmdroid:osmdroid-geopackage:6.1.18") { - exclude("org.osmdroid.gpkg") - exclude("ormlite-core") - exclude("com.j256.ormlite") - } - - // Realm - implementation("com.github.realm:realm-android-adapters:v4.0.0") - - // OSS license plugin - implementation("com.google.android.gms:play-services-oss-licenses:17.1.0") - -} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro deleted file mode 100644 index 5bb1f14fc..000000000 --- a/app/proguard-rules.pro +++ /dev/null @@ -1,25 +0,0 @@ -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in /home/viveksb007/Android/Sdk/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle.kts. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml deleted file mode 100644 index 494df111f..000000000 --- a/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/assets/fonts/digital-7 (italic).ttf b/app/src/main/assets/fonts/digital-7 (italic).ttf deleted file mode 100644 index c120ab456..000000000 Binary files a/app/src/main/assets/fonts/digital-7 (italic).ttf and /dev/null differ diff --git a/app/src/main/java/io/pslab/CheckBoxGetter.java b/app/src/main/java/io/pslab/CheckBoxGetter.java deleted file mode 100644 index d79dec077..000000000 --- a/app/src/main/java/io/pslab/CheckBoxGetter.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.pslab; - -import java.io.Serializable; - -public class CheckBoxGetter implements Serializable { - - private String name; - private boolean isSelected; - - public CheckBoxGetter(String name, boolean isSelected) { - this.name = name; - this.isSelected = isSelected; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public boolean isSelected() { - return isSelected; - } - - public void setSelected(boolean selected) { - isSelected = selected; - } -} diff --git a/app/src/main/java/io/pslab/DataFormatter.java b/app/src/main/java/io/pslab/DataFormatter.java deleted file mode 100644 index 255d7fe13..000000000 --- a/app/src/main/java/io/pslab/DataFormatter.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.pslab; - -import java.text.DecimalFormatSymbols; -import java.util.Locale; - -public class DataFormatter { - public static final String HIGH_PRECISION_FORMAT = "%.5f"; - public static final String MEDIUM_PRECISION_FORMAT = "%.4f"; - public static final String LOW_PRECISION_FORMAT = "%.2f"; - public static final String MINIMAL_PRECISION_FORMAT = "%.1f"; - - public static final char decSeparator = DecimalFormatSymbols.getInstance().getDecimalSeparator(); - - public static String formatDouble(double value, String format) { - return String.format(Locale.ROOT, format, value); - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/InputMinMaxFilter.java b/app/src/main/java/io/pslab/InputMinMaxFilter.java deleted file mode 100644 index ee2bfe74f..000000000 --- a/app/src/main/java/io/pslab/InputMinMaxFilter.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.pslab; - -import android.text.InputFilter; -import android.text.Spanned; - -public class InputMinMaxFilter implements InputFilter { - - private int min; - private int max; - - public InputMinMaxFilter(int min, int max) { - this.min = min; - this.max = max; - } - public InputMinMaxFilter(String min, String max) { - this.min = Integer.parseInt(min); - this.max = Integer.parseInt(max); - } - private boolean isInRange(int a, int b, int c) { - return b > a ? c >= a && c <= b : c >= b && c <= a; - } - @Override - public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { - try { - String newVal = dest.toString().substring(0, dstart) + dest.toString().substring(dend, dest.toString().length()); - newVal = newVal.substring(0, dstart) + source.toString() + newVal.substring(dstart, newVal.length()); - int input = Integer.parseInt(newVal); - if (newVal.length() >= 4) - return ""; - if (isInRange(min, max, input)) - return null; - } catch (NumberFormatException nfe) { - } - return ""; - } -} diff --git a/app/src/main/java/io/pslab/PSLabApplication.java b/app/src/main/java/io/pslab/PSLabApplication.java deleted file mode 100644 index 7c80ccd66..000000000 --- a/app/src/main/java/io/pslab/PSLabApplication.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.pslab; - -import android.app.Application; - -import io.realm.Realm; -import io.realm.RealmConfiguration; - -/** - * Created by viveksb007 on 4/8/17. - */ - -public class PSLabApplication extends Application { - - @Override - public void onCreate() { - super.onCreate(); - Realm.init(this); - RealmConfiguration.Builder v = new RealmConfiguration.Builder().name(Realm.DEFAULT_REALM_NAME) - .schemaVersion(0) - .deleteRealmIfMigrationNeeded(); - Realm.setDefaultConfiguration(v.build()); - } -} diff --git a/app/src/main/java/io/pslab/SearchModel.java b/app/src/main/java/io/pslab/SearchModel.java deleted file mode 100644 index 2fd0bc717..000000000 --- a/app/src/main/java/io/pslab/SearchModel.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.pslab; - -import ir.mirrajabi.searchdialog.core.Searchable; - -/** - * Created by Harsh on 07-05-2018. - */ - -public class SearchModel implements Searchable { - - private String mTitle; - - public SearchModel(String mTitle) { - this.mTitle = mTitle; - } - - public void setTitle(String mTitle) { - this.mTitle = mTitle; - } - - @Override - public String getTitle() { - return mTitle; - } -} diff --git a/app/src/main/java/io/pslab/activity/AccelerometerActivity.java b/app/src/main/java/io/pslab/activity/AccelerometerActivity.java deleted file mode 100644 index 09ea4cce6..000000000 --- a/app/src/main/java/io/pslab/activity/AccelerometerActivity.java +++ /dev/null @@ -1,139 +0,0 @@ -package io.pslab.activity; - -import android.content.SharedPreferences; -import android.hardware.Sensor; -import android.hardware.SensorManager; - -import androidx.appcompat.app.ActionBar; -import androidx.fragment.app.Fragment; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.fragment.AccelerometerDataFragment; -import io.pslab.fragment.AccelerometerSettingsFragment; -import io.pslab.models.AccelerometerData; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.LocalDataLog; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class AccelerometerActivity extends PSLabSensor { - - private static final String PREF_NAME = "customDialogPreference"; - public final String ACCELEROMETER_LIMIT = "accelerometer_limit"; - public RealmResults recordedAccelerometerData; - - @Override - public int getMenu() { - return R.menu.sensor_data_log_menu; - } - - @Override - public SharedPreferences getStateSettings() { - return this.getSharedPreferences(PREF_NAME, MODE_PRIVATE); - } - - @Override - public String getFirstTimeSettingID() { - return "AccelerometerFirstTime"; - } - - @Override - public String getSensorName() { - return getResources().getString(R.string.accelerometer); - } - - @Override - public int getGuideTitle() { - return R.string.accelerometer; - } - - @Override - public int getGuideAbstract() { - return R.string.accelerometer_intro; - } - - - @Override - public int getGuideSchematics() { - return R.drawable.bh1750_schematic; - } - - @Override - public int getGuideDescription() { - return R.string.accelerometer_description_text; - } - - @Override - public int getGuideExtraContent() { - return 0; - } - - @Override - public void recordSensorDataBlockID(SensorDataBlock categoryData) { - realm.beginTransaction(); - realm.copyToRealm(categoryData); - realm.commitTransaction(); - } - - @Override - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((AccelerometerData) sensorData); - realm.commitTransaction(); - } - - @Override - public void stopRecordSensorData() { - LocalDataLog.with().refresh(); - } - - @Override - public Fragment getSensorFragment() { - return AccelerometerDataFragment.newInstance(); - } - - @Override - public void getDataFromDataLogger() { - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - //playingData = true; - viewingData = true; - recordedAccelerometerData = LocalDataLog.with() - .getBlockOfAccelerometerRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - final AccelerometerData data = recordedAccelerometerData.get(0); - if (data != null) { - final String title = titleFormat.format(data.getTime()); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(title); - } - } - } - } - - @Override - public boolean sensorFound() { - SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); - return sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null; - } - - /** - * Once settings have been changed, those changes can be captured from onResume method. - */ - @Override - protected void onResume() { - super.onResume(); - reinstateConfigurations(); - } - - private void reinstateConfigurations() { - SharedPreferences accelerometerConfigurations; - accelerometerConfigurations = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - locationEnabled = accelerometerConfigurations.getBoolean(AccelerometerSettingsFragment.KEY_INCLUDE_LOCATION, true); - AccelerometerDataFragment.setParameters( - Float.valueOf(accelerometerConfigurations.getString(AccelerometerSettingsFragment.KEY_HIGH_LIMIT, "20")), - Integer.valueOf(accelerometerConfigurations.getString(AccelerometerSettingsFragment.KEY_UPDATE_PERIOD, "1000")), - accelerometerConfigurations.getString(AccelerometerSettingsFragment.KEY_ACCELEROMETER_SENSOR_GAIN, "1")); - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/activity/BarometerActivity.java b/app/src/main/java/io/pslab/activity/BarometerActivity.java deleted file mode 100644 index 53cb6e11a..000000000 --- a/app/src/main/java/io/pslab/activity/BarometerActivity.java +++ /dev/null @@ -1,138 +0,0 @@ -package io.pslab.activity; - -import android.content.SharedPreferences; -import android.hardware.Sensor; -import android.hardware.SensorManager; - -import androidx.appcompat.app.ActionBar; -import androidx.fragment.app.Fragment; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.fragment.BaroMeterDataFragment; -import io.pslab.fragment.BaroMeterSettingsFragment; -import io.pslab.models.BaroData; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.LocalDataLog; -import io.realm.RealmObject; -import io.realm.RealmResults; - -/** - * Created by Padmal on 12/13/18. - */ - -public class BarometerActivity extends PSLabSensor { - - private static final String PREF_NAME = "customDialogPreference"; - public final String BAROMETER_LIMIT = "barometer_limit"; - public RealmResults recordedBaroData; - - @Override - public int getMenu() { - return R.menu.sensor_data_log_menu; - } - - @Override - public SharedPreferences getStateSettings() { - return this.getSharedPreferences(PREF_NAME, MODE_PRIVATE); - } - - @Override - public String getFirstTimeSettingID() { - return "BaroMeterFirstTime"; - } - - @Override - public String getSensorName() { - return getResources().getString(R.string.baro_meter); - } - - @Override - public int getGuideTitle() { - return R.string.baro_meter; - } - - @Override - public int getGuideAbstract() { - return R.string.baro_meter_intro; - } - - @Override - public int getGuideSchematics() { - return R.drawable.bmp180_schematic; - } - - @Override - public int getGuideDescription() { - return R.string.baro_meter_desc; - } - - @Override - public int getGuideExtraContent() { - return 0; - } - - @Override - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - @Override - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((BaroData) sensorData); - realm.commitTransaction(); - } - - @Override - public void stopRecordSensorData() { - LocalDataLog.with().refresh(); - } - - @Override - public Fragment getSensorFragment() { - return BaroMeterDataFragment.newInstance(); - } - - @Override - public void getDataFromDataLogger() { - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - viewingData = true; - recordedBaroData = LocalDataLog.with() - .getBlockOfBaroRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - final BaroData data = recordedBaroData.get(0); - if (data != null) { - final String title = titleFormat.format(data.getTime()); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(title); - } - } - } - } - - @Override - public boolean sensorFound() { - SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); - return sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) != null; - } - - @Override - protected void onResume() { - super.onResume(); - reinstateConfigurations(); - } - - private void reinstateConfigurations() { - SharedPreferences BaroMeterConfigurations; - BaroMeterConfigurations = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - locationEnabled = BaroMeterConfigurations.getBoolean(BaroMeterSettingsFragment.KEY_INCLUDE_LOCATION, true); - BaroMeterDataFragment.setParameters( - Float.valueOf(BaroMeterConfigurations.getString(BaroMeterSettingsFragment.KEY_HIGH_LIMIT, "1.1")), - Integer.valueOf(BaroMeterConfigurations.getString(BaroMeterSettingsFragment.KEY_UPDATE_PERIOD, "1000")), - BaroMeterConfigurations.getString(BaroMeterSettingsFragment.KEY_BARO_SENSOR_TYPE, "0")); - } -} diff --git a/app/src/main/java/io/pslab/activity/CompassActivity.java b/app/src/main/java/io/pslab/activity/CompassActivity.java deleted file mode 100644 index f041fb8cb..000000000 --- a/app/src/main/java/io/pslab/activity/CompassActivity.java +++ /dev/null @@ -1,132 +0,0 @@ -package io.pslab.activity; - -import android.content.SharedPreferences; -import android.hardware.Sensor; -import android.hardware.SensorManager; - -import androidx.appcompat.app.ActionBar; -import androidx.fragment.app.Fragment; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.fragment.CompassDataFragment; -import io.pslab.fragment.CompassSettingsFragment; -import io.pslab.models.CompassData; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.LocalDataLog; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class CompassActivity extends PSLabSensor { - - private static final String PREF_NAME = "customDialogPreference"; - public RealmResults recordedCompassData; - - - @Override - public int getMenu() { - return R.menu.sensor_data_log_menu; - } - - @Override - public SharedPreferences getStateSettings() { - return this.getSharedPreferences(PREF_NAME, MODE_PRIVATE); - } - - @Override - public String getFirstTimeSettingID() { - return "CompassFirstTime"; - } - - @Override - public String getSensorName() { - return getResources().getString(R.string.compass); - } - - @Override - public int getGuideTitle() { - return R.string.compass_bottom_sheet_heading; - } - - @Override - public int getGuideAbstract() { - return R.string.compass_bottom_sheet_text; - } - - @Override - public int getGuideSchematics() { - return R.drawable.find_mobile_axis; - } - - @Override - public int getGuideDescription() { - return R.string.compass_description; - } - - @Override - public int getGuideExtraContent() { - return 0; - } - - @Override - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - @Override - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((CompassData) sensorData); - realm.commitTransaction(); - } - - @Override - public void stopRecordSensorData() { - LocalDataLog.with().refresh(); - } - - @Override - public Fragment getSensorFragment() { - return CompassDataFragment.newInstance(); - } - - @Override - public void getDataFromDataLogger() { - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - viewingData = true; - recordedCompassData = LocalDataLog.with() - .getBlockOfCompassRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - final CompassData data = recordedCompassData.get(0); - if (data != null) { - final String title = titleFormat.format(data.getTime()); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(title); - } - } - } - } - - @Override - public boolean sensorFound() { - SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); - return sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION) != null; - } - - @Override - protected void onResume() { - super.onResume(); - reinstateConfigurations(); - } - - private void reinstateConfigurations() { - SharedPreferences compassConfigurations; - compassConfigurations = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - locationEnabled = compassConfigurations.getBoolean(CompassSettingsFragment.KEY_INCLUDE_LOCATION, true); - CompassDataFragment.setParameters( - compassConfigurations.getString(CompassSettingsFragment.KEY_COMPASS_SENSOR_TYPE, "0")); - } -} diff --git a/app/src/main/java/io/pslab/activity/ControlActivity.java b/app/src/main/java/io/pslab/activity/ControlActivity.java deleted file mode 100644 index 31635dd25..000000000 --- a/app/src/main/java/io/pslab/activity/ControlActivity.java +++ /dev/null @@ -1,73 +0,0 @@ -package io.pslab.activity; - -import android.os.Bundle; -import android.view.MenuItem; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentTransaction; - -import com.google.android.material.bottomnavigation.BottomNavigationView; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.pslab.R; -import io.pslab.fragment.ControlFragmentAdvanced; -import io.pslab.fragment.ControlFragmentMain; -import io.pslab.fragment.ControlFragmentRead; -import io.pslab.others.ControlActivityCommon; - -public class ControlActivity extends AppCompatActivity { - ControlActivityCommon common = new ControlActivityCommon(); - @BindView(R.id.navigation) - BottomNavigationView bottomNavigationView; - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_control); - ButterKnife.bind(this); - - bottomNavigationView.setOnNavigationItemSelectedListener - (new BottomNavigationView.OnNavigationItemSelectedListener() { - @Override - public boolean onNavigationItemSelected(@NonNull MenuItem item) { - Fragment selectedFragment = null; - Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame_layout_control); - - switch (item.getItemId()) { - case R.id.action_item1: - if (!(fragment instanceof ControlFragmentMain)) - selectedFragment = ControlFragmentMain.newInstance(); - break; - case R.id.action_item2: - if (!(fragment instanceof ControlFragmentRead)) - selectedFragment = ControlFragmentRead.newInstance(); - break; - case R.id.action_item3: - if (!(fragment instanceof ControlFragmentAdvanced)) - selectedFragment = ControlFragmentAdvanced.newInstance(); - break; - } - if (selectedFragment != null) { - FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); - transaction.replace(R.id.frame_layout_control, selectedFragment); - transaction.commit(); - } - return true; - } - }); - - FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); - transaction.replace(R.id.frame_layout_control, ControlFragmentMain.newInstance()); - transaction.commit(); - } - - @Override - public void onBackPressed() { - ControlActivityCommon.editTextValues = null; - finish(); - } -} diff --git a/app/src/main/java/io/pslab/activity/CreateConfigActivity.java b/app/src/main/java/io/pslab/activity/CreateConfigActivity.java deleted file mode 100644 index 388692c5b..000000000 --- a/app/src/main/java/io/pslab/activity/CreateConfigActivity.java +++ /dev/null @@ -1,204 +0,0 @@ -package io.pslab.activity; - -import android.os.Bundle; -import android.os.Environment; -import android.view.MenuItem; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.EditText; -import android.widget.Spinner; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import com.google.android.material.snackbar.Snackbar; - -import org.apache.commons.lang3.StringUtils; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.pslab.CheckBoxGetter; -import io.pslab.R; -import io.pslab.adapters.CheckBoxAdapter; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; - -public class CreateConfigActivity extends AppCompatActivity { - - private ArrayList instrumentsList; - private ArrayList instrumentParamsList; - private ArrayList instrumentParamsListTitles; - private int selectedItem = 0; - private String intervalUnit = "sec"; - private EditText intervalEditText; - private String interval; - private View rootView; - private RecyclerView paramsListContainer; - private List list; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_create_config); - Toolbar toolbar = findViewById(R.id.toolbar); - rootView = findViewById(R.id.create_config_root_view); - paramsListContainer = findViewById(R.id.params_list_container); - Spinner selectInstrumentSpinner = findViewById(R.id.select_instrument_spinner); - Spinner intervalUnitSpinner = findViewById(R.id.interval_unit_spinner); - intervalEditText = findViewById(R.id.interval_edit_text); - Button createConfigFileBtn = findViewById(R.id.create_config_btn); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.nav_config); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - instrumentsList = new ArrayList<>(); - instrumentParamsList = new ArrayList<>(); - instrumentParamsListTitles = new ArrayList<>(); - paramsListContainer.setLayoutManager(new LinearLayoutManager(this)); - list = new ArrayList<>(); - createArrayLists(); - selectInstrumentSpinner.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, instrumentsList)); - selectInstrumentSpinner.setSelection(0, true); - createCheckboxList(); - selectInstrumentSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - selectedItem = position; - createCheckboxList(); - } - - @Override - public void onNothingSelected(AdapterView parent) { - selectedItem = 0; - } - }); - - intervalUnitSpinner.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.interval_units))); - intervalUnitSpinner.setSelection(0, true); - intervalUnitSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - intervalUnit = (String) parent.getItemAtPosition(position); - } - - @Override - public void onNothingSelected(AdapterView parent) { - intervalUnit = "sec"; - } - }); - - createConfigFileBtn.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - interval = intervalEditText.getText().toString(); - if (interval.length() == 0) { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.no_interval_message), null, null, Snackbar.LENGTH_SHORT); - } else { - ArrayList selectedParamsList = new ArrayList<>(); - for (int i = 0; i < paramsListContainer.getChildCount(); i++) { - boolean checkBox = list.get(i).isSelected(); - if (checkBox) { - selectedParamsList.add(instrumentParamsList.get(selectedItem)[i]); - } - } - createConfigFile(selectedParamsList); - } - } - }); - } - - private void createArrayLists() { - - instrumentParamsList.add(getResources().getStringArray(R.array.oscilloscope_params)); - instrumentParamsList.add(getResources().getStringArray(R.array.multimeter_params)); - instrumentParamsList.add(getResources().getStringArray(R.array.logic_analyzer_params)); - instrumentParamsList.add(getResources().getStringArray(R.array.barometer_params)); - instrumentParamsList.add(getResources().getStringArray(R.array.luxmeter_params)); - instrumentParamsList.add(getResources().getStringArray(R.array.accelerometer_params)); - - instrumentParamsListTitles.add(getResources().getStringArray(R.array.oscilloscope_params_title)); - instrumentParamsListTitles.add(getResources().getStringArray(R.array.multimeter_params_title)); - instrumentParamsListTitles.add(getResources().getStringArray(R.array.logic_analyzer_params_title)); - instrumentParamsListTitles.add(getResources().getStringArray(R.array.barometer_params)); - instrumentParamsListTitles.add(getResources().getStringArray(R.array.luxmeter_params)); - instrumentParamsListTitles.add(getResources().getStringArray(R.array.accelerometer_params_title)); - - instrumentsList.add(getResources().getString(R.string.oscilloscope)); - instrumentsList.add(getResources().getString(R.string.multimeter)); - instrumentsList.add(getResources().getString(R.string.logical_analyzer)); - instrumentsList.add(getResources().getString(R.string.baro_meter)); - instrumentsList.add(getResources().getString(R.string.lux_meter)); - instrumentsList.add(getResources().getString(R.string.accelerometer)); - } - - private void createCheckboxList() { - list.clear(); - String[] params = instrumentParamsListTitles.get(selectedItem); - for (int i = 0; i < params.length; i++) { - CheckBoxGetter check = new CheckBoxGetter(params[i], false); - list.add(check); - } - CheckBoxAdapter box; - box = new CheckBoxAdapter(CreateConfigActivity.this, list); - paramsListContainer.setAdapter(box); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return super.onOptionsItemSelected(item); - } - - private void createConfigFile(ArrayList params) { - String instrumentName = instrumentsList.get(selectedItem); - String fileName = "pslab_config.txt"; - String basepath = Environment.getExternalStorageDirectory().getAbsolutePath(); - - File baseDirectory = new File(basepath + File.separator + CSVLogger.CSV_DIRECTORY); - if (!baseDirectory.exists()) { - try { - baseDirectory.mkdir(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - File configFile = new File(basepath + File.separator + CSVLogger.CSV_DIRECTORY + File.separator + fileName); - if (!configFile.exists()) { - try { - configFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - try { - FileWriter writer = new FileWriter(configFile); - writer.write("instrument: " + instrumentName + "\n"); - writer.write("interval: " + interval + " " + intervalUnit + "\n"); - String param = StringUtils.join(",", params); - writer.write("params: " + param); - writer.flush(); - writer.close(); - CustomSnackBar.showSnackBar(rootView, getString(R.string.file_created_success_message), null, null, Snackbar.LENGTH_SHORT); - } catch (IOException e) { - e.printStackTrace(); - CustomSnackBar.showSnackBar(rootView, getString(R.string.file_created_fail_message), null, null, Snackbar.LENGTH_SHORT); - } - - } -} diff --git a/app/src/main/java/io/pslab/activity/DataLoggerActivity.java b/app/src/main/java/io/pslab/activity/DataLoggerActivity.java deleted file mode 100644 index 7598de8b8..000000000 --- a/app/src/main/java/io/pslab/activity/DataLoggerActivity.java +++ /dev/null @@ -1,356 +0,0 @@ -package io.pslab.activity; - -import android.content.Context; -import android.content.Intent; -import android.net.Uri; -import android.os.AsyncTask; -import android.os.Bundle; -import android.os.Environment; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.ProgressBar; -import android.widget.TextView; - -import androidx.annotation.Nullable; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AlertDialog; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; -import androidx.recyclerview.widget.DividerItemDecoration; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import com.google.android.material.snackbar.Snackbar; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.pslab.R; -import io.pslab.adapters.SensorLoggerListAdapter; -import io.pslab.models.AccelerometerData; -import io.pslab.models.BaroData; -import io.pslab.models.CompassData; -import io.pslab.models.GasSensorData; -import io.pslab.models.GyroData; -import io.pslab.models.LogicAnalyzerData; -import io.pslab.models.LuxData; -import io.pslab.models.OscilloscopeData; -import io.pslab.models.PowerSourceData; -import io.pslab.models.SensorDataBlock; -import io.pslab.models.ServoData; -import io.pslab.models.ThermometerData; -import io.pslab.models.WaveGeneratorData; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.LocalDataLog; -import io.realm.OrderedCollectionChangeSet; -import io.realm.OrderedRealmCollectionChangeListener; -import io.realm.Realm; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class DataLoggerActivity extends AppCompatActivity { - - public static final String CALLER_ACTIVITY = "Caller"; - - @BindView(R.id.recycler_view) - RecyclerView recyclerView; - @BindView(R.id.data_logger_blank_view) - TextView blankView; - @BindView(R.id.toolbar) - Toolbar toolbar; - - private ProgressBar deleteAllProgressBar; - private RealmResults categoryData; - private String selectedDevice = null; - private Realm realm; - private String caller; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_data_logger); - ButterKnife.bind(this); - setSupportActionBar(toolbar); - deleteAllProgressBar = findViewById(R.id.delete_all_progbar); - deleteAllProgressBar.setVisibility(View.GONE); - realm = LocalDataLog.with().getRealm(); - caller = getIntent().getStringExtra(CALLER_ACTIVITY); - if (caller == null) { - caller = getResources().getString(R.string.logged_data); - } - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - actionBar.setTitle(caller); - } - - setCategoryData(); - fillData(); - } - - private void setCategoryData() { - switch (caller) { - case "Lux Meter": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getString(R.string.lux_meter)); - break; - case "Barometer": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getString(R.string.baro_meter)); - break; - case "Accelerometer": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getString(R.string.accelerometer)); - break; - case "Multimeter": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getString(R.string.multimeter)); - break; - case "Gyroscope": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getString(R.string.gyroscope)); - break; - case "Compass": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getString(R.string.compass)); - break; - case "Thermometer": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getString(R.string.thermometer)); - break; - case "Robotic Arm": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getString(R.string.robotic_arm)); - break; - case "Wave Generator": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getResources().getString(R.string.wave_generator)); - break; - case "Oscilloscope": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getResources().getString(R.string.oscilloscope)); - break; - case "Power Source": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getResources().getString(R.string.power_source)); - break; - case "Logic Analyzer": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getResources().getString(R.string.logical_analyzer)); - break; - case "Gas Sensor": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getString(R.string.gas_sensor)); - break; - case "Dust Sensor": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getString(R.string.dust_sensor)); - break; - case "Sound Meter": - categoryData = LocalDataLog.with().getTypeOfSensorBlocks(getString(R.string.sound_meter)); - break; - default: - categoryData = LocalDataLog.with().getAllSensorBlocks(); - } - fillData(); - categoryData.addChangeListener(new OrderedRealmCollectionChangeListener>() { - @Override - public void onChange(RealmResults sensorDataBlocks, OrderedCollectionChangeSet changeSet) { - if (categoryData.size() == 0) { - DataLoggerActivity.this.toolbar.getMenu().findItem(R.id.delete_all).setVisible(false); - } - } - }); - } - - private void fillData() { - if (categoryData.size() > 0) { - blankView.setVisibility(View.GONE); - SensorLoggerListAdapter adapter = new SensorLoggerListAdapter(categoryData, this); - LinearLayoutManager linearLayoutManager = new LinearLayoutManager( - this, LinearLayoutManager.VERTICAL, false); - recyclerView.setLayoutManager(linearLayoutManager); - DividerItemDecoration itemDecor = new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL); - recyclerView.addItemDecoration(itemDecor); - recyclerView.setAdapter(adapter); - } else { - recyclerView.setVisibility(View.GONE); - blankView.setVisibility(View.VISIBLE); - } - } - - @Override - public void onBackPressed() { - finish(); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - finish(); - break; - case R.id.action_import_log: - selectFile(); - break; - case R.id.delete_all: - displayAlertDialog(DataLoggerActivity.this); - break; - } - return super.onOptionsItemSelected(item); - } - - private void displayAlertDialog(Context context) { - new AlertDialog.Builder(context) - .setTitle(context.getString(R.string.delete)) - .setMessage(context.getString(R.string.delete_all_message)) - .setPositiveButton(context.getString(R.string.delete), (dialog, which) -> { - deleteAllProgressBar.setVisibility(View.VISIBLE); - new DeleteAllTask().execute(); - }).setNegativeButton(context.getString(R.string.cancel), (dialog, which) -> dialog.dismiss()).create().show(); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.log_activity_menu, menu); - menu.findItem(R.id.delete_all).setVisible(categoryData.size() > 0); - return super.onCreateOptionsMenu(menu); - } - - private void selectFile() { - Intent intent = new Intent(Intent.ACTION_GET_CONTENT); - intent.setType("*/*"); - startActivityForResult(intent, 100); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if (requestCode == 100) { - if (resultCode == RESULT_OK && data != null) { - Uri uri = data.getData(); - String path = uri.getPath(); - path = path.replace("/root_path/", "/"); - File file = new File(path); - getFileData(file); - } else - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.no_file_selected), null, null, Snackbar.LENGTH_SHORT); - } - } - - private void getFileData(File file) { - try { - FileInputStream is = new FileInputStream(file); - BufferedReader reader = new BufferedReader(new InputStreamReader(is)); - String line = reader.readLine(); - int i = 0; - long block = 0, time = 0; - while (line != null) { - if (i > 1) { - String[] data = line.split(","); - try { - time += 1000; - realm.beginTransaction(); - RealmObject object = getObject(selectedDevice, data, time, block); - if (object != null) { - realm.copyToRealm(object); - } else { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.incorrect_import_format), null, null, Snackbar.LENGTH_SHORT); - } - realm.commitTransaction(); - } catch (Exception e) { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.incorrect_import_format), null, null, Snackbar.LENGTH_SHORT); - } - } else if (i == 0) { - block = System.currentTimeMillis(); - time = block; - selectedDevice = line.split(",")[0]; - realm.beginTransaction(); - realm.copyToRealm(new SensorDataBlock(block, selectedDevice)); - realm.commitTransaction(); - } - i++; - line = reader.readLine(); - } - fillData(); - DataLoggerActivity.this.toolbar.getMenu().findItem(R.id.delete_all).setVisible(true); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private RealmObject getObject(String objectType, String[] data, long time, long block) { - RealmObject returnObject = null; - switch (objectType) { - case "Lux Meter": - returnObject = new LuxData(time, block, Float.valueOf(data[2]), Double.valueOf(data[3]), Double.valueOf(data[4])); - break; - case "Barometer": - returnObject = new BaroData(time, block, Float.valueOf(data[2]), Float.valueOf(data[3]), Double.valueOf(data[4]), Double.valueOf(data[5])); - break; - case "Accelerometer": - returnObject = new AccelerometerData(time, block, Float.valueOf(data[2]), Float.valueOf(data[3]), Float.valueOf(data[4]), Double.valueOf(data[5]), Double.valueOf(data[6])); - break; - case "Gyroscope": - returnObject = new GyroData(time, block, Float.valueOf(data[2]), Float.valueOf(data[3]), Float.valueOf(data[4]), Double.valueOf(data[5]), Double.valueOf(data[6])); - break; - case "Compass": - returnObject = new CompassData(time, block, data[2].equals("null") ? 0f : Float.valueOf(data[2]), data[3].equals("null") ? 0f : Float.valueOf(data[3]), data[4].equals("null") ? 0f : Float.valueOf(data[4]), data[5], Double.valueOf(data[6]), Double.valueOf(data[7])); - break; - case "Thermometer": - returnObject = new ThermometerData(time, block, Float.valueOf(data[2]), Double.valueOf(data[5]), Double.valueOf(data[6])); - break; - case "Robotic Arm": - returnObject = new ServoData(time, block, data[2], data[3], data[4], data[5], Float.valueOf(data[6]), Float.valueOf(data[7])); - break; - case "Wave Generator": - returnObject = new WaveGeneratorData(time, block, data[2], data[3], data[4], data[5], data[6], data[7], Float.valueOf(data[8]), Float.valueOf(data[9])); - break; - case "Oscilloscope": - returnObject = new OscilloscopeData(time, block, Integer.valueOf(data[2]), data[3], data[4], data[5], Float.valueOf(data[6]), Float.valueOf(data[7]), Float.valueOf(data[8])); - break; - case "Power Source": - returnObject = new PowerSourceData(time, block, Float.valueOf(data[2]), Float.valueOf(data[3]), Float.valueOf(data[4]), Float.valueOf(data[5]), Float.valueOf(data[6]), Float.valueOf(data[7])); - break; - case "Logic Analyzer": - returnObject = new LogicAnalyzerData(time, block, data[2], Integer.valueOf(data[3]), data[4], data[5], Float.valueOf(data[6]), Float.valueOf(data[7])); - break; - case "Gas Sensor": - returnObject = new GasSensorData(time, block, Float.valueOf(data[2]), Double.valueOf(data[3]), Double.valueOf(data[4])); - break; - default: - returnObject = null; - break; - } - return returnObject; - } - - private class DeleteAllTask extends AsyncTask { - @Override - protected Void doInBackground(Void... voids) { - Realm realm = Realm.getDefaultInstance(); - for (SensorDataBlock data : realm.where(SensorDataBlock.class) - .findAll()) { - File logDirectory = new File( - Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSVLogger.CSV_DIRECTORY + - File.separator + data.getSensorType() + - File.separator + CSVLogger.FILE_NAME_FORMAT.format(data.getBlock()) + ".csv"); - logDirectory.delete(); - realm.beginTransaction(); - realm.where(SensorDataBlock.class) - .equalTo("block", data.getBlock()) - .findFirst().deleteFromRealm(); - realm.commitTransaction(); - } - realm.close(); - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - deleteAllProgressBar.setVisibility(View.GONE); - if (LocalDataLog.with().getAllSensorBlocks().size() <= 0) { - blankView.setVisibility(View.VISIBLE); - } - DataLoggerActivity.this.toolbar.getMenu().findItem(R.id.delete_all).setVisible(false); - } - } -} diff --git a/app/src/main/java/io/pslab/activity/DustSensorActivity.java b/app/src/main/java/io/pslab/activity/DustSensorActivity.java deleted file mode 100644 index bf0e3093c..000000000 --- a/app/src/main/java/io/pslab/activity/DustSensorActivity.java +++ /dev/null @@ -1,148 +0,0 @@ -package io.pslab.activity; - -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - -import androidx.appcompat.app.ActionBar; -import androidx.fragment.app.Fragment; - -import io.pslab.R; -import io.pslab.fragment.DustSensorDataFragment; -import io.pslab.fragment.DustSensorSettingsFragment; -import io.pslab.models.DustSensorData; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.LocalDataLog; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class DustSensorActivity extends PSLabSensor { - - private static final String PREF_NAME = "customDialogPreference"; - public RealmResults recordedDustSensorData; - - @Override - public int getMenu() { - return R.menu.sensor_data_log_menu; - } - - @Override - public SharedPreferences getStateSettings() { - return this.getSharedPreferences(PREF_NAME, MODE_PRIVATE); - } - - @Override - public String getFirstTimeSettingID() { - return "DustSensorFirstTime"; - } - - @Override - public String getSensorName() { - return getResources().getString(R.string.dust_sensor); - } - - @Override - public int getGuideTitle() { - return R.string.dust_sensor; - } - - @Override - public int getGuideAbstract() { - return R.string.dust_sensor_intro; - } - - @Override - public int getGuideSchematics() { - return 0; - } - - @Override - public int getGuideDescription() { - return R.string.dust_sensor_desc; - } - - @Override - public int getGuideExtraContent() { - return 0; - } - - @Override - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - @Override - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((DustSensorData) sensorData); - realm.commitTransaction(); - } - - @Override - public void stopRecordSensorData() { - LocalDataLog.with().refresh(); - } - - @Override - public Fragment getSensorFragment() { - return DustSensorDataFragment.newInstance(); - } - - @Override - protected void onResume() { - super.onResume(); - reinstateConfigurations(); - } - - private void reinstateConfigurations() { - SharedPreferences luxMeterConfigurations; - luxMeterConfigurations = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - locationEnabled = luxMeterConfigurations.getBoolean(DustSensorSettingsFragment.KEY_INCLUDE_LOCATION, true); - DustSensorDataFragment.setParameters( - getValueFromText(luxMeterConfigurations.getString(DustSensorSettingsFragment.KEY_HIGH_LIMIT, "4.0"), - 0.0, 5.0), - getValueFromText(luxMeterConfigurations.getString(DustSensorSettingsFragment.KEY_UPDATE_PERIOD, "1000"), - 100, 1000), - luxMeterConfigurations.getString(DustSensorSettingsFragment.KEY_DUST_SENSOR_TYPE, "0")); - } - - private int getValueFromText(String strValue, int lowerBound, int upperBound) { - if (strValue.isEmpty()) return lowerBound; - int value = Integer.parseInt(strValue); - if (value > upperBound) return upperBound; - else if (value < lowerBound) return lowerBound; - else return value; - } - - private double getValueFromText(String strValue, double lowerBound, double upperBound) { - if (strValue.isEmpty()) return lowerBound; - double value = Double.parseDouble(strValue); - if (value > upperBound) return upperBound; - else if (value < lowerBound) return lowerBound; - else return value; - } - - @Override - public void getDataFromDataLogger() { - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - viewingData = true; - recordedDustSensorData = LocalDataLog.with() - .getBlockOfDustSensorRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - final DustSensorData data = recordedDustSensorData.get(0); - if (data != null) { - final String title = titleFormat.format(data.getTime()); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(title); - } - } - } - } - - @Override - public boolean sensorFound() { - return false; - } -} diff --git a/app/src/main/java/io/pslab/activity/GasSensorActivity.java b/app/src/main/java/io/pslab/activity/GasSensorActivity.java deleted file mode 100644 index 07f48d573..000000000 --- a/app/src/main/java/io/pslab/activity/GasSensorActivity.java +++ /dev/null @@ -1,113 +0,0 @@ -package io.pslab.activity; - -import android.content.SharedPreferences; - -import androidx.appcompat.app.ActionBar; -import androidx.fragment.app.Fragment; - -import io.pslab.R; -import io.pslab.fragment.GasSensorDataFragment; -import io.pslab.models.GasSensorData; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.LocalDataLog; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class GasSensorActivity extends PSLabSensor { - - private static final String PREF_NAME = "customDialogPreference"; - public RealmResults recordedGasSensorData; - - @Override - public int getMenu() { - return R.menu.sensor_data_log_menu; - } - - @Override - public SharedPreferences getStateSettings() { - return this.getSharedPreferences(PREF_NAME, MODE_PRIVATE); - - } - - @Override - public String getFirstTimeSettingID() { - return "GasSensorFirstTime"; - } - - @Override - public String getSensorName() { - return getResources().getString(R.string.gas_sensor); - } - - @Override - public int getGuideTitle() { - return R.string.gas_sensor; - } - - @Override - public int getGuideAbstract() { - return R.string.gas_sensor; - } - - @Override - public int getGuideSchematics() { - return R.drawable.bmp180_schematic; - } - - @Override - public int getGuideDescription() { - return R.string.gas_sensor; - } - - @Override - public int getGuideExtraContent() { - return 0; - } - - @Override - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - @Override - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((GasSensorData) sensorData); - realm.commitTransaction(); - } - - @Override - public void stopRecordSensorData() { - LocalDataLog.with().refresh(); - } - - @Override - public Fragment getSensorFragment() { - return GasSensorDataFragment.newInstance(); - } - - @Override - public void getDataFromDataLogger() { - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - viewingData = true; - recordedGasSensorData = LocalDataLog.with() - .getBlockOfGasSensorRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - final GasSensorData data = recordedGasSensorData.get(0); - if (data != null) { - final String title = titleFormat.format(data.getTime()); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(title); - } - } - } - } - - @Override - public boolean sensorFound() { - return false; - } -} diff --git a/app/src/main/java/io/pslab/activity/GyroscopeActivity.java b/app/src/main/java/io/pslab/activity/GyroscopeActivity.java deleted file mode 100644 index 17e949778..000000000 --- a/app/src/main/java/io/pslab/activity/GyroscopeActivity.java +++ /dev/null @@ -1,134 +0,0 @@ -package io.pslab.activity; - -import android.content.SharedPreferences; -import android.hardware.Sensor; -import android.hardware.SensorManager; - -import androidx.appcompat.app.ActionBar; -import androidx.fragment.app.Fragment; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.fragment.GyroscopeDataFragment; -import io.pslab.fragment.GyroscopeSettingsFragment; -import io.pslab.models.GyroData; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.LocalDataLog; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class GyroscopeActivity extends PSLabSensor { - - private static final String PREF_NAME = "customDialogPreference"; - public final String GYROSCOPE_LIMIT = "gyroscope_limit"; - public RealmResults recordedGyroData; - - @Override - public int getMenu() { - return R.menu.sensor_data_log_menu; - } - - @Override - public SharedPreferences getStateSettings() { - return this.getSharedPreferences(PREF_NAME, MODE_PRIVATE); - } - - @Override - public String getFirstTimeSettingID() { - return "GyroscopeFirstTime"; - } - - @Override - public String getSensorName() { - return getResources().getString(R.string.gyroscope); - } - - @Override - public int getGuideTitle() { - return R.string.gyroscope; - } - - @Override - public int getGuideAbstract() { - return R.string.gyroscope_intro; - } - - @Override - public int getGuideSchematics() { - return R.drawable.gyroscope_axes_orientation; - } - - @Override - public int getGuideDescription() { - return R.string.gyroscope_description_text; - } - - @Override - public int getGuideExtraContent() { - return 0; - } - - @Override - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - @Override - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((GyroData) sensorData); - realm.commitTransaction(); - } - - @Override - public void stopRecordSensorData() { - LocalDataLog.with().refresh(); - } - - @Override - public Fragment getSensorFragment() { - return GyroscopeDataFragment.newInstance(); - } - - @Override - public void getDataFromDataLogger() { - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - viewingData = true; - recordedGyroData = LocalDataLog.with() - .getBlockOfGyroRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - final GyroData data = recordedGyroData.get(0); - if (data != null) { - final String title = titleFormat.format(data.getTime()); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(title); - } - } - } - } - - @Override - public boolean sensorFound() { - SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); - return sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null; - } - - @Override - protected void onResume() { - super.onResume(); - reinstateConfigurations(); - } - - private void reinstateConfigurations() { - SharedPreferences gyroscopeConfigurations; - gyroscopeConfigurations = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - locationEnabled = gyroscopeConfigurations.getBoolean(GyroscopeSettingsFragment.KEY_INCLUDE_LOCATION, true); - GyroscopeDataFragment.setParameters( - Float.valueOf(gyroscopeConfigurations.getString(GyroscopeSettingsFragment.KEY_HIGH_LIMIT, "20")), - Integer.valueOf(gyroscopeConfigurations.getString(GyroscopeSettingsFragment.KEY_UPDATE_PERIOD, "1000")), - gyroscopeConfigurations.getString(GyroscopeSettingsFragment.KEY_GYROSCOPE_SENSOR_GAIN, "1")); - } -} diff --git a/app/src/main/java/io/pslab/activity/LogicalAnalyzerActivity.java b/app/src/main/java/io/pslab/activity/LogicalAnalyzerActivity.java deleted file mode 100644 index 70e4fed0a..000000000 --- a/app/src/main/java/io/pslab/activity/LogicalAnalyzerActivity.java +++ /dev/null @@ -1,149 +0,0 @@ -package io.pslab.activity; - -import android.annotation.SuppressLint; -import android.content.Intent; -import android.os.Bundle; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.Window; -import android.view.WindowManager; - -import androidx.annotation.Nullable; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.widget.Toolbar; - -import io.pslab.R; -import io.pslab.activity.guide.GuideActivity; -import io.pslab.fragment.LALogicLinesFragment; -import io.pslab.models.LogicAnalyzerData; -import io.pslab.others.LocalDataLog; -import io.realm.RealmResults; - -/** - * Created by viveksb007 on 10/5/17. - */ - -public class LogicalAnalyzerActivity extends GuideActivity { - - public static final String PREFS_NAME = "LogicAnalyzerPreference"; - - private boolean isRunning = false; - - private final String KEY_LOG = "has_log"; - private final String DATA_BLOCK = "data_block"; - public boolean isPlayback = false; - public RealmResults recordedLAData; - private LALogicLinesFragment laLogicLinesFragment; - - public LogicalAnalyzerActivity() { - super(R.layout.activity_logic_analyzer); - } - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - requestWindowFeature(Window.FEATURE_NO_TITLE); - super.onCreate(savedInstanceState); - getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); - - removeStatusBar(); - - laLogicLinesFragment = LALogicLinesFragment.newInstance(this); - getSupportFragmentManager().beginTransaction().add(R.id.la_frame_layout, laLogicLinesFragment).commit(); - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.logical_analyzer); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - recordedLAData = LocalDataLog.with() - .getBlockOfLARecords(getIntent().getExtras().getLong(DATA_BLOCK)); - isPlayback = true; - } - } - - @Override - protected void onResume() { - super.onResume(); - removeStatusBar(); - } - - private void removeStatusBar() { - final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; - getWindow().getDecorView().setSystemUiVisibility(flags); - final View decorView = getWindow().getDecorView(); - decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() { - @Override - public void onSystemUiVisibilityChange(int i) { - if ((i & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) { - decorView.setSystemUiVisibility(flags); - } - } - }); - } - - @SuppressLint("NewApi") - @Override - public void onWindowFocusChanged(boolean hasFocus) { - super.onWindowFocusChanged(hasFocus); - if (hasFocus) { - getWindow().getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); - } - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.logical_analyzer_menu, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - finish(); - break; - case R.id.show_logged_data: - Intent intent = new Intent(LogicalAnalyzerActivity.this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getResources().getString(R.string.logical_analyzer)); - startActivity(intent); - break; - case R.id.save_graph: - laLogicLinesFragment.logData(); - break; - case R.id.show_guide: - toggleGuide(); - break; - default: - break; - } - return true; - } - - @Override - public void onBackPressed() { - if (!isRunning) - finish(); - } - - public void setStatus(boolean status) { - isRunning = status; - } - - -} diff --git a/app/src/main/java/io/pslab/activity/LuxMeterActivity.java b/app/src/main/java/io/pslab/activity/LuxMeterActivity.java deleted file mode 100644 index 412e6db07..000000000 --- a/app/src/main/java/io/pslab/activity/LuxMeterActivity.java +++ /dev/null @@ -1,151 +0,0 @@ -package io.pslab.activity; - -import static android.os.Build.VERSION.SDK_INT; - -import android.content.SharedPreferences; -import android.hardware.Sensor; -import android.hardware.SensorManager; - -import androidx.appcompat.app.ActionBar; -import androidx.fragment.app.Fragment; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.fragment.LuxMeterDataFragment; -import io.pslab.fragment.LuxMeterSettingFragment; -import io.pslab.models.LuxData; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.LocalDataLog; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class LuxMeterActivity extends PSLabSensor { - - private static final String PREF_NAME = "customDialogPreference"; - public final String LUXMETER_LIMIT = "luxmeter_limit"; - public RealmResults recordedLuxData; - - @Override - public int getMenu() { - return R.menu.sensor_data_log_menu; - } - - @Override - public SharedPreferences getStateSettings() { - return this.getSharedPreferences(PREF_NAME, MODE_PRIVATE); - } - - @Override - public String getFirstTimeSettingID() { - return "LuxMeterFirstTime"; - } - - @Override - public String getSensorName() { - return getResources().getString(R.string.lux_meter); - } - - @Override - public int getGuideTitle() { - return R.string.lux_meter; - } - - @Override - public int getGuideAbstract() { - return R.string.lux_meter_intro; - } - - @Override - public int getGuideSchematics() { - return R.drawable.bh1750_schematic; - } - - @Override - public int getGuideDescription() { - return R.string.lux_meter_desc; - } - - @Override - public int getGuideExtraContent() { - return 0; - } - - @Override - public void recordSensorDataBlockID(SensorDataBlock categoryData) { - realm.beginTransaction(); - realm.copyToRealm(categoryData); - realm.commitTransaction(); - } - - @Override - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((LuxData) sensorData); - realm.commitTransaction(); - } - - @Override - public void stopRecordSensorData() { - LocalDataLog.with().refresh(); - } - - @Override - public Fragment getSensorFragment() { - return LuxMeterDataFragment.newInstance(); - } - - @Override - public void getDataFromDataLogger() { - if (SDK_INT >= 21 && getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - //playingData = true; - viewingData = true; - recordedLuxData = LocalDataLog.with() - .getBlockOfLuxRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - final LuxData data = recordedLuxData.get(0); - if (data != null) { - final String title = titleFormat.format(data.getTime()); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(title); - } - } - } - } - - @Override - public boolean sensorFound() { - SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); - return sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT) != null; - } - - /** - * Once settings have been changed, those changes can be captured from onResume method. - * reinstateConfigurations() will update the logs with new settings - */ - @Override - protected void onResume() { - super.onResume(); - reinstateConfigurations(); - } - - private void reinstateConfigurations() { - SharedPreferences luxMeterConfigurations; - luxMeterConfigurations = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - locationEnabled = luxMeterConfigurations.getBoolean(LuxMeterSettingFragment.KEY_INCLUDE_LOCATION, true); - LuxMeterDataFragment.setParameters( - getValueFromText(luxMeterConfigurations.getString(LuxMeterSettingFragment.KEY_HIGH_LIMIT, "2000"), - 10, 10000), - getValueFromText(luxMeterConfigurations.getString(LuxMeterSettingFragment.KEY_UPDATE_PERIOD, "1000"), - 100, 1000), - luxMeterConfigurations.getString(LuxMeterSettingFragment.KEY_LUX_SENSOR_TYPE, "0"), - luxMeterConfigurations.getString(LuxMeterSettingFragment.KEY_LUX_SENSOR_GAIN, "1")); - } - - private int getValueFromText(String strValue, int lowerBound, int upperBound) { - if (strValue.isEmpty()) return lowerBound; - int value = Integer.parseInt(strValue); - if (value > upperBound) return upperBound; - else return Math.max(value, lowerBound); - } -} diff --git a/app/src/main/java/io/pslab/activity/MainActivity.java b/app/src/main/java/io/pslab/activity/MainActivity.java deleted file mode 100644 index ad3965cc7..000000000 --- a/app/src/main/java/io/pslab/activity/MainActivity.java +++ /dev/null @@ -1,582 +0,0 @@ -package io.pslab.activity; - -import static io.pslab.others.ScienceLabCommon.scienceLab; - -import android.app.PendingIntent; -import android.app.ProgressDialog; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.hardware.usb.UsbDevice; -import android.hardware.usb.UsbManager; -import android.os.Bundle; -import android.os.Handler; -import android.util.Log; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.widget.ImageView; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.ActionBarDrawerToggle; -import androidx.appcompat.app.AlertDialog; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; -import androidx.browser.customtabs.CustomTabsServiceConnection; -import androidx.core.view.GravityCompat; -import androidx.drawerlayout.widget.DrawerLayout; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentTransaction; - -import com.google.android.gms.oss.licenses.OssLicensesMenuActivity; -import com.google.android.material.navigation.NavigationView; -import com.google.android.material.snackbar.Snackbar; - -import java.io.IOException; - -import javax.annotation.Nullable; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.pslab.BuildConfig; -import io.pslab.R; -import io.pslab.communication.CommunicationHandler; -import io.pslab.fragment.AboutUsFragment; -import io.pslab.fragment.FAQFragment; -import io.pslab.fragment.HomeFragment; -import io.pslab.fragment.InstrumentsFragment; -import io.pslab.fragment.PSLabPinLayoutFragment; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.CustomTabService; -import io.pslab.others.InitializationVariable; -import io.pslab.others.ScienceLabCommon; -import io.pslab.receivers.USBDetachReceiver; - -public class MainActivity extends AppCompatActivity { - - private static final String TAG = "MainActivity"; - - @BindView(R.id.nav_view) - NavigationView navigationView; - @Nullable - @BindView(R.id.drawer_layout) - DrawerLayout drawer; - @BindView(R.id.toolbar) - Toolbar toolbar; - - View navHeader; - private ImageView imgProfile; - private TextView txtName; - - private ProgressDialog initialisationDialog; - - private CustomTabService customTabService; - private CustomTabsServiceConnection customTabsServiceConnection; - - public static int navItemIndex = 0; - - private static final String TAG_DEVICE = "device"; - private static final String TAG_INSTRUMENTS = "instruments"; - private static final String TAG_ABOUTUS = "aboutUs"; - private static final String TAG_PINLAYOUT = "pinLayout"; - private static final String TAG_FAQ = "faq"; - private static String CURRENT_TAG = TAG_INSTRUMENTS; - private String[] activityTitles; - - private final boolean shouldLoadHomeFragOnBackPress = true; - private Handler mHandler; - private ScienceLabCommon mScienceLabCommon; - - public boolean PSLabisConnected = false; - - InitializationVariable initialisationStatus; - - public static boolean hasPermission = false; - private boolean receiverRegister = false; - private UsbManager usbManager; - private PendingIntent mPermissionIntent; - private CommunicationHandler communicationHandler; - private USBDetachReceiver usbDetachReceiver; - private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"; - private static final int TIME_INTERVAL = 2000; - private long mBackPressed; - private static MainActivity instance; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - ButterKnife.bind(this); - - initialisationStatus = new InitializationVariable(); - initialisationDialog = new ProgressDialog(this); - initialisationDialog.setMessage(getString(R.string.initialising_wait)); - initialisationDialog.setIndeterminate(true); - initialisationDialog.setCancelable(false); - - usbManager = (UsbManager) getSystemService(USB_SERVICE); - - customTabService = new CustomTabService(MainActivity.this, customTabsServiceConnection); - - mScienceLabCommon = ScienceLabCommon.getInstance(); - - initialisationDialog.show(); - - communicationHandler = new CommunicationHandler(usbManager); - attemptToGetUSBPermission(); - - PSLabisConnected = mScienceLabCommon.openDevice(communicationHandler); - - IntentFilter usbDetachFilter = new IntentFilter(); - usbDetachFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); - usbDetachReceiver = new USBDetachReceiver(this); - registerReceiver(usbDetachReceiver, usbDetachFilter); - - setSupportActionBar(toolbar); - mHandler = new Handler(); - - navHeader = navigationView.getHeaderView(0); - txtName = navHeader.findViewById(io.pslab.R.id.name); - imgProfile = navHeader.findViewById(io.pslab.R.id.img_profile); - activityTitles = getResources().getStringArray(io.pslab.R.array.nav_item_activity_titles); - - setPSLabVersionIDs(); - - setUpNavigationView(); - initialisationDialog.dismiss(); - - if (savedInstanceState == null) { - navItemIndex = 0; - CURRENT_TAG = TAG_INSTRUMENTS; - loadHomeFragment(); - } - instance = this; - } - - private void loadHomeFragment() { - selectNavMenu(); - setToolbarTitle(activityTitles[navItemIndex]); - if (drawer != null && getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) { - drawer.closeDrawers(); - return; - } - Runnable mPendingRunnable = new Runnable() { - @Override - public void run() { - Fragment fragment = null; - try { - fragment = getHomeFragment(); - } catch (IOException e) { - e.printStackTrace(); - } - FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); - fragmentTransaction.setCustomAnimations(R.anim.fade_in, - R.anim.fade_out); - fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG); - fragmentTransaction.commitAllowingStateLoss(); - } - }; - if (mPendingRunnable != null) { - mHandler.post(mPendingRunnable); - } - if (drawer != null) { - drawer.closeDrawers(); - invalidateOptionsMenu(); - } - } - - public static MainActivity getInstance() { - return instance; - } - - private Fragment getHomeFragment() throws IOException { - switch (navItemIndex) { - case 2: - return HomeFragment.newInstance(ScienceLabCommon.scienceLab.isConnected(), ScienceLabCommon.scienceLab.isDeviceFound()); - case 5: - return AboutUsFragment.newInstance(); - case 8: - return FAQFragment.newInstance(); - default: - return InstrumentsFragment.newInstance(); - } - } - - private void setToolbarTitle(final CharSequence title) { - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(title); - } - } - - private void unCheckAllMenuItems(Menu menu) { - int size = menu.size(); - for (int i = 0; i < size; i++) { - final MenuItem item = menu.getItem(i); - item.setChecked(false); - } - } - - private void selectNavMenu() { - int size_menu = navigationView.getMenu().size(); - for (int i = 0; i < size_menu; i++) { - final MenuItem item = navigationView.getMenu().getItem(i); - if (item.hasSubMenu()) { - unCheckAllMenuItems(item.getSubMenu()); - } else { - item.setChecked(false); - } - } - switch (navItemIndex) { - case 0: - case 1: - case 2: - navigationView.getMenu().getItem(navItemIndex).setChecked(true); - break; - case 5: - navigationView.getMenu().getItem(navItemIndex).setChecked(true); - break; - case 8: - navigationView.getMenu().getItem(navItemIndex).setChecked(true); - break; - default: - navigationView.getMenu().getItem(0).setChecked(true); - break; - } - } - - private void setUpNavigationView() { - navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { - @Override - public boolean onNavigationItemSelected(@NonNull MenuItem item) { - switch (item.getItemId()) { - case R.id.nav_instruments: - navItemIndex = 0; - CURRENT_TAG = TAG_INSTRUMENTS; - break; - case R.id.nav_device: - navItemIndex = 2; - CURRENT_TAG = TAG_DEVICE; - break; - case R.id.nav_settings: - if (drawer != null) { - drawer.closeDrawers(); - } - Intent intent = new Intent(MainActivity.this, SettingsActivity.class); - intent.putExtra("title", "Settings"); - startActivity(intent); - return true; - case R.id.nav_about_us: - navItemIndex = 5; - CURRENT_TAG = TAG_ABOUTUS; - break; - case R.id.nav_documentation: - customTabService.launchUrl("https://docs.pslab.io/"); - if (drawer != null) { - drawer.closeDrawers(); - } - break; - case R.id.nav_rate: - customTabService.launchUrl("https://play.google.com/store/apps/details?id=io.pslab"); - if (drawer != null) { - drawer.closeDrawers(); - } - break; - case R.id.nav_help_feedback: - navItemIndex = 8; - CURRENT_TAG = TAG_FAQ; - break; - case R.id.nav_buy_pslab: - customTabService.launchUrl("https://pslab.io/shop/"); - if (drawer != null) { - drawer.closeDrawers(); - } - break; - case R.id.sensor_data_logger: - if (drawer != null) { - drawer.closeDrawers(); - } - startActivity(new Intent(MainActivity.this, DataLoggerActivity.class)); - break; - case R.id.nav_share_app: - if (drawer != null) { - drawer.closeDrawers(); - } - Intent shareIntent = new Intent(Intent.ACTION_SEND); - shareIntent.setType("text/plain"); - shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name)); - String shareMessage = "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID; - shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage); - startActivity(shareIntent); - return true; - case R.id.nav_generate_config: - if (drawer != null) { - drawer.closeDrawers(); - } - startActivity(new Intent(MainActivity.this, CreateConfigActivity.class)); - break; - case R.id.nav_privacy_policy: - customTabService.launchUrl("https://pslab.io/privacy-policy/"); - if (drawer != null) { - drawer.closeDrawers(); - } - break; - case R.id.nav_third_party_libs: - OssLicensesMenuActivity.setActivityTitle(getString(R.string.third_party_libs)); - startActivity(new Intent(MainActivity.this, OssLicensesMenuActivity.class)); - break; - default: - navItemIndex = 0; - } - loadHomeFragment(); - return true; - } - }); - - if (drawer != null) { - ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, io.pslab.R.string.openDrawer, io.pslab.R.string.closeDrawer) { - @Override - public void onDrawerClosed(View drawerView) { - super.onDrawerClosed(drawerView); - } - - @Override - public void onDrawerOpened(View drawerView) { - super.onDrawerOpened(drawerView); - } - }; - drawer.setDrawerListener(actionBarDrawerToggle); - actionBarDrawerToggle.syncState(); - } - } - - private void setPSLabVersionIDs() { - try { - txtName.setText(scienceLab.getVersion()); - } catch (IOException e) { - txtName.setText(getString(R.string.device_not_found)); - } - } - - public void showFirmwareDialog() { - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle(R.string.legacy_title); - builder.setCancelable(false); - builder.setMessage(R.string.legacy_message); - builder.setIcon(android.R.drawable.ic_dialog_alert); - builder.setPositiveButton("OK", (dialog, which) -> dialog.dismiss()); - builder.create().show(); - - } - - @Override - public void onBackPressed() { - Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame); - if (drawer != null && drawer.isDrawerOpen(GravityCompat.START)) { - drawer.closeDrawers(); - return; - } - if (fragment instanceof HomeFragment && HomeFragment.isWebViewShowing) { - ((HomeFragment) fragment).hideWebView(); - return; - } - if (shouldLoadHomeFragOnBackPress) { - if (navItemIndex != 0 || CURRENT_TAG.equals(TAG_PINLAYOUT)) { - navItemIndex = 0; - CURRENT_TAG = TAG_INSTRUMENTS; - loadHomeFragment(); - return; - } - } - if (fragment instanceof InstrumentsFragment) { - if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) { - super.onBackPressed(); - return; - } else { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.Toast_double_tap), null, null, Snackbar.LENGTH_SHORT); - } - mBackPressed = System.currentTimeMillis(); - } - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.pslab_connectivity_menu, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.menu_pslab_connected: - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.device_connected_successfully), null, null, Snackbar.LENGTH_SHORT); - break; - case R.id.menu_pslab_disconnected: - attemptToConnectPSLab(); - break; - case R.id.menu_pslab_layout_front: - PSLabPinLayoutFragment.frontSide = true; - displayPSLabPinLayout(); - break; - case R.id.menu_pslab_layout_back: - PSLabPinLayoutFragment.frontSide = false; - displayPSLabPinLayout(); - break; - default: - break; - } - return true; - } - - private void attemptToConnectPSLab() { - initialisationDialog.show(); - mScienceLabCommon = ScienceLabCommon.getInstance(); - if (communicationHandler.isConnected()) { - initialisationDialog.dismiss(); - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.device_connected_successfully), null, null, Snackbar.LENGTH_SHORT); - } else { - communicationHandler = new CommunicationHandler(usbManager); - if (communicationHandler.isDeviceFound()) { - attemptToGetUSBPermission(); - } else { - initialisationDialog.dismiss(); - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.device_not_found), null, null, Snackbar.LENGTH_SHORT); - navItemIndex = 2; - CURRENT_TAG = TAG_DEVICE; - loadHomeFragment(); - } - } - } - - private void displayPSLabPinLayout() { - CURRENT_TAG = TAG_PINLAYOUT; - navigationView.getMenu().getItem(navItemIndex).setChecked(false); - setToolbarTitle(getResources().getString(R.string.pslab_pinlayout)); - Runnable mPendingRunnable = new Runnable() { - @Override - public void run() { - Fragment fragment = PSLabPinLayoutFragment.newInstance(); - FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); - fragmentTransaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out) - .replace(R.id.frame, fragment, TAG_PINLAYOUT) - .commitAllowingStateLoss(); - } - }; - mHandler.post(mPendingRunnable); - } - - private void attemptToGetUSBPermission() { - if (!("android.hardware.usb.action.USB_DEVICE_ATTACHED".equals(getIntent().getAction()))) { - if (communicationHandler.isDeviceFound() && !usbManager.hasPermission(communicationHandler.mUsbDevice)) { - mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); - IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); - registerReceiver(mUsbReceiver, filter); - receiverRegister = true; - usbManager.requestPermission(communicationHandler.mUsbDevice, mPermissionIntent); - } - if (communicationHandler.mUsbDevice != null) { - if (usbManager.hasPermission(communicationHandler.mUsbDevice)) - initialisationDialog.dismiss(); - hasPermission = true; - } - } else if (usbManager.hasPermission(communicationHandler.mUsbDevice)) { - hasPermission = true; - initialisationDialog.dismiss(); - } - } - - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - menu.getItem(0).setVisible(PSLabisConnected); - menu.getItem(1).setVisible(!PSLabisConnected); - setPSLabVersionIDs(); - return true; - } - - @Override - protected void onDestroy() { - super.onDestroy(); - Log.v(TAG, "MainActivityDestroyed"); - try { - scienceLab.disconnect(); - } catch (IOException e) { - e.printStackTrace(); - } - unregisterReceiver(usbDetachReceiver); - if (customTabsServiceConnection != null) { - this.unbindService(customTabsServiceConnection); - } - if (receiverRegister) - unregisterReceiver(mUsbReceiver); - } - - private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (ACTION_USB_PERMISSION.equals(action)) { - synchronized (this) { - UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); - if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { - if (device != null) { - hasPermission = true; - PSLabisConnected = mScienceLabCommon.openDevice(communicationHandler); - initialisationDialog.dismiss(); - invalidateOptionsMenu(); - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.device_connected_successfully), null, null, Snackbar.LENGTH_SHORT); - if (navItemIndex == 0) { - getSupportFragmentManager().beginTransaction().replace(R.id.frame, InstrumentsFragment.newInstance()).commit(); - } else if (navItemIndex == 2) { - getSupportFragmentManager().beginTransaction().replace(R.id.frame, HomeFragment.newInstance(true, true)).commitAllowingStateLoss(); - } else { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.device_connected_successfully), null, null, Snackbar.LENGTH_SHORT); - } - } - } else { - initialisationDialog.dismiss(); - Log.d(TAG, "permission denied for device " + device); - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.device_not_found), null, null, Snackbar.LENGTH_SHORT); - } - } - } - } - }; - - @Override - protected void onNewIntent(Intent intent) { - super.onNewIntent(intent); - attemptToConnectPSLab(); - synchronized (this) { - UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); - if (device != null && hasPermission) { - PSLabisConnected = mScienceLabCommon.openDevice(communicationHandler); - initialisationDialog.dismiss(); - invalidateOptionsMenu(); - if (navItemIndex == 0) { - getSupportFragmentManager().beginTransaction().replace(R.id.frame, InstrumentsFragment.newInstance()).commit(); - } else if (navItemIndex == 2) { - getSupportFragmentManager().beginTransaction().replace(R.id.frame, HomeFragment.newInstance(true, true)).commitAllowingStateLoss(); - } - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.device_connected_successfully), null, null, Snackbar.LENGTH_SHORT); - } - } - } - - @Override - protected void onPostResume() { - super.onPostResume(); - selectNavMenu(); - } -} diff --git a/app/src/main/java/io/pslab/activity/MapsActivity.java b/app/src/main/java/io/pslab/activity/MapsActivity.java deleted file mode 100644 index ab8bc6384..000000000 --- a/app/src/main/java/io/pslab/activity/MapsActivity.java +++ /dev/null @@ -1,80 +0,0 @@ -package io.pslab.activity; - -import android.os.Bundle; - -import androidx.appcompat.app.AppCompatActivity; -import androidx.core.content.res.ResourcesCompat; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.osmdroid.api.IMapController; -import org.osmdroid.config.Configuration; -import org.osmdroid.tileprovider.tilesource.TileSourceFactory; -import org.osmdroid.util.GeoPoint; -import org.osmdroid.views.MapView; -import org.osmdroid.views.overlay.Marker; - -import io.pslab.BuildConfig; -import io.pslab.R; - -public class MapsActivity extends AppCompatActivity { - - MapView map = null; - private Marker m; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_maps); - - Configuration.getInstance().setUserAgentValue(BuildConfig.APPLICATION_ID); - map = findViewById(R.id.osmmap); - map.setTileSource(TileSourceFactory.MAPNIK); - map.setBuiltInZoomControls(true); - map.setMultiTouchControls(true); - - m = new Marker(map); - - IMapController mapController = map.getController(); - mapController.setZoom((double) 9); - - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean("hasMarkers")) { - try { - JSONArray markers = new JSONArray(getIntent().getExtras().getString("markers")); - addMarkers(markers); - } catch (JSONException e) { - e.printStackTrace(); - } finally { - map.invalidate(); - mapController.setCenter(m.getPosition()); - } - } else { - GeoPoint startPoint = new GeoPoint(-33.8688, 151.2093); - mapController.setCenter(startPoint); - } - } - - private void addMarkers(JSONArray markers) throws JSONException { - for (int i = 0; i < markers.length(); i++) { - JSONObject marker = markers.getJSONObject(i); - m.setPosition(new GeoPoint(marker.getDouble("lat"), marker.getDouble("lon"))); - m.setTitle(getString(R.string.logged_data) + " @ " + marker.getString("date")); - m.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.action_item_read, null)); - m.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_TOP); - map.getOverlays().add(m); - } - } - - @Override - protected void onResume() { - super.onResume(); - map.onResume(); - } - - @Override - protected void onPause() { - super.onPause(); - map.onPause(); - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/activity/MultimeterActivity.java b/app/src/main/java/io/pslab/activity/MultimeterActivity.java deleted file mode 100644 index 19f1115d1..000000000 --- a/app/src/main/java/io/pslab/activity/MultimeterActivity.java +++ /dev/null @@ -1,568 +0,0 @@ -package io.pslab.activity; - -import android.Manifest; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.pm.ActivityInfo; -import android.content.pm.PackageManager; -import android.graphics.Typeface; -import android.location.Location; -import android.location.LocationManager; -import android.os.Bundle; -import android.os.Handler; -import android.preference.PreferenceManager; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.widget.CompoundButton; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.widget.SwitchCompat; -import androidx.appcompat.widget.Toolbar; -import androidx.coordinatorlayout.widget.CoordinatorLayout; -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; -import androidx.core.content.res.ResourcesCompat; - -import com.google.android.material.snackbar.Snackbar; - -import java.text.DecimalFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.Timer; -import java.util.TimerTask; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.activity.guide.GuideActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.fragment.MultimeterSettingsFragment; -import io.pslab.models.MultimeterData; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.GPSLogger; -import io.pslab.others.LocalDataLog; -import io.pslab.others.ScienceLabCommon; -import io.realm.Realm; -import io.realm.RealmObject; -import io.realm.RealmResults; -import it.beppi.knoblibrary.Knob; - -/** - * Created by Abhinav Raj on 26/5/18. - */ - -public class MultimeterActivity extends GuideActivity { - - public static final String NAME = "savingData"; - private static final int MY_PERMISSIONS_REQUEST_STORAGE_FOR_DATA = 101; - private static final CSVDataLine CSV_HEADER = - new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("Data") - .add("Value") - .add("Latitude") - .add("Longitude"); - private final String KEY_LOG = "has_log"; - private final String DATA_BLOCK = "data_block"; - public boolean recordData = false; - public CSVLogger multimeterLogger = null; - @BindView(R.id.multimeter_toolbar) - Toolbar mToolbar; - @BindView(R.id.quantity) - TextView quantity; - @BindView(R.id.unit) - TextView unit; - @BindView(R.id.knobs) - Knob knob; - @BindView(R.id.selector) - SwitchCompat aSwitch; - @BindView(R.id.multimeter_coordinator_layout) - CoordinatorLayout coordinatorLayout; - - SharedPreferences multimeter_data; - private ScienceLab scienceLab; - private int knobState; - private CSVDataLine dataRecorded; - private String defaultValue; - private Menu menu; - private Boolean switchIsChecked; - private String[] knobMarker; - private boolean isRecordingStarted = false; - private boolean isDataRecorded = false; - private Timer recordTimer; - private boolean locationEnabled = true; - private long recordPeriod; - private double lat = 0, lon = 0; - private GPSLogger gpsLogger; - private Realm realm; - private long block; - private RealmResults recordedMultimeterData; - private MenuItem playMenu; - private MenuItem stopMenu; - private boolean isPlayingBack = false; - private boolean playClicked = false; - private Timer playBackTimer; - private int currentPosition = 0; - - public MultimeterActivity() { - super(R.layout.activity_multimeter_main); - } - - @Override - protected void onCreate(final Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - defaultValue = getString(R.string.multimeter_default_value); - ButterKnife.bind(this); - scienceLab = ScienceLabCommon.scienceLab; - knobMarker = getResources().getStringArray(io.pslab.R.array.multimeter_knob_states); - setSupportActionBar(mToolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setDisplayHomeAsUpEnabled(true); - } - - gpsLogger = new GPSLogger(this, (LocationManager) getSystemService(Context.LOCATION_SERVICE)); - - multimeter_data = this.getSharedPreferences(NAME, MODE_PRIVATE); - dataRecorded = CSV_HEADER; - knobState = multimeter_data.getInt("KnobState", 2); - switchIsChecked = multimeter_data.getBoolean("SwitchState", false); - aSwitch.setChecked(switchIsChecked); - - Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/digital-7 (italic).ttf"); - quantity.setTypeface(tf); - - String text_quantity = multimeter_data.getString("TextBox", defaultValue); - String text_unit = multimeter_data.getString("TextBoxUnit", null); - - realm = LocalDataLog.with().getRealm(); - - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - recordedMultimeterData = LocalDataLog.with() - .getBlockOfMultimeterRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - isPlayingBack = true; - } else { - knob.setState(knobState); - quantity.setText(text_quantity); - unit.setText(text_unit); - knob.setOnStateChanged(new Knob.OnStateChanged() { - @Override - public void onState(int state) { - knobState = state; - saveKnobState(knobState); - } - }); - aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - switchIsChecked = isChecked; - SharedPreferences.Editor editor = multimeter_data.edit(); - editor.putBoolean("SwitchState", switchIsChecked); - editor.apply(); - } - }); - isPlayingBack = false; - checkConfig(); - logTimer(); - } - if (getResources().getBoolean(R.bool.isTablet)) { - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER); - } - } - - @Override - protected void onResume() { - super.onResume(); - checkConfig(); - } - - private void logData() { - switch (knobState) { - case 3: // Resistor - if (scienceLab.isConnected()) { - DecimalFormat resistanceFormat = new DecimalFormat("#.##"); - Double resistance; - Double avgResistance = 0.0; - int loops = 20; - for (int i = 0; i < loops; i++) { - resistance = scienceLab.getResistance(); - if (resistance == null) { - avgResistance = null; - break; - } else { - avgResistance = avgResistance + resistance / loops; - } - } - String resistanceUnit; - String recordUnit = "Ohms"; - String Resistance = ""; - if (avgResistance == null) { - Resistance = "Infinity"; - resistanceUnit = "\u2126"; - recordUnit = "Ohms"; - } else { - if (avgResistance > 10e5) { - Resistance = resistanceFormat.format((avgResistance / 10e5)); - resistanceUnit = "M" + "\u2126"; - recordUnit = "MOhms"; - } else if (avgResistance > 10e2) { - Resistance = resistanceFormat.format((avgResistance / 10e2)); - resistanceUnit = "k" + "\u2126"; - recordUnit = "kOhms"; - } else if (avgResistance > 1) { - Resistance = resistanceFormat.format(avgResistance); - resistanceUnit = "\u2126"; - recordUnit = "Ohms"; - } else { - Resistance = "Cannot measure!"; - resistanceUnit = "Ohms"; - } - } - saveAndSetData(Resistance, resistanceUnit); - if (recordData) - record(knobMarker[knobState], Resistance + " " + recordUnit); - } - break; - case 4: //Capacitor - if (scienceLab.isConnected()) { - Double capacitance = scienceLab.getCapacitance(); - DecimalFormat capacitanceFormat = new DecimalFormat("#.##"); - String Capacitance; - String capacitanceUnit; - if (capacitance == null) { - Capacitance = "Cannot measure!"; - capacitanceUnit = "pF"; - } else { - if (capacitance < 1e-9) { - Capacitance = capacitanceFormat.format((capacitance / 1e-12)); - capacitanceUnit = "pF"; - } else if (capacitance < 1e-6) { - Capacitance = capacitanceFormat.format((capacitance / 1e-9)); - capacitanceUnit = "nF"; - } else if (capacitance < 1e-3) { - Capacitance = capacitanceFormat.format((capacitance / 1e-6)); - capacitanceUnit = "\u00B5" + "F"; - } else if (capacitance < 1e-1) { - Capacitance = capacitanceFormat.format((capacitance / 1e-3)); - capacitanceUnit = "mF"; - } else { - Capacitance = capacitanceFormat.format(capacitance); - capacitanceUnit = getString(R.string.capacitance_unit); - } - } - saveAndSetData(Capacitance, capacitanceUnit); - if (recordData) - record(knobMarker[knobState], Capacitance + " " + capacitanceUnit); - } - break; - case 5: - getIDdata(); - break; - case 6: - getIDdata(); - break; - case 7: - getIDdata(); - break; - case 8: - getIDdata(); - break; - default: - if (scienceLab.isConnected()) { - saveAndSetData(DataFormatter.formatDouble(scienceLab.getVoltage(knobMarker[knobState], 1), DataFormatter.LOW_PRECISION_FORMAT), getString(R.string.multimeter_voltage_unit)); - if (recordData) - record(knobMarker[knobState], DataFormatter.formatDouble(scienceLab.getVoltage(knobMarker[knobState], 1), DataFormatter.LOW_PRECISION_FORMAT) + " " + getString(R.string.multimeter_voltage_unit)); - } - break; - } - } - - private void logTimer() { - if (recordTimer == null) { - recordTimer = new Timer(); - } - recordTimer.schedule(new TimerTask() { - @Override - public void run() { - runOnUiThread(new Runnable() { - @Override - public void run() { - logData(); - } - }); - } - }, 0, recordPeriod); - } - - private void getIDdata() { - try { - if (!switchIsChecked) { - if (scienceLab.isConnected()) { - Double frequency = scienceLab.getFrequency(knobMarker[knobState]); - saveAndSetData(DataFormatter.formatDouble(frequency, DataFormatter.LOW_PRECISION_FORMAT), getString(R.string.frequency_unit)); - if (recordData) - record(knobMarker[knobState], DataFormatter.formatDouble(frequency, DataFormatter.LOW_PRECISION_FORMAT) + getString(R.string.frequency_unit)); - } - } else { - if (scienceLab.isConnected()) { - scienceLab.countPulses(knobMarker[knobState]); - double pulseCount = scienceLab.readPulseCount(); - saveAndSetData(DataFormatter.formatDouble(pulseCount, DataFormatter.LOW_PRECISION_FORMAT), ""); - if (recordData) - record(knobMarker[knobState], String.valueOf(pulseCount)); - } - } - } catch (Exception e) { - saveAndSetData("Cannot measure!", "null"); - if (recordData) { - record(knobMarker[knobState], "null"); - } - } - } - - private void checkConfig() { - SharedPreferences multimeterConfigs = PreferenceManager.getDefaultSharedPreferences(this); - recordPeriod = Long.valueOf(multimeterConfigs.getString(MultimeterSettingsFragment.KEY_UPDATE_PERIOD, getResources().getString(R.string.multimeter_default_1000))); - locationEnabled = multimeterConfigs.getBoolean(MultimeterSettingsFragment.KEY_INCLUDE_LOCATION, true); - } - - private void saveAndSetData(String Quantity, String Unit) { - SharedPreferences.Editor editor = multimeter_data.edit(); - editor.putString("TextBox", Quantity); - editor.putString("TextBoxUnit", Unit); - editor.apply(); - quantity.setText(Quantity); - unit.setText(Unit); - } - - private void record(String data, String value) { - if (locationEnabled && gpsLogger.isGPSEnabled()) { - Location location = gpsLogger.getDeviceLocation(); - if (location != null) { - lat = location.getLatitude(); - lon = location.getLongitude(); - } else { - lat = 0.0; - lon = 0.0; - } - } else { - lat = 0.0; - lon = 0.0; - } - long timestamp = System.currentTimeMillis(); - dataRecorded = new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(data) - .add(value) - .add(lat) - .add(lon); - multimeterLogger.writeCSVFile(dataRecorded); - recordSensorData(new MultimeterData(timestamp, block, data, value, lat, lon)); - } - - private void saveKnobState(int state) { - SharedPreferences.Editor editor = multimeter_data.edit(); - editor.putInt("KnobState", state); - editor.apply(); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.multimeter_log_menu, menu); - this.menu = menu; - return true; - } - - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - playMenu = menu.findItem(R.id.play_data); - stopMenu = menu.findItem(R.id.stop_data); - playMenu.setVisible(isPlayingBack); - menu.findItem(R.id.record_pause_data).setVisible(!isPlayingBack); - return super.onPrepareOptionsMenu(menu); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.record_pause_data: - if (scienceLab.isConnected()) { - if (ContextCompat.checkSelfPermission(this, - Manifest.permission.WRITE_EXTERNAL_STORAGE) - != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(this, - new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_STORAGE_FOR_DATA); - return true; - } - if (recordData) { - item.setIcon(R.drawable.ic_record_white); - recordData = false; - if (isDataRecorded) { - MenuItem item1 = menu.findItem(R.id.record_pause_data); - item1.setIcon(R.drawable.ic_record_white); - dataRecorded = CSV_HEADER; - // Export Data - CustomSnackBar.showSnackBar(coordinatorLayout, - getString(R.string.csv_store_text) + " " + multimeterLogger.getCurrentFilePath() - , getString(R.string.open), new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(MultimeterActivity.this, DataLoggerActivity.class)); - } - }, Snackbar.LENGTH_SHORT); - isRecordingStarted = false; - recordData = false; - } else { - CustomSnackBar.showSnackBar(coordinatorLayout, getString(R.string.nothing_to_export), null, null, Snackbar.LENGTH_SHORT); - } - } else { - isDataRecorded = true; - item.setIcon(R.drawable.ic_record_stop_white); - if (!isRecordingStarted) { - multimeterLogger = new CSVLogger(getString(R.string.multimeter)); - multimeterLogger.prepareLogFile(); - multimeterLogger.writeMetaData(getResources().getString(R.string.multimeter)); - multimeterLogger.writeCSVFile(CSV_HEADER); - block = System.currentTimeMillis(); - recordSensorDataBlockID(new SensorDataBlock(block, getResources().getString(R.string.multimeter))); - isRecordingStarted = true; - recordData = true; - CustomSnackBar.showSnackBar(coordinatorLayout, getString(R.string.data_recording_start), null, null, Snackbar.LENGTH_SHORT); - } - } - } else { - CustomSnackBar.showSnackBar(coordinatorLayout, getString(R.string.device_not_found), null, null, Snackbar.LENGTH_SHORT); - } - break; - case R.id.settings: - Intent settingIntent = new Intent(this, SettingsActivity.class); - settingIntent.putExtra("title", getResources().getString(R.string.multimeter_configurations)); - startActivity(settingIntent); - break; - case android.R.id.home: - this.finish(); - break; - case R.id.multimeter_show_data: - Intent intent = new Intent(this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getResources().getString(R.string.multimeter)); - startActivity(intent); - break; - case R.id.show_guide: - toggleGuide(); - break; - case R.id.play_data: - if (playClicked) { - playClicked = false; - stopMenu.setVisible(true); - item.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_play_arrow_white_24dp, null)); - if (playBackTimer != null) { - playBackTimer.cancel(); - } - } else { - playClicked = true; - item.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_pause_white_24dp, null)); - stopMenu.setVisible(true); - if (playBackTimer != null) { - playBackTimer.cancel(); - } - playBackTimer = new Timer(); - final Handler handler = new Handler(); - playBackTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - if (currentPosition < recordedMultimeterData.size()) { - setLoggedData(recordedMultimeterData.get(currentPosition)); - } else { - playBackTimer.cancel(); - currentPosition = 0; - stopMenu.setVisible(false); - item.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_play_arrow_white_24dp, null)); - } - } - }); - } - }, 0, recordPeriod); - } - break; - case R.id.stop_data: - stopMenu.setVisible(false); - if (playBackTimer != null) { - playBackTimer.cancel(); - playBackTimer = null; - } - currentPosition = 0; - playClicked = false; - playMenu.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_play_arrow_white_24dp, null)); - default: - break; - } - return true; - } - - private void setLoggedData(MultimeterData multimeterData) { - String data = multimeterData.getData(); - String value = multimeterData.getValue(); - knob.setEnabled(false); - knob.setState(Arrays.asList(knobMarker).indexOf(data)); - String quantityString = ""; - String unitString = ""; - try { - if (value.split(" ")[0].equals("Cannot")) { - quantityString = value.split(" ")[0] + " " + value.split(" ")[1]; - unitString = value.split(" ")[2]; - } else { - quantityString = value.split(" ")[0]; - unitString = value.split(" ")[1]; - } - } catch (Exception e) { - e.printStackTrace(); - } - unit.setText(unitString); - quantity.setText(quantityString); - currentPosition++; - } - - @Override - protected void onDestroy() { - super.onDestroy(); - if (recordTimer != null) { - recordTimer.cancel(); - recordTimer = null; - } - if (playBackTimer != null) { - playBackTimer.cancel(); - playBackTimer = null; - } - if (isRecordingStarted) { - if (multimeterLogger != null) - multimeterLogger.deleteFile(); - isRecordingStarted = false; - } - } - - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((MultimeterData) sensorData); - realm.commitTransaction(); - } -} diff --git a/app/src/main/java/io/pslab/activity/OscilloscopeActivity.java b/app/src/main/java/io/pslab/activity/OscilloscopeActivity.java deleted file mode 100644 index 04a998616..000000000 --- a/app/src/main/java/io/pslab/activity/OscilloscopeActivity.java +++ /dev/null @@ -1,1376 +0,0 @@ -package io.pslab.activity; - - -import static io.pslab.others.AudioJack.SAMPLING_RATE; -import static io.pslab.others.MathUtils.map; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.Intent; -import android.graphics.Color; -import android.graphics.Point; -import android.location.Location; -import android.location.LocationManager; -import android.os.AsyncTask; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.view.Display; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.Window; -import android.view.WindowManager; -import android.widget.FrameLayout; -import android.widget.ImageButton; -import android.widget.LinearLayout; -import android.widget.RelativeLayout; -import android.widget.TextView; -import android.widget.Toast; - -import androidx.annotation.IdRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.widget.Toolbar; -import androidx.fragment.app.Fragment; -import androidx.recyclerview.widget.DefaultItemAnimator; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; -import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; -import com.google.android.material.snackbar.Snackbar; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.math3.complex.Complex; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Objects; -import java.util.Timer; -import java.util.TimerTask; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.pslab.R; -import io.pslab.activity.guide.GuideActivity; -import io.pslab.adapters.OscilloscopeMeasurementsAdapter; -import io.pslab.communication.AnalyticsClass; -import io.pslab.communication.ScienceLab; -import io.pslab.fragment.ChannelParametersFragment; -import io.pslab.fragment.DataAnalysisFragment; -import io.pslab.fragment.OscilloscopePlaybackFragment; -import io.pslab.fragment.TimebaseTriggerFragment; -import io.pslab.fragment.XYPlotFragment; -import io.pslab.models.OscilloscopeData; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.AudioJack; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.GPSLogger; -import io.pslab.others.LocalDataLog; -import io.pslab.others.OscilloscopeMeasurements; -import io.pslab.others.Plot2D; -import io.pslab.others.ScienceLabCommon; -import io.realm.Realm; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class OscilloscopeActivity extends GuideActivity implements View.OnClickListener { - - private static final CSVDataLine CSV_HEADER = new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("Mode") - .add("Channel") - .add("xData") - .add("yData") - .add("Timebase") - .add("lat") - .add("lon"); - private final Object lock = new Object(); - @BindView(R.id.chart_os) - public LineChart mChart; - @BindView(R.id.tv_label_left_yaxis_os) - public TextView leftYAxisLabel; - @BindView(R.id.tv_unit_left_yaxis_os) - public TextView leftYAxisLabelUnit; - @BindView(R.id.tv_label_right_yaxis_os) - public TextView rightYAxisLabel; - @BindView(R.id.tv_unit_right_yaxis_os) - public TextView rightYAxisLabelUnit; - @BindView(R.id.tv_graph_label_xaxis_os) - public TextView xAxisLabel; - @BindView(R.id.tv_unit_xaxis_os) - public TextView xAxisLabelUnit; - public int samples; - public double timeGap; - public double timebase; - public double maxTimebase = 102.4f; - public double xAxisScale = 875f; - public double yAxisScale = 16f; - public boolean isCH1Selected; - public boolean isCH2Selected; - public boolean isCH3Selected; - public boolean isMICSelected; - public static boolean isInBuiltMicSelected; - public boolean isAudioInputSelected; - public boolean isTriggerSelected; - public boolean isTriggered; - public boolean isFourierTransformSelected; - public boolean isXYPlotSelected; - private boolean isDataAnalysisFragSelected; - public boolean sineFit; - public boolean squareFit; - public boolean isCH1FrequencyRequired; - public boolean isCH2FrequencyRequired; - public String triggerChannel; - public String triggerMode; - public String curveFittingChannel1; - public String curveFittingChannel2; - public String xyPlotXAxisChannel; - public String xyPlotYAxisChannel; - public HashMap xOffsets; - public HashMap yOffsets; - public double trigger; - public Plot2D graph; - @BindView(R.id.layout_dock_os1) - LinearLayout linearLayout; - @BindView(R.id.layout_dock_os2) - FrameLayout frameLayout; - @BindView(R.id.layout_chart_os) - RelativeLayout mChartLayout; - @BindView(R.id.button_channel_parameters_os) - ImageButton channelParametersButton; - @BindView(R.id.button_timebase_os) - ImageButton timebaseButton; - @BindView(R.id.button_data_analysis_os) - ImageButton dataAnalysisButton; - @BindView(R.id.button_xy_plot_os) - ImageButton xyPlotButton; - @BindView(R.id.tv_channel_parameters_os) - TextView channelParametersTextView; - @BindView(R.id.tv_timebase_tigger_os) - TextView timebaseTiggerTextView; - @BindView(R.id.tv_data_analysis_os) - TextView dataAnalysisTextView; - @BindView(R.id.tv_xy_plot_os) - TextView xyPlotTextView; - @BindView(R.id.parent_layout) - View parentLayout; - @BindView(R.id.recyclerView) - RecyclerView measurementsList; - private Fragment channelParametersFragment; - private Fragment timebaseTriggerFragment; - private Fragment dataAnalysisFragment; - private Fragment xyPlotFragment; - private Fragment playbackFragment; - private ScienceLab scienceLab; - private int height; - private int width; - private XAxis x1; - private YAxis y1; - private YAxis y2; - private XYPlotTask xyPlotTask; - private AudioJack audioJack = null; - private AnalyticsClass analyticsClass; - private CaptureTask captureTask; - private Thread monitorThread; - private volatile boolean monitor = true; - private double maxAmp, maxFreq; - private boolean isRecording = false; - private boolean isRunning = true; - private boolean isMeasurementsChecked = false; - private Realm realm; - public RealmResults recordedOscilloscopeData; - private CSVLogger csvLogger; - private GPSLogger gpsLogger; - private long block; - private Timer recordTimer; - private final long recordPeriod = 100; - private String loggingXdata = ""; - private final String KEY_LOG = "has_log"; - private final String DATA_BLOCK = "data_block"; - private int currentPosition = 0; - private Timer playbackTimer; - private View mainLayout; - private double lat; - private double lon; - public boolean isPlaybackFourierChecked = false; - private HashMap channelIndexMap; - public static final Integer[] channelColors = {Color.CYAN, Color.GREEN, Color.WHITE, Color.MAGENTA}; - private final String[] loggingYdata = new String[4]; - public String xyPlotAxis1 = "CH1"; - public String xyPlotAxis2 = "CH2"; - private boolean isPlayingback = false; - private boolean isPlaying = false; - private MenuItem playMenu; - private ArrayList> dataEntries = new ArrayList<>(); - private String[] dataParamsChannels; - - public enum CHANNEL {CH1, CH2, CH3, MIC} - - private enum MODE {RISING, FALLING, DUAL} - - public enum ChannelMeasurements {FREQUENCY, PERIOD, AMPLITUDE, POSITIVE_PEAK, NEGATIVE_PEAK} - - public OscilloscopeActivity() { - super(R.layout.activity_oscilloscope); - } - - @SuppressLint("ClickableViewAccessibility") - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - requestWindowFeature(Window.FEATURE_NO_TITLE); - super.onCreate(savedInstanceState); - final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; - getWindow().getDecorView().setSystemUiVisibility(flags); - final View decorView = getWindow().getDecorView(); - decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() { - @Override - public void onSystemUiVisibilityChange(int i) { - if ((i & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) { - decorView.setSystemUiVisibility(flags); - } - } - }); - ButterKnife.bind(this); - - removeStatusBar(); - mainLayout = findViewById(R.id.oscilloscope_mail_layout); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.oscilloscope); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - channelIndexMap = new HashMap<>(); - channelIndexMap.put(CHANNEL.CH1.toString(), 1); - channelIndexMap.put(CHANNEL.CH2.toString(), 2); - channelIndexMap.put(CHANNEL.CH3.toString(), 3); - channelIndexMap.put(CHANNEL.MIC.toString(), 4); - - realm = LocalDataLog.with().getRealm(); - gpsLogger = new GPSLogger(this, - (LocationManager) getSystemService(Context.LOCATION_SERVICE)); - csvLogger = new CSVLogger(getString(R.string.oscilloscope)); - - scienceLab = ScienceLabCommon.scienceLab; - x1 = mChart.getXAxis(); - y1 = mChart.getAxisLeft(); - y2 = mChart.getAxisRight(); - triggerChannel = CHANNEL.CH1.toString(); - trigger = 0; - timebase = 875; - samples = 512; - timeGap = 2; - - xOffsets = new HashMap<>(); - xOffsets.put(CHANNEL.CH1.toString(), 0.0); - xOffsets.put(CHANNEL.CH2.toString(), 0.0); - xOffsets.put(CHANNEL.CH3.toString(), 0.0); - xOffsets.put(CHANNEL.MIC.toString(), 0.0); - yOffsets = new HashMap<>(); - yOffsets.put(CHANNEL.CH1.toString(), 0.0); - yOffsets.put(CHANNEL.CH2.toString(), 0.0); - yOffsets.put(CHANNEL.CH3.toString(), 0.0); - yOffsets.put(CHANNEL.MIC.toString(), 0.0); - - sineFit = true; - squareFit = false; - isDataAnalysisFragSelected = false; - graph = new Plot2D(this, new float[]{}, new float[]{}, 1); - curveFittingChannel1 = "None"; - curveFittingChannel2 = "None"; - xyPlotXAxisChannel = CHANNEL.CH1.toString(); - xyPlotYAxisChannel = CHANNEL.CH2.toString(); - analyticsClass = new AnalyticsClass(); - isCH1FrequencyRequired = false; - isCH2FrequencyRequired = false; - - Display display = getWindowManager().getDefaultDisplay(); - Point size = new Point(); - display.getSize(size); - width = size.x; - height = size.y; - - onWindowFocusChanged(); - - channelParametersFragment = new ChannelParametersFragment(); - timebaseTriggerFragment = new TimebaseTriggerFragment(); - dataAnalysisFragment = new DataAnalysisFragment(); - xyPlotFragment = new XYPlotFragment(); - playbackFragment = new OscilloscopePlaybackFragment(); - - if (findViewById(R.id.layout_dock_os2) != null) { - addFragment(R.id.layout_dock_os2, channelParametersFragment); - } - - channelParametersButton.setOnClickListener(this); - timebaseButton.setOnClickListener(this); - dataAnalysisButton.setOnClickListener(this); - xyPlotButton.setOnClickListener(this); - channelParametersTextView.setOnClickListener(this); - timebaseTiggerTextView.setOnClickListener(this); - dataAnalysisTextView.setOnClickListener(this); - xyPlotTextView.setOnClickListener(this); - - measurementsList = findViewById(R.id.recyclerView); - - chartInit(); - - final Runnable runnable = new Runnable() { - - private final List channels = new ArrayList<>(); - - @Override - public void run() { - //Thread to check which checkbox is enabled - while (monitor) { - if (isRunning) { - if (isInBuiltMicSelected && audioJack == null) { - audioJack = new AudioJack("input"); - } - - channels.clear(); - - if (scienceLab.isConnected() && isXYPlotSelected) { - xyPlotTask = new XYPlotTask(); - xyPlotTask.execute(xyPlotAxis1, xyPlotAxis2); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } else { - if (scienceLab.isConnected()) { - if (isCH1Selected) { - channels.add(CHANNEL.CH1.toString()); - } - if (isCH2Selected) { - channels.add(CHANNEL.CH2.toString()); - } - if (isCH3Selected) { - channels.add(CHANNEL.CH3.toString()); - } - } - if (isAudioInputSelected && isInBuiltMicSelected || (scienceLab.isConnected() && isMICSelected)) { - channels.add(CHANNEL.MIC.toString()); - } - captureTask = new CaptureTask(); - captureTask.execute(channels.toArray(new String[0])); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - if ((!isInBuiltMicSelected) && audioJack != null) { - audioJack.release(); - audioJack = null; - } - - if (!(((isCH1Selected || isCH2Selected || isCH3Selected || isMICSelected) && scienceLab.isConnected()) || isInBuiltMicSelected) && !mChart.isEmpty()) { - mChart.post(() -> mChart.clearValues()); - } - } - } - } - }; - monitorThread = new Thread(runnable); - monitorThread.start(); - - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - recordedOscilloscopeData = LocalDataLog.with() - .getBlockOfOscilloscopeRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - isPlayingback = true; - setLayoutForPlayback(); - } - } - - @SuppressLint("NewApi") - @Override - public void onWindowFocusChanged(boolean hasFocus) { - super.onWindowFocusChanged(hasFocus); - if (hasFocus) { - getWindow().getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); - } - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.activity_landscape_menu, menu); - return true; - } - - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - playMenu = menu.findItem(R.id.play_data); - menu.findItem(R.id.record_pause_data).setVisible(!isPlayingback); - menu.findItem(R.id.play_data).setVisible(isPlayingback); - return super.onPrepareOptionsMenu(menu); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - finish(); - break; - case R.id.run_stop: - if (isRunning) { - isRunning = false; - item.setTitle(R.string.control_run); - } else { - isRunning = true; - item.setTitle(R.string.control_stop); - } - break; - case R.id.record_pause_data: - if (isRecording) { - isRecording = false; - item.setIcon(R.drawable.ic_record_white); - CustomSnackBar.showSnackBar(mainLayout, - getString(R.string.csv_store_text) + " " + csvLogger.getCurrentFilePath() - , getString(R.string.open), new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(OscilloscopeActivity.this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getResources().getString(R.string.oscilloscope)); - startActivity(intent); - } - }, Snackbar.LENGTH_SHORT); - } else if (!isRecording && !scienceLab.isConnected()) { - CustomSnackBar.showSnackBar(mainLayout, getString(R.string.device_not_connected), null, null, Snackbar.LENGTH_SHORT); - - } else { - isRecording = true; - item.setIcon(R.drawable.ic_record_stop_white); - block = System.currentTimeMillis(); - if (gpsLogger.isGPSEnabled()) { - Location location = gpsLogger.getDeviceLocation(); - if (location != null) { - lat = location.getLatitude(); - lon = location.getLongitude(); - } else { - lat = 0.0; - lon = 0.0; - } - } else { - lat = 0.0; - lon = 0.0; - } - csvLogger = new CSVLogger(getResources().getString(R.string.oscilloscope)); - csvLogger.prepareLogFile(); - csvLogger.writeMetaData(getResources().getString(R.string.oscilloscope)); - csvLogger.writeCSVFile(CSV_HEADER); - recordSensorDataBlockID(new SensorDataBlock(block, getResources().getString(R.string.oscilloscope))); - CustomSnackBar.showSnackBar(mainLayout, getString(R.string.data_recording_start), null, null, Snackbar.LENGTH_SHORT); - } - break; - case R.id.show_guide: - toggleGuide(); - break; - case R.id.show_logged_data: - Intent intent = new Intent(OscilloscopeActivity.this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getResources().getString(R.string.oscilloscope)); - startActivity(intent); - break; - case R.id.play_data: - if (isPlaying) { - isPlaying = false; - item.setIcon(R.drawable.ic_play_arrow_white_24dp); - pauseData(); - } else { - isPlaying = true; - item.setIcon(R.drawable.ic_pause_white_24dp); - playRecordedData(); - } - break; - case R.id.auto_scale: - if (((isCH1Selected || isCH2Selected || isCH3Selected || isMICSelected) && scienceLab.isConnected()) || isInBuiltMicSelected) { - autoScale(); - } - break; - case R.id.measurements: - if (!isMeasurementsChecked) { - isMeasurementsChecked = true; - item.setChecked(true); - measurementsList.setVisibility(View.VISIBLE); - } else { - isMeasurementsChecked = false; - item.setChecked(false); - measurementsList.setVisibility(View.INVISIBLE); - } - default: - break; - } - return true; - } - - private void setLayoutForPlayback() { - findViewById(R.id.layout_dock_os1).setVisibility(View.GONE); - RelativeLayout.LayoutParams lineChartParams = (RelativeLayout.LayoutParams) mChartLayout.getLayoutParams(); - RelativeLayout.LayoutParams frameLayoutParams = (RelativeLayout.LayoutParams) frameLayout.getLayoutParams(); - lineChartParams.height = height * 3 / 4; - lineChartParams.width = RelativeLayout.LayoutParams.MATCH_PARENT; - mChartLayout.setLayoutParams(lineChartParams); - frameLayoutParams.height = height / 4; - frameLayoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT; - frameLayout.setLayoutParams(frameLayoutParams); - replaceFragment(R.id.layout_dock_os2, playbackFragment, "Playback Fragment"); - } - - public void playRecordedData() { - final Handler handler = new Handler(); - if (playbackTimer == null) { - playbackTimer = new Timer(); - } - playbackTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - try { - if (currentPosition < recordedOscilloscopeData.size()) { - OscilloscopeData data = recordedOscilloscopeData.get(currentPosition); - int mode = data.getMode(); - List dataSets = new ArrayList<>(); - ArrayList> entries = new ArrayList<>(); - for (int i = 0; i < mode; i++) { - data = recordedOscilloscopeData.get(currentPosition); - entries.add(new ArrayList<>()); - String[] xData = data.getDataX().split(" "); - String[] yData = data.getDataY().split(" "); - if (!isPlaybackFourierChecked) { - int n = Math.min(xData.length, yData.length); - for (int j = 0; j < n; j++) { - if (xData[j].length() > 0 && yData[j].length() > 0) { - entries.get(i).add(new Entry(Float.valueOf(xData[j]), Float.valueOf(yData[j]))); - } - } - setLeftYAxisScale(16f, -16f); - setRightYAxisScale(16f, -16f); - setXAxisScale(data.getTimebase()); - } else { - Complex[] yComplex = new Complex[yData.length]; - for (int j = 0; j < yData.length; j++) { - yComplex[j] = Complex.valueOf(Double.valueOf(yData[j])); - } - Complex[] fftOut = fft(yComplex); - int n = fftOut.length; - double mA = 0; - double factor = samples * timeGap * 1e-3; - double mF = (n / 2 - 1) / factor; - for (int j = 0; j < n / 2; j++) { - float y = (float) fftOut[j].abs() / samples; - if (y > mA) { - mA = y; - } - entries.get(i).add(new Entry((float) (j / factor), y)); - } - setLeftYAxisScale(mA, 0); - setRightYAxisScale(mA, 0); - setXAxisScale(mF); - } - currentPosition++; - LineDataSet dataSet; - dataSet = new LineDataSet(entries.get(i), data.getChannel()); - dataSet.setDrawCircles(false); - dataSet.setColor(channelColors[i]); - dataSets.add(dataSet); - ((OscilloscopePlaybackFragment) playbackFragment).setTimeBase(String.valueOf(data.getTimebase())); - } - LineData lineData = new LineData(dataSets); - mChart.setData(lineData); - mChart.notifyDataSetChanged(); - mChart.invalidate(); - } else { - playbackTimer.cancel(); - playbackTimer = null; - playMenu.setIcon(R.drawable.ic_play_arrow_white_24dp); - currentPosition = 0; - } - } catch (Exception e) { - if (playbackTimer != null) { - playbackTimer.cancel(); - playbackTimer = null; - } - playMenu.setIcon(R.drawable.ic_play_arrow_white_24dp); - currentPosition = 0; - } - } - }); - - } - }, 0, recordPeriod); - } - - public void pauseData() { - if (playbackTimer != null) { - playbackTimer.cancel(); - playbackTimer = null; - } - } - - private void logChannelData(String[] channels) { - long timestamp = System.currentTimeMillis(); - int noOfChannels = channels.length; - String dateTime = CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp)); - for (int i = 0; i < noOfChannels; i++) { - recordSensorData(new OscilloscopeData(timestamp + i, block, noOfChannels, channels[i], loggingXdata, loggingYdata[i], xAxisScale, lat, lon)); - csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(dateTime) - .add(noOfChannels) - .add(channels[i]) - .add(loggingXdata) - .add(loggingYdata[i]) - .add(xAxisScale) - .add(lat) - .add(lon) - ); - } - } - - @Override - protected void onResume() { - super.onResume(); - removeStatusBar(); - } - - private void removeStatusBar() { - if (Build.VERSION.SDK_INT < 16) { - getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, - WindowManager.LayoutParams.FLAG_FULLSCREEN); - } else { - View decorView = getWindow().getDecorView(); - - decorView.setSystemUiVisibility((View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)); - } - } - - @Override - public void onClick(View v) { - switch (v.getId()) { - case R.id.button_channel_parameters_os: - case R.id.tv_channel_parameters_os: - replaceFragment(R.id.layout_dock_os2, channelParametersFragment, "ChannelParametersFragment"); - clearTextBackgroundColor(); - channelParametersTextView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark)); - isDataAnalysisFragSelected = false; - break; - - case R.id.button_timebase_os: - case R.id.tv_timebase_tigger_os: - replaceFragment(R.id.layout_dock_os2, timebaseTriggerFragment, "TimebaseTiggerFragment"); - clearTextBackgroundColor(); - timebaseTiggerTextView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark)); - isDataAnalysisFragSelected = false; - break; - - case R.id.button_data_analysis_os: - case R.id.tv_data_analysis_os: - replaceFragment(R.id.layout_dock_os2, dataAnalysisFragment, "DataAnalysisFragment"); - clearTextBackgroundColor(); - dataAnalysisTextView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark)); - isDataAnalysisFragSelected = true; - break; - - case R.id.button_xy_plot_os: - case R.id.tv_xy_plot_os: - replaceFragment(R.id.layout_dock_os2, xyPlotFragment, "XYPlotFragment"); - clearTextBackgroundColor(); - xyPlotTextView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark)); - isDataAnalysisFragSelected = false; - break; - - default: - break; - } - } - - @SuppressLint("ResourceType") - private void clearTextBackgroundColor() { - channelParametersTextView.setBackgroundColor(getResources().getColor(R.color.customBorderFill)); - timebaseTiggerTextView.setBackgroundColor(getResources().getColor(R.color.customBorderFill)); - dataAnalysisTextView.setBackgroundColor(getResources().getColor(R.color.customBorderFill)); - xyPlotTextView.setBackgroundColor(getResources().getColor(R.color.customBorderFill)); - } - - public void onWindowFocusChanged() { - RelativeLayout.LayoutParams lineChartParams = (RelativeLayout.LayoutParams) mChartLayout.getLayoutParams(); - RelativeLayout.LayoutParams frameLayoutParams = (RelativeLayout.LayoutParams) frameLayout.getLayoutParams(); - if (getResources().getBoolean(R.bool.isTablet)) { - lineChartParams.height = height * 3 / 4; - lineChartParams.width = width * 9 / 10; - mChartLayout.setLayoutParams(lineChartParams); - frameLayoutParams.height = height / 4; - frameLayoutParams.width = width * 9 / 10; - frameLayout.setLayoutParams(frameLayoutParams); - } else { - lineChartParams.height = height * 3 / 5; - lineChartParams.width = width * 7 / 8; - mChartLayout.setLayoutParams(lineChartParams); - frameLayoutParams.height = height * 2 / 5; - frameLayoutParams.width = width * 7 / 8; - frameLayout.setLayoutParams(frameLayoutParams); - } - } - - protected void addFragment(@IdRes int containerViewId, - @NonNull Fragment fragment) { - getSupportFragmentManager().beginTransaction() - .add(containerViewId, fragment, "ChannelParametersFragment").commit(); - } - - protected void replaceFragment(@IdRes int containerViewId, - @NonNull Fragment fragment, - @NonNull String fragmentTag) { - getSupportFragmentManager().beginTransaction() - .replace(containerViewId, fragment, fragmentTag).commit(); - } - - @Override - public void onBackPressed() { - finish(); - } - - @Override - protected void onDestroy() { - monitor = false; - if (captureTask != null) { - captureTask.cancel(true); - } - if (recordTimer != null) { - recordTimer.cancel(); - recordTimer = null; - } - if (audioJack != null) { - audioJack.release(); - audioJack = null; - } - super.onDestroy(); - } - - public void chartInit() { - mChart.setTouchEnabled(true); - mChart.setHighlightPerDragEnabled(true); - mChart.setDragEnabled(true); - mChart.setScaleEnabled(true); - mChart.setDrawGridBackground(false); - mChart.setPinchZoom(true); - mChart.setScaleYEnabled(false); - mChart.setBackgroundColor(Color.BLACK); - mChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mChart.setData(data); - - Legend l = mChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x1.setTextColor(Color.WHITE); - x1.setDrawGridLines(true); - x1.setAvoidFirstLastClipping(true); - x1.setAxisMinimum(0f); - x1.setAxisMaximum(875f); - - y1.setTextColor(Color.WHITE); - y1.setAxisMaximum(16f); - y1.setAxisMinimum(-16f); - y1.setDrawGridLines(true); - - y2.setAxisMaximum(16f); - y2.setAxisMinimum(-16f); - y2.setTextColor(Color.WHITE); - y2.setEnabled(true); - } - - public void setXAxisScale(double timebase) { - x1.setAxisMinimum(0); - x1.setAxisMaximum((float) timebase); - if (timebase == 875f) - xAxisLabelUnit.setText("(μs)"); - else - xAxisLabelUnit.setText("(ms)"); - - this.timebase = timebase; - mChart.fitScreen(); - mChart.invalidate(); - } - - public void setLeftYAxisScale(double upperLimit, double lowerLimit) { - y1.setAxisMaximum((float) upperLimit); - y1.setAxisMinimum((float) lowerLimit); - if (upperLimit == 500f) - leftYAxisLabelUnit.setText("(mV)"); - else - leftYAxisLabelUnit.setText("(V)"); - mChart.fitScreen(); - mChart.invalidate(); - } - - public void setRightYAxisScale(double upperLimit, double lowerLimit) { - y2.setAxisMaximum((float) upperLimit); - y2.setAxisMinimum((float) lowerLimit); - if (upperLimit == 500f) - rightYAxisLabelUnit.setText("(mV)"); - else - rightYAxisLabelUnit.setText("(V)"); - mChart.fitScreen(); - mChart.invalidate(); - } - - public void setLeftYAxisLabel(String leftYAxisInput) { - leftYAxisLabel.setText(leftYAxisInput); - } - - public void setXAxisLabel(String xAxisInput) { - xAxisLabel.setText(xAxisInput); - } - - public class CaptureTask extends AsyncTask { - private final ArrayList> entries = new ArrayList<>(); - private final ArrayList> curveFitEntries = new ArrayList<>(); - private Integer noOfChannels; - private String[] paramsChannels; - private String channel; - - @Override - protected Void doInBackground(String... channels) { - paramsChannels = channels; - noOfChannels = channels.length; - if (isInBuiltMicSelected) { - noOfChannels--; - } - try { - double[] xData; - double[] yData; - double xValue; - ArrayList yDataString = new ArrayList<>(); - String[] xDataString = null; - maxAmp = 0; - scienceLab.captureTraces(4, samples, timeGap, channel, false, null); - Thread.sleep((long) (samples * timeGap * 1e-3)); - for (int i = 0; i < noOfChannels; i++) { - entries.add(new ArrayList<>()); - channel = channels[i]; - isTriggered = false; - HashMap data; - data = scienceLab.fetchTrace(channelIndexMap.get(channel)); - xData = data.get("x"); - yData = data.get("y"); - xValue = xData[0]; - int n = Math.min(xData.length, yData.length); - xDataString = new String[n]; - yDataString.add(new String[n]); - Complex[] fftOut = null; - if (isFourierTransformSelected) { - Complex[] yComplex = new Complex[yData.length]; - for (int j = 0; j < yData.length; j++) { - yComplex[j] = Complex.valueOf(yData[j]); - } - fftOut = fft(yComplex); - } - double factor = samples * timeGap * 1e-3; - maxFreq = (n / 2 - 1) / factor; - double mA = 0; - double prevY = yData[0]; - boolean increasing = false; - for (int j = 0; j < n; j++) { - double currY = yData[j]; - xData[j] = xData[j] / ((timebase == 875) ? 1 : 1000); - if (!isFourierTransformSelected) { - if (isTriggerSelected && triggerChannel.equals(channel)) { - if (currY > prevY) { - increasing = true; - } else if (currY < prevY && increasing) { - increasing = false; - } - if (isTriggered) { - double k = xValue / ((timebase == 875) ? 1 : 1000); - entries.get(i).add(new Entry((float) k, (float) yData[j])); - xValue += timeGap; - } - if (Objects.equals(triggerMode, MODE.RISING.toString()) && prevY < trigger && currY >= trigger && increasing) { - isTriggered = true; - } else if (Objects.equals(triggerMode, MODE.FALLING.toString()) && prevY > trigger && currY <= trigger && !increasing) { - isTriggered = true; - } else if (Objects.equals(triggerMode, MODE.DUAL.toString()) && ((prevY < trigger && currY >= trigger && increasing) || (prevY > trigger && currY <= trigger && !increasing))) { - isTriggered = true; - } - prevY = currY; - } else { - entries.get(i).add(new Entry((float) xData[j], (float) yData[j])); - } - } else { - if (j < n / 2) { - float y = (float) fftOut[j].abs() / samples; - if (y > mA) { - mA = y; - } - entries.get(i).add(new Entry((float) (j / factor), y)); - } - } - xDataString[j] = String.valueOf(xData[j]); - yDataString.get(i)[j] = String.valueOf(yData[j]); - } - if (sineFit && isDataAnalysisFragSelected && channel.equals(curveFittingChannel1)) { - if (curveFitEntries.size() == 0 || curveFitEntries.get(curveFitEntries.size() - 1) == null) { - curveFitEntries.add(new ArrayList<>()); - } - double[] sinFit = analyticsClass.sineFit(xData, yData); - double amp = sinFit[0]; - double freq = sinFit[1]; - double offset = sinFit[2]; - double phase = sinFit[3]; - - freq = freq / 1e6; - double max = xData[xData.length - 1]; - for (int j = 0; j < 500; j++) { - double x = j * max / 500; - double y = offset + amp * Math.sin(Math.abs(freq * (2 * Math.PI)) * x + phase * Math.PI / 180); - curveFitEntries.get(curveFitEntries.size() - 1).add(new Entry((float) x, (float) y)); - } - } - - if (squareFit && isDataAnalysisFragSelected && channel.equals(curveFittingChannel1)) { - if (curveFitEntries.size() == 0 || curveFitEntries.get(curveFitEntries.size() - 1) == null) { - curveFitEntries.add(new ArrayList<>()); - } - double[] sqFit = analyticsClass.squareFit(xData, yData); - double amp = sqFit[0]; - double freq = sqFit[1]; - double phase = sqFit[2]; - double dc = sqFit[3]; - double offset = sqFit[4]; - - freq = freq / 1e6; - double max = xData[xData.length - 1]; - for (int j = 0; j < 500; j++) { - double x = j * max / 500; - double t = 2 * Math.PI * freq * (x - phase); - double y; - if (t % (2 * Math.PI) < 2 * Math.PI * dc) { - y = offset + amp; - } else { - y = offset - 2 * amp; - } - curveFitEntries.get(curveFitEntries.size() - 1).add(new Entry((float) x, (float) y)); - } - } - if (mA > maxAmp) { - maxAmp = mA; - } - } - - - if (isInBuiltMicSelected) { - noOfChannels++; - isTriggered = false; - entries.add(new ArrayList<>()); - if (audioJack == null) { - audioJack = new AudioJack("input"); - } - short[] buffer = audioJack.read(); - yDataString.add(new String[buffer.length]); - - int n = buffer.length; - Complex[] fftOut = null; - if (isFourierTransformSelected) { - Complex[] yComplex = new Complex[n]; - for (int j = 0; j < n; j++) { - float audioValue = (float) map(buffer[j], -32768, 32767, -3, 3); - yComplex[j] = Complex.valueOf(audioValue); - } - fftOut = fft(yComplex); - } - double factor = buffer.length * timeGap * 1e-3; - maxFreq = (n / 2 - 1) / factor; - double mA = 0; - if (xDataString == null) { - xDataString = new String[n]; - } - float prevY = (float) map(buffer[0], -32768, 32767, -3, 3); - boolean increasing = false; - double xDataPoint = 0; - for (int i = 0; i < n; i++) { - float j = (float) (((double) i / SAMPLING_RATE) * 1000000.0); - j = j / ((timebase == 875) ? 1 : 1000); - float audioValue = (float) map(buffer[i], -32768, 32767, -3, 3); - float currY = audioValue; - if (!isFourierTransformSelected) { - if (noOfChannels == 1) { - xDataString[i] = String.valueOf(j); - } - if (isTriggerSelected && triggerChannel.equals(CHANNEL.MIC.toString())) { - if (currY > prevY) { - increasing = true; - } else if (currY < prevY) { - increasing = false; - } - if (Objects.equals(triggerMode, MODE.RISING.toString()) && prevY < trigger && currY >= trigger && increasing) { - isTriggered = true; - } else if (Objects.equals(triggerMode, MODE.FALLING.toString()) && prevY > trigger && currY <= trigger && !increasing) { - isTriggered = true; - } else if (Objects.equals(triggerMode, MODE.DUAL.toString()) && ((prevY < trigger && currY >= trigger && increasing) || (prevY > trigger && currY <= trigger && !increasing))) { - isTriggered = true; - } - if (isTriggered) { - float k = (float) ((xDataPoint / SAMPLING_RATE) * 1000000.0); - k = k / ((timebase == 875) ? 1 : 1000); - entries.get(entries.size() - 1).add(new Entry(k, audioValue)); - xDataPoint++; - } - prevY = currY; - } else { - entries.get(entries.size() - 1).add(new Entry(j, audioValue)); - } - } else { - if (i < n / 2) { - float y = (float) fftOut[i].abs() / samples; - if (y > mA) { - mA = y; - } - entries.get(entries.size() - 1).add(new Entry((float) (i / factor), y)); - } - } - yDataString.get(yDataString.size() - 1)[i] = String.valueOf(audioValue); - } - if (mA > maxAmp) { - maxAmp = mA; - } - - } - if (isRecording) { - loggingXdata = StringUtils.join(" ", xDataString); - for (int i = 0; i < yDataString.size(); i++) { - loggingYdata[i] = StringUtils.join(" ", yDataString.get(i)); - } - runOnUiThread(new Runnable() { - @Override - public void run() { - logChannelData(paramsChannels); - } - }); - } - - } catch (NullPointerException e) { - cancel(true); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - dataEntries = new ArrayList<>(entries); - dataParamsChannels = paramsChannels.clone(); - - List dataSets = new ArrayList<>(); - if (!isFourierTransformSelected) { - for (int i = 0; i < Math.min(entries.size(), paramsChannels.length); i++) { - ArrayList entryArrayList = entries.get(i); - for (int j = 0; j < entryArrayList.size(); j++) { - Entry entry = entryArrayList.get(j); - entry.setX((float) (entry.getX() - xOffsets.get(paramsChannels[i]))); - entry.setY((float) (entry.getY() + yOffsets.get(paramsChannels[i]))); - } - } - } - - if (!isFourierTransformSelected) { - for (int i = 0; i < Math.min(entries.size(), paramsChannels.length); i++) { - CHANNEL channel = CHANNEL.valueOf(paramsChannels[i]); - double minY = Double.MAX_VALUE; - double maxY = -1 * Double.MIN_VALUE; - double yRange; - double[] voltage = new double[512]; - ArrayList entryArrayList = dataEntries.get(i); - for (int j = 0; j < entryArrayList.size(); j++) { - Entry entry = entryArrayList.get(j); - if (j < voltage.length - 1) { - voltage[j] = entry.getY(); - } - if (entry.getY() > maxY) { - maxY = entry.getY(); - } - if (entry.getY() < minY) { - minY = entry.getY(); - } - } - final double frequency; - if (Objects.equals(dataParamsChannels[i], CHANNEL.MIC.toString())) { - frequency = analyticsClass.findFrequency(voltage, ((double) 1 / SAMPLING_RATE)); - } else { - frequency = analyticsClass.findFrequency(voltage, timeGap / 1000000.0); - } - double period = (1 / frequency) * 1000.0; - yRange = maxY - minY; - OscilloscopeMeasurements.channel.get(channel).put(ChannelMeasurements.FREQUENCY, frequency); - OscilloscopeMeasurements.channel.get(channel).put(ChannelMeasurements.PERIOD, period); - OscilloscopeMeasurements.channel.get(channel).put(ChannelMeasurements.AMPLITUDE, yRange); - OscilloscopeMeasurements.channel.get(channel).put(ChannelMeasurements.POSITIVE_PEAK, maxY); - OscilloscopeMeasurements.channel.get(channel).put(ChannelMeasurements.NEGATIVE_PEAK, minY); - } - } - - for (int i = 0; i < Math.min(entries.size(), paramsChannels.length); i++) { - LineDataSet dataSet; - dataSet = new LineDataSet(entries.get(i), paramsChannels[i]); - dataSet.setDrawCircles(false); - dataSet.setColor(channelColors[i]); - dataSets.add(dataSet); - - } - for (int i = 0; i < curveFitEntries.size(); i++) { - LineDataSet dataSet; - dataSet = new LineDataSet(curveFitEntries.get(i), "Fit"); - dataSet.setDrawCircles(false); - dataSet.setColor(Color.YELLOW); - dataSets.add(dataSet); - } - LineData data = new LineData(dataSets); - if (isFourierTransformSelected) { - setXAxisScale(maxFreq); - setLeftYAxisScale(maxAmp, 0); - setRightYAxisScale(maxAmp, 0); - } else { - setXAxisScale(xAxisScale); - setLeftYAxisScale(yAxisScale, -1 * yAxisScale); - setRightYAxisScale(yAxisScale, -1 * yAxisScale); - } - if (isMeasurementsChecked) { - RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(OscilloscopeActivity.this); - measurementsList.setItemAnimator(new DefaultItemAnimator()); - measurementsList.setLayoutManager(layoutManager); - OscilloscopeMeasurementsAdapter adapter = new OscilloscopeMeasurementsAdapter(dataParamsChannels, channelColors); - measurementsList.setAdapter(adapter); - } - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.invalidate(); - synchronized (lock) { - lock.notify(); - } - } - } - - public void autoScale() { - double minY = Double.MAX_VALUE; - double maxY = Double.MIN_VALUE; - double maxPeriod = -1 * Double.MIN_VALUE; - double yRange; - double yPadding; - double[] voltage = new double[512]; - for (int i = 0; i < dataParamsChannels.length; i++) { - if (dataEntries.size() > i) { - ArrayList entryArrayList = dataEntries.get(i); - for (int j = 0; j < entryArrayList.size(); j++) { - Entry entry = entryArrayList.get(j); - if (j < voltage.length - 1) { - voltage[j] = entry.getY(); - } - if (entry.getY() > maxY) { - maxY = entry.getY(); - } - if (entry.getY() < minY) { - minY = entry.getY(); - } - } - final double frequency; - if (Objects.equals(dataParamsChannels[i], CHANNEL.MIC.toString())) { - frequency = analyticsClass.findSignalFrequency(voltage, ((double) 1 / SAMPLING_RATE)); - } else { - frequency = analyticsClass.findSignalFrequency(voltage, timeGap / 1000000.0); - } - double period = (1 / frequency) * 1000.0; - if (period > maxPeriod) { - maxPeriod = period; - } - } - } - yRange = maxY - minY; - yPadding = yRange * 0.1; - if (maxPeriod > 0) { - xAxisScale = Math.min((maxPeriod * 5), maxTimebase); - if (Math.abs(maxY) >= Math.abs(minY)) { - yAxisScale = maxY + yPadding; - } else { - yAxisScale = -1 * (minY - yPadding); - } - samples = 512; - timeGap = (2 * xAxisScale * 1000.0) / samples; - } else { - Toast.makeText(this, getString(R.string.auto_scale_error), Toast.LENGTH_SHORT).show(); - } - } - - public class XYPlotTask extends AsyncTask { - private String analogInput1; - private String analogInput2; - private float[] xFloatData; - private float[] yFloatData; - - @Override - protected Void doInBackground(String... params) { - analogInput1 = params[0]; - analogInput2 = params[1]; - HashMap data; - if (analogInput1.equals(analogInput2)) { - scienceLab.captureTraces(1, samples, timeGap, analogInput1, isTriggerSelected, null); - data = scienceLab.fetchTrace(1); - double[] yData = data.get("y"); - int n = yData.length; - xFloatData = new float[n]; - yFloatData = new float[n]; - for (int i = 0; i < n; i++) { - xFloatData[i] = (float) yData[i]; - yFloatData[i] = (float) yData[i]; - } - } else { - int noChannels = 1; - if ((analogInput1.equals(CHANNEL.CH1.toString()) && analogInput2.equals(CHANNEL.CH2.toString())) || (analogInput1.equals(CHANNEL.CH2.toString()) && analogInput2.equals(CHANNEL.CH1.toString()))) { - noChannels = 2; - scienceLab.captureTraces(noChannels, 175, timeGap, "CH1", isTriggerSelected, null); - data = scienceLab.fetchTrace(1); - double[] yData1 = data.get("y"); - data = scienceLab.fetchTrace(2); - double[] yData2 = data.get("y"); - int n = Math.min(yData1.length, yData2.length); - xFloatData = new float[n]; - yFloatData = new float[n]; - for (int i = 0; i < n; i++) { - xFloatData[i] = (float) yData1[i]; - yFloatData[i] = (float) yData2[i]; - } - - } else { - noChannels = 4; - scienceLab.captureTraces(noChannels, 175, timeGap, "CH1", isTriggerSelected, null); - data = scienceLab.fetchTrace(channelIndexMap.get(analogInput1) + 1); - double[] yData1 = data.get("y"); - data = scienceLab.fetchTrace(channelIndexMap.get(analogInput2) + 1); - double[] yData2 = data.get("y"); - int n = Math.min(yData1.length, yData2.length); - xFloatData = new float[n]; - yFloatData = new float[n]; - for (int i = 0; i < n; i++) { - xFloatData[i] = (float) yData1[i]; - yFloatData[i] = (float) yData2[i]; - } - } - - } - try { - Thread.sleep(200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - graph.plotData(xFloatData, yFloatData, 1); - synchronized (lock) { - lock.notify(); - } - } - } - - public Complex[] fft(Complex[] input) { - Complex[] x = input; - int n = x.length; - - if (n == 1) return new Complex[]{x[0]}; - - if (n % 2 != 0) { - x = Arrays.copyOfRange(x, 0, x.length - 1); - } - - Complex[] halfArray = new Complex[n / 2]; - for (int k = 0; k < n / 2; k++) { - halfArray[k] = x[2 * k]; - } - Complex[] q = fft(halfArray); - - for (int k = 0; k < n / 2; k++) { - halfArray[k] = x[2 * k + 1]; - } - Complex[] r = fft(halfArray); - - Complex[] y = new Complex[n]; - for (int k = 0; k < n / 2; k++) { - double kth = -2 * k * Math.PI / n; - Complex wk = new Complex(Math.cos(kth), Math.sin(kth)); - if (r[k] == null) { - r[k] = new Complex(1); - } - if (q[k] == null) { - q[k] = new Complex(1); - } - y[k] = q[k].add(wk.multiply(r[k])); - y[k + n / 2] = q[k].subtract(wk.multiply(r[k])); - } - return y; - } - - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((OscilloscopeData) sensorData); - realm.commitTransaction(); - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/activity/PowerSourceActivity.java b/app/src/main/java/io/pslab/activity/PowerSourceActivity.java deleted file mode 100644 index 819759501..000000000 --- a/app/src/main/java/io/pslab/activity/PowerSourceActivity.java +++ /dev/null @@ -1,1073 +0,0 @@ -package io.pslab.activity; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.pm.ActivityInfo; -import android.location.Location; -import android.location.LocationManager; -import android.os.Bundle; -import android.os.Handler; -import android.text.Editable; -import android.util.Log; -import android.util.Range; -import android.view.KeyEvent; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.MotionEvent; -import android.view.View; -import android.view.inputmethod.EditorInfo; -import android.widget.EditText; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.widget.Toolbar; -import androidx.coordinatorlayout.widget.CoordinatorLayout; -import androidx.core.content.res.ResourcesCompat; -import androidx.core.widget.TextViewCompat; - -import com.google.android.material.snackbar.Snackbar; -import com.sdsmdg.harjot.crollerTest.Croller; -import com.sdsmdg.harjot.crollerTest.OnCrollerChangeListener; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.Date; -import java.util.Locale; -import java.util.Timer; -import java.util.TimerTask; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.pslab.R; -import io.pslab.activity.guide.GuideActivity; -import io.pslab.communication.CommunicationHandler; -import io.pslab.communication.ScienceLab; -import io.pslab.items.SquareImageButton; -import io.pslab.models.PowerSourceData; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.GPSLogger; -import io.pslab.others.LocalDataLog; -import io.pslab.others.ScienceLabCommon; -import io.realm.Realm; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class PowerSourceActivity extends GuideActivity { - - private final static String TAG = PowerSourceActivity.class.getSimpleName(); - - public static final String POWER_PREFERENCES = "Power_Preferences"; - private static final CSVDataLine CSV_HEADER = new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("PV1") - .add("PV2") - .add("PV3") - .add("PCS") - .add("Latitude") - .add("Longitude"); - - private static final String VOLTAGE_FORMAT = "%f V"; - private static final String CURRENT_FORMAT = "%f mA"; - - private static final int CONTROLLER_MIN = 1; - private static final int PV1_CONTROLLER_MAX = 1001; - private static final int PV2_CONTROLLER_MAX = 661; - private static final int PV3_CONTROLLER_MAX = 331; - private static final int PCS_CONTROLLER_MAX = 331; - - private static final Range PV1_VOLTAGE_RANGE = Range.create(-5.0f, 5.0f); - private static final Range PV2_VOLTAGE_RANGE = Range.create(-3.30f, 3.30f); - private static final Range PV3_VOLTAGE_RANGE = Range.create(0.0f, 3.30f); - private static final Range PCS_CURRENT_RANGE = Range.create(0.0f, 3.30f); - - private final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault()); - - /** - * Step of one tap on an up or down button. - */ - private static final float STEP = 0.01f; - - private static final long LONG_CLICK_DELAY = 100; - private static final String KEY_LOG = "has_log"; - private static final String DATA_BLOCK = "data_block"; - - @BindView(R.id.toolbar) - Toolbar toolbar; - @BindView(R.id.power_card_pv1_controller) - Croller controllerPV1; - @BindView(R.id.power_card_pv1_display) - EditText displayPV1; - @BindView(R.id.power_card_pv1_up) - SquareImageButton upPV1; - @BindView(R.id.power_card_pv1_down) - SquareImageButton downPV1; - @BindView(R.id.power_source_coordinatorLayout) - CoordinatorLayout coordinatorLayout; - @BindView(R.id.power_card_pv2_controller) - Croller controllerPV2; - @BindView(R.id.power_card_pv2_display) - EditText displayPV2; - @BindView(R.id.power_card_pv2_up) - SquareImageButton upPV2; - @BindView(R.id.power_card_pv2_down) - SquareImageButton downPV2; - @BindView(R.id.power_card_pv3_controller) - Croller controllerPV3; - @BindView(R.id.power_card_pv3_display) - EditText displayPV3; - @BindView(R.id.power_card_pv3_up) - SquareImageButton upPV3; - @BindView(R.id.power_card_pv3_down) - SquareImageButton downPV3; - @BindView(R.id.power_card_pcs_controller) - Croller controllerPCS; - @BindView(R.id.power_card_pcs_display) - EditText displayPCS; - @BindView(R.id.power_card_pcs_up) - SquareImageButton upPCS; - @BindView(R.id.power_card_pcs_down) - SquareImageButton downPCS; - private CSVLogger powerSourceLogger = null; - private GPSLogger gpsLogger = null; - private Realm realm; - private Timer recordTimer = null; - private Timer playbackTimer = null; - private int currentPosition = 0; - private boolean playClicked = false; - private final long recordPeriod = 1000; - private boolean isRecording = false; - private Boolean writeHeaderToFile = true; - private SharedPreferences powerPreferences; - private boolean isRunning = false; - private boolean incrementPower = false, decrementPower = false; - private final ScienceLab scienceLab = ScienceLabCommon.scienceLab; - private RealmResults recordedPowerData; - private Timer powerCounter; - private final Handler powerHandler = new Handler(); - private long block; - private boolean isPlayingBack = false; - private MenuItem stopMenu; - private MenuItem playMenu; - - private float voltagePV1 = 0.00f, voltagePV2 = 0.00f, voltagePV3 = 0.00f, currentPCS = 0.00f; - - public PowerSourceActivity() { - super(R.layout.activity_power_source); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - ButterKnife.bind(this); - - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setDisplayHomeAsUpEnabled(true); - } - powerPreferences = getSharedPreferences(POWER_PREFERENCES, MODE_PRIVATE); - - gpsLogger = new GPSLogger(this, - (LocationManager) getSystemService(Context.LOCATION_SERVICE)); - realm = LocalDataLog.with().getRealm(); - - autoSize(displayPV1); - autoSize(displayPV2); - autoSize(displayPV3); - autoSize(displayPCS); - - displayPV1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - displayPV1.setCursorVisible(true); - } - }); - displayPV2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - displayPV2.setCursorVisible(true); - } - }); - displayPV3.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - displayPV3.setCursorVisible(true); - } - }); - displayPCS.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - displayPCS.setCursorVisible(true); - } - }); - displayPV1.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if (actionId == EditorInfo.IME_ACTION_DONE) { - final String voltageValue = remove(displayPV1.getText(), "V", "\\+").trim(); - final float voltage = PV1_VOLTAGE_RANGE.clamp(parseFloat(voltageValue, PV1_VOLTAGE_RANGE.getLower())); - setText(displayPV1, VOLTAGE_FORMAT, voltage); - controllerPV1.setProgress(mapPowerToProgress(voltage, PV1_CONTROLLER_MAX, - PV1_VOLTAGE_RANGE.getUpper(), PV1_VOLTAGE_RANGE.getLower())); - } - return false; - } - }); - - displayPV2.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if (actionId == EditorInfo.IME_ACTION_DONE) { - final String voltageValue = remove(displayPV2.getText(), "V", "\\+").trim(); - final float voltage = PV2_VOLTAGE_RANGE.clamp(parseFloat(voltageValue, PV2_VOLTAGE_RANGE.getLower())); - setText(displayPV2, VOLTAGE_FORMAT, voltage); - controllerPV2.setProgress(mapPowerToProgress(voltage, PV2_CONTROLLER_MAX, - PV2_VOLTAGE_RANGE.getUpper(), PV2_VOLTAGE_RANGE.getLower())); - } - return false; - } - }); - - displayPV3.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if (actionId == EditorInfo.IME_ACTION_DONE) { - final String voltageValue = remove(displayPV3.getText(), "V", "\\+").trim(); - final float voltage = PV3_VOLTAGE_RANGE.clamp(parseFloat(voltageValue, PV3_VOLTAGE_RANGE.getLower())); - setText(displayPV3, VOLTAGE_FORMAT, voltage); - controllerPV3.setProgress(mapPowerToProgress(voltage, PV3_CONTROLLER_MAX, - PV3_VOLTAGE_RANGE.getUpper(), PV3_VOLTAGE_RANGE.getLower())); - } - return false; - } - }); - - displayPCS.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if (actionId == EditorInfo.IME_ACTION_DONE) { - final String currentValue = remove(displayPCS.getText(), "mA", "\\+").trim(); - final float current = PCS_CURRENT_RANGE.clamp(parseFloat(currentValue, PCS_CURRENT_RANGE.getLower())); - setText(displayPV3, CURRENT_FORMAT, current); - controllerPCS.setProgress(mapPowerToProgress(current, PCS_CONTROLLER_MAX, - PCS_CURRENT_RANGE.getUpper(), PCS_CURRENT_RANGE.getLower())); - } - return false; - } - }); - - monitorControllers(controllerPV1, Pin.PV1, PV1_CONTROLLER_MAX); - monitorControllers(controllerPV2, Pin.PV2, PV2_CONTROLLER_MAX); - monitorControllers(controllerPV3, Pin.PV3, PV3_CONTROLLER_MAX); - monitorControllers(controllerPCS, Pin.PCS, PCS_CONTROLLER_MAX); - - monitorVariations(upPV1, downPV1, Pin.PV1); - monitorVariations(upPV2, downPV2, Pin.PV2); - monitorVariations(upPV3, downPV3, Pin.PV3); - monitorVariations(upPCS, downPCS, Pin.PCS); - - monitorLongClicks(upPV1, downPV1); - monitorLongClicks(upPV2, downPV2); - monitorLongClicks(upPV3, downPV3); - monitorLongClicks(upPCS, downPCS); - - updateDisplay(displayPV1, limitDigits(mapProgressToPower(retrievePowerValues(Pin.PV1), - PV1_CONTROLLER_MAX, PV1_VOLTAGE_RANGE.getUpper(), PV1_VOLTAGE_RANGE.getLower())), Pin.PV1); - updateDisplay(displayPV2, limitDigits(mapProgressToPower(retrievePowerValues(Pin.PV2), - PV2_CONTROLLER_MAX, PV2_VOLTAGE_RANGE.getUpper(), PV2_VOLTAGE_RANGE.getLower())), Pin.PV2); - updateDisplay(displayPV3, limitDigits(mapProgressToPower(retrievePowerValues(Pin.PV3), - PV3_CONTROLLER_MAX, PV3_VOLTAGE_RANGE.getUpper(), PV3_VOLTAGE_RANGE.getLower())), Pin.PV3); - updateDisplay(displayPCS, limitDigits(mapProgressToPower(retrievePowerValues(Pin.PCS), - PCS_CONTROLLER_MAX, PCS_CURRENT_RANGE.getUpper(), PCS_CURRENT_RANGE.getLower())), Pin.PCS); - - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - recordedPowerData = LocalDataLog.with() - .getBlockOfPowerRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - isPlayingBack = true; - disableButtons(); - } - - if (getResources().getBoolean(R.bool.isTablet)) { - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER); - } - - if (!scienceLab.isConnected() && savedInstanceState != null) { - displayPV1.setText(savedInstanceState.getString("displayPV1")); - displayPV1.onEditorAction(EditorInfo.IME_ACTION_DONE); - displayPV2.setText(savedInstanceState.getString("displayPV2")); - displayPV2.onEditorAction(EditorInfo.IME_ACTION_DONE); - displayPV3.setText(savedInstanceState.getString("displayPV3")); - displayPV3.onEditorAction(EditorInfo.IME_ACTION_DONE); - displayPCS.setText(savedInstanceState.getString("displayPCS")); - displayPCS.onEditorAction(EditorInfo.IME_ACTION_DONE); - } - } - - /** - * Parses text to produce a number respecting the current locale of the system. - * - * @param toBeParsed text to be parsed - * @param defaultValue fallback value to be used if text cannot be parsed - * @return number parsed from text - */ - private float parseFloat(@NonNull String toBeParsed, float defaultValue) { - float parsedValue = defaultValue; - try { - parsedValue = numberFormat.parse(toBeParsed).floatValue(); - } catch (ParseException e) { - Log.e(TAG, "Unable to parse " + toBeParsed, e); - } - - return parsedValue; - } - - /** - * Turns a value into a String representation that respects the current locale of the device - * and sets it to a TextVew. - * - * @param textView UI element which will display the text - * @param format formatted String which value will be inserted to - * @param value the value to display - */ - private static void setText(@NonNull TextView textView, @NonNull String format, float value) { - textView.setText(String.format(Locale.getDefault(), format, value)); - } - - private String remove(@NonNull Editable input, @NonNull String... toBeRemoved) { - return remove(input.toString(), toBeRemoved); - } - - private String remove(@NonNull String input, @NonNull String... toBeRemoved) { - String output = input; - for (String s : toBeRemoved) { - output = output.replaceAll(s, ""); - } - return output; - } - - /** - * Autosize the voltage display in textView to utilize empty space - * - * @param view Display text view - */ - private void autoSize(TextView view) { - TextViewCompat.setAutoSizeTextTypeWithDefaults(view, - TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.power_source_menu, menu); - return true; - } - - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - if (isPlayingBack) { - menu.findItem(R.id.play_data).setVisible(true); - menu.findItem(R.id.stop_data).setVisible(false); - menu.findItem(R.id.power_source_record_data).setVisible(false); - } else { - menu.findItem(R.id.play_data).setVisible(false); - menu.findItem(R.id.stop_data).setVisible(false); - menu.findItem(R.id.power_source_record_data).setVisible(true); - } - stopMenu = menu.findItem(R.id.stop_data); - playMenu = menu.findItem(R.id.play_data); - return super.onPrepareOptionsMenu(menu); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.show_guide: - toggleGuide(); - break; - case R.id.power_source_record_data: - if (!isRecording) { - item.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_record_stop_white, null)); - isRecording = true; - if (recordTimer == null) { - recordTimer = new Timer(); - } else { - recordTimer.cancel(); - recordTimer = new Timer(); - } - CustomSnackBar.showSnackBar(coordinatorLayout, getString(R.string.data_recording_start), null, null, Snackbar.LENGTH_SHORT); - final Handler handler = new Handler(); - block = System.currentTimeMillis(); - recordTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - recordData(); - } - }); - } - }, 0, recordPeriod); - } else { - item.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_record_white, null)); - recordTimer.cancel(); - recordTimer = null; - isRecording = false; - writeHeaderToFile = true; - CustomSnackBar.showSnackBar(coordinatorLayout, - getString(R.string.csv_store_text) + " " + powerSourceLogger.getCurrentFilePath() - , getString(R.string.open), new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(PowerSourceActivity.this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getResources().getString(R.string.power_source)); - startActivity(intent); - } - }, Snackbar.LENGTH_LONG); - - } - break; - case R.id.play_data: - if (!playClicked) { - playClicked = true; - stopMenu.setVisible(true); - item.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_pause_white_24dp, null)); - if (playbackTimer == null) { - playbackTimer = new Timer(); - } else { - playbackTimer.cancel(); - playbackTimer = new Timer(); - } - final Handler handler = new Handler(); - playbackTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - if (recordedPowerData != null && currentPosition < recordedPowerData.size()) { - final PowerSourceData data = recordedPowerData.get(currentPosition); - if (data != null) { - setSavedValue(data); - } - } else { - playbackTimer.cancel(); - currentPosition = 0; - playClicked = false; - stopMenu.setVisible(false); - item.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_play_arrow_white_24dp, null)); - } - } - }); - } - }, 0, recordPeriod); - - } else { - playClicked = false; - stopMenu.setVisible(false); - item.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_play_arrow_white_24dp, null)); - if (playbackTimer != null) { - playbackTimer.cancel(); - playbackTimer = null; - } - } - break; - case R.id.stop_data: - if (playbackTimer != null) { - playbackTimer.cancel(); - currentPosition = 0; - playClicked = false; - playMenu.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_play_arrow_white_24dp, null)); - stopMenu.setVisible(false); - } - break; - case android.R.id.home: - this.finish(); - break; - default: - break; - } - - return true; - } - - @Override - protected void onSaveInstanceState(@NonNull Bundle outState) { - outState.putString("displayPV1", displayPV1.getText().toString()); - outState.putString("displayPV2", displayPV2.getText().toString()); - outState.putString("displayPV3", displayPV3.getText().toString()); - outState.putString("displayPCS", displayPCS.getText().toString()); - super.onSaveInstanceState(outState); - } - - /** - * Initiates and sets up power knob controller - * - * @param controller assigned knob - * @param pin assigned power pin - * @param controllerLimit maximum value the knob can handle - */ - private void monitorControllers(Croller controller, final Pin pin, int controllerLimit) { - controller.setMax(controllerLimit); - controller.setProgress(retrievePowerValues(pin)); - controller.setOnCrollerChangeListener(new OnCrollerChangeListener() { - private int progress; - - @Override - public void onProgressChanged(Croller croller, int progress) { - setMappedPower(pin, progress); - this.progress = progress; - removeCursor(); - } - - @Override - public void onStartTrackingTouch(Croller croller) { /**/ } - - @Override - public void onStopTrackingTouch(Croller croller) { - setPower(pin); - /* - V6 hardware has two pairs of paired channels: - 0: PCS & PVS2 - 1: PVS1 & PVS3 - Paired channels share relative output levels, i.e. if PV1 outputs 5 V - then PV3 outputs 3.3 V. - */ - switch (pin) { - case PV1: - if ((int) (progress * 3.3 / 10) > PV3_CONTROLLER_MAX) { - controllerPV3.setProgress(PV3_CONTROLLER_MAX); - } else if ((int) (progress * 3.3 / 10) < CONTROLLER_MIN) { - controllerPV3.setProgress(CONTROLLER_MIN); - } else { - controllerPV3.setProgress((int) (progress * 3.3 / 10)); - } - break; - case PV2: - if (PCS_CONTROLLER_MAX - (progress / 2) > PCS_CONTROLLER_MAX) { - controllerPCS.setProgress(PCS_CONTROLLER_MAX); - } else if (PCS_CONTROLLER_MAX - (progress / 2) < CONTROLLER_MIN) { - controllerPCS.setProgress(CONTROLLER_MIN); - } else { - controllerPCS.setProgress(PCS_CONTROLLER_MAX - (progress / 2)); - } - break; - case PV3: - if ((int) (progress * 10 / 3.3) > PV1_CONTROLLER_MAX) { - controllerPV1.setProgress(PV1_CONTROLLER_MAX); - } else if ((int) (progress * 10 / 3.3) < CONTROLLER_MIN) { - controllerPV1.setProgress(CONTROLLER_MIN); - } else { - controllerPV1.setProgress((int) (progress * 10 / 3.3)); - } - break; - case PCS: - if (PV2_CONTROLLER_MAX - (progress * 2) > PV2_CONTROLLER_MAX) { - controllerPV2.setProgress(PV2_CONTROLLER_MAX); - } else if (PV2_CONTROLLER_MAX - (progress * 2) < CONTROLLER_MIN) { - controllerPV2.setProgress(CONTROLLER_MIN); - } else { - controllerPV2.setProgress(PV2_CONTROLLER_MAX - (progress * 2)); - } - break; - default: - break; - } - } - }); - } - - private void removeCursor() { - displayPV1.setCursorVisible(false); - displayPV2.setCursorVisible(false); - displayPV3.setCursorVisible(false); - displayPCS.setCursorVisible(false); - } - - /** - * Click listeners to increment and decrement buttons - * - * @param up increment button - * @param down decrement button - * @param pin assigned power pin - */ - private void monitorVariations(SquareImageButton up, SquareImageButton down, final Pin pin) { - up.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - incrementValue(pin); - } - }); - up.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(final View view) { - if (!isRunning) { - isRunning = true; - incrementPower = true; - fastCounter(pin); - } - return true; - } - }); - down.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - decrementValue(pin); - } - }); - down.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(final View view) { - if (!isRunning) { - isRunning = true; - decrementPower = true; - fastCounter(pin); - } - return true; - } - }); - } - - /** - * Handles action when user releases long click on an increment or a decrement button - * - * @param up increment button - * @param down decrement button - */ - private void monitorLongClicks(SquareImageButton up, SquareImageButton down) { - up.setOnTouchListener(new View.OnTouchListener() { - @SuppressLint("ClickableViewAccessibility") - @Override - public boolean onTouch(View view, MotionEvent motionEvent) { - view.onTouchEvent(motionEvent); - if (motionEvent.getAction() == MotionEvent.ACTION_UP && incrementPower) { - if (isRunning) { - isRunning = false; - stopCounter(); - incrementPower = false; - } - } - return true; - } - }); - down.setOnTouchListener(new View.OnTouchListener() { - @SuppressLint("ClickableViewAccessibility") - @Override - public boolean onTouch(View view, MotionEvent motionEvent) { - view.onTouchEvent(motionEvent); - if (motionEvent.getAction() == MotionEvent.ACTION_UP && decrementPower) { - if (isRunning) { - isRunning = false; - stopCounter(); - decrementPower = false; - } - } - return true; - } - }); - } - - /** - * Increase power value by a fraction of hundreds - * - * @param pin assigned power pin - */ - private void incrementValue(Pin pin) { - switch (pin) { - case PV1: - if (voltagePV1 < PV1_VOLTAGE_RANGE.getUpper()) { - voltagePV1 += STEP; - updateDisplay(displayPV1, voltagePV1, Pin.PV1); - updateController(controllerPV1, Pin.PV1); - } - break; - case PV2: - if (voltagePV2 < PV2_VOLTAGE_RANGE.getUpper()) { - voltagePV2 += STEP; - updateDisplay(displayPV2, voltagePV2, Pin.PV2); - updateController(controllerPV2, Pin.PV2); - } - break; - case PV3: - if (voltagePV3 < PV3_VOLTAGE_RANGE.getUpper()) { - voltagePV3 += STEP; - updateDisplay(displayPV3, voltagePV3, Pin.PV3); - updateController(controllerPV3, Pin.PV3); - } - break; - case PCS: - if (currentPCS < PCS_CURRENT_RANGE.getUpper()) { - currentPCS += STEP; - updateDisplay(displayPCS, currentPCS, Pin.PCS); - updateController(controllerPCS, Pin.PCS); - } - break; - default: - break; - } - } - - /** - * Decrease power value by a fraction of hundreds - * - * @param pin assigned power pin - */ - private void decrementValue(Pin pin) { - switch (pin) { - case PV1: - if (voltagePV1 > PV1_VOLTAGE_RANGE.getLower()) { - voltagePV1 -= STEP; - updateDisplay(displayPV1, voltagePV1, Pin.PV1); - updateController(controllerPV1, Pin.PV1); - } - break; - case PV2: - if (voltagePV2 > PV2_VOLTAGE_RANGE.getLower()) { - voltagePV2 -= STEP; - updateDisplay(displayPV2, voltagePV2, Pin.PV2); - updateController(controllerPV2, Pin.PV2); - } - break; - case PV3: - if (voltagePV3 > PV3_VOLTAGE_RANGE.getLower()) { - voltagePV3 -= STEP; - updateDisplay(displayPV3, voltagePV3, Pin.PV3); - updateController(controllerPV3, Pin.PV3); - } - break; - case PCS: - if (currentPCS > PCS_CURRENT_RANGE.getLower()) { - currentPCS -= STEP; - updateDisplay(displayPCS, currentPCS, Pin.PCS); - updateController(controllerPCS, Pin.PCS); - } - break; - default: - break; - } - } - - /** - * Rotate power knob to the correct position determined by the numerical power value - * - * @param controller assigned knob - * @param pin assigned power pin - */ - private void updateController(Croller controller, Pin pin) { - switch (pin) { - case PV1: - controller.setProgress(mapPowerToProgress(voltagePV1, PV1_CONTROLLER_MAX, - PV1_VOLTAGE_RANGE.getUpper(), PV1_VOLTAGE_RANGE.getLower())); - break; - case PV2: - controller.setProgress(mapPowerToProgress(voltagePV2, PV2_CONTROLLER_MAX, - PV2_VOLTAGE_RANGE.getUpper(), PV2_VOLTAGE_RANGE.getLower())); - break; - case PV3: - controller.setProgress(mapPowerToProgress(voltagePV3, PV3_CONTROLLER_MAX, - PV3_VOLTAGE_RANGE.getUpper(), PV3_VOLTAGE_RANGE.getLower())); - break; - case PCS: - controller.setProgress(mapPowerToProgress(currentPCS, PCS_CONTROLLER_MAX, - PCS_CURRENT_RANGE.getUpper(), PCS_CURRENT_RANGE.getLower())); - break; - default: - break; - } - - } - - /** - * Updates display with user set values and issue commands to PSLab device to output power - * - * @param display text view corresponding to power values - * @param value signed power value - * @param pin assigned power pin - */ - private void updateDisplay(TextView display, float value, Pin pin) { - String displayText = (value >= 0 ? "+" : "-").concat(String.format(Locale.getDefault(), - "%.2f", Math.abs(value))).concat(pin.equals(Pin.PCS) ? " mA" : " V"); - display.setText(displayText); - setPower(pin); - } - - /** - * Updates display and calculate power value determined by knob position - * - * @param pin assigned power pin - * @param progress corresponding progress value - */ - private void setMappedPower(Pin pin, int progress) { - savePowerValues(pin, progress); - switch (pin) { - case PV1: - voltagePV1 = limitDigits(mapProgressToPower(progress, PV1_CONTROLLER_MAX, - PV1_VOLTAGE_RANGE.getUpper(), PV1_VOLTAGE_RANGE.getLower())); - updateDisplay(displayPV1, voltagePV1, pin); - break; - case PV2: - voltagePV2 = limitDigits(mapProgressToPower(progress, PV2_CONTROLLER_MAX, - PV2_VOLTAGE_RANGE.getUpper(), PV2_VOLTAGE_RANGE.getLower())); - updateDisplay(displayPV2, voltagePV2, pin); - break; - case PV3: - voltagePV3 = limitDigits(mapProgressToPower(progress, PV3_CONTROLLER_MAX, - PV3_VOLTAGE_RANGE.getUpper(), PV3_VOLTAGE_RANGE.getLower())); - updateDisplay(displayPV3, voltagePV3, pin); - break; - case PCS: - currentPCS = limitDigits(mapProgressToPower(progress, PCS_CONTROLLER_MAX, - PCS_CURRENT_RANGE.getUpper(), PCS_CURRENT_RANGE.getLower())); - updateDisplay(displayPCS, currentPCS, pin); - break; - default: - break; - } - } - - /** - * Output the power values set by user when the PSLab device is connected - * - * @param pin assigned power pin - */ - private void setPower(Pin pin) { - if (scienceLab.isConnected()) { - switch (pin) { - case PV1: - scienceLab.setPV1(voltagePV1); - break; - case PV2: - scienceLab.setPV2(voltagePV2); - break; - case PV3: - scienceLab.setPV3(voltagePV3); - break; - case PCS: - scienceLab.setPCS(currentPCS); - break; - default: - break; - } - } - } - - /** - * Saves power values set by user if the PSLab device is plugged in - * - * @param pin assigned power pin - * @param power corresponding progress value - */ - private void savePowerValues(Pin pin, int power) { - if (scienceLab.isConnected()) { - SharedPreferences.Editor modifier = powerPreferences.edit(); - modifier.putInt(String.valueOf(pin), power); - modifier.apply(); - } - } - - /** - * Retrieves saved power values corresponding to power pin. If user has already unplugged the - * PSLab device, this method will clean up records as the device has reset already - * - * @param pin assigned power pin - * @return corresponding progress value - */ - private int retrievePowerValues(Pin pin) { - if (scienceLab.isConnected()) { - return powerPreferences.getInt(String.valueOf(pin), 1); - } else { - boolean guideState = powerPreferences.getBoolean("PowerSourceFirstTime", true); - powerPreferences.edit().clear().apply(); - SharedPreferences.Editor editor = powerPreferences.edit(); - editor.putBoolean("PowerSourceFirstTime", guideState); - editor.apply(); - return 1; - } - } - - /** - * Maps progress value to power values in between the range supported by power pin - * - * @param progress value captured from knob position - * @param CONTROLLER_MAX maximum value supported by knob - * @param max maximum power output - * @param min minimum power output - * @return float value corresponding to the progress value in between min and max - */ - private float mapProgressToPower(int progress, int CONTROLLER_MAX, float max, float min) { - return (progress - CONTROLLER_MIN) * (max - min) / - (CONTROLLER_MAX - CONTROLLER_MIN) + min; - } - - /** - * Maps power value to progress values in between the range supported by knob - * - * @param power signed voltage or current value - * @param CONTROLLER_MAX maximum value supported by knob - * @param max maximum power output - * @param min minimum power output - * @return integer value representing progress level at the respective power level in between - * CONTROLLER_MIN and CONTROLLER_MAX - */ - private int mapPowerToProgress(float power, int CONTROLLER_MAX, float max, float min) { - return (int) (limitDigits((power - min) * (CONTROLLER_MAX - CONTROLLER_MIN) / - (max - min)) + CONTROLLER_MIN); - } - - /** - * Chops off excess and rounds off a float number to two decimal places - * - * @param number float value with inconsistent decimal places - * @return truncated float value - */ - private float limitDigits(float number) { - try { - return Float.parseFloat(String.format(Locale.ROOT, "%.2f", number)); - } catch (NumberFormatException e) { - return 0.00f; - } - } - - /** - * Stops the Timer that is changing power pin values - */ - private void stopCounter() { - if (powerCounter != null) { - powerCounter.cancel(); - powerCounter.purge(); - } - } - - /** - * TimerTask implementation to increment or decrement assigned power pin values at a constant - * rate provided by LONG_CLICK_DELAY - * - * @param pin assigned power pin - */ - private void fastCounter(final Pin pin) { - powerCounter = new Timer(); - TimerTask task = new TimerTask() { - public void run() { - powerHandler.post(new Runnable() { - public void run() { - if (incrementPower) { - incrementValue(pin); - } else if (decrementPower) { - decrementValue(pin); - } - } - }); - } - }; - powerCounter.schedule(task, 1, LONG_CLICK_DELAY); - } - - private void recordData() { - long timestamp; - double lat; - double lon; - if (writeHeaderToFile) { - powerSourceLogger = new CSVLogger(getString(R.string.power_source)); - powerSourceLogger.prepareLogFile(); - powerSourceLogger.writeMetaData(getString(R.string.power_source)); - powerSourceLogger.writeCSVFile(CSV_HEADER); - writeHeaderToFile = !writeHeaderToFile; - recordSensorDataBlockID(new SensorDataBlock(block, getResources().getString(R.string.power_source))); - } - if (gpsLogger.isGPSEnabled()) { - Location location = gpsLogger.getDeviceLocation(); - if (location != null) { - lat = location.getLatitude(); - lon = location.getLongitude(); - } else { - lat = 0.0; - lon = 0.0; - } - } else { - lat = 0.0; - lon = 0.0; - } - timestamp = System.currentTimeMillis(); - powerSourceLogger.writeCSVFile( - new CSVDataLine() - .add(System.currentTimeMillis()) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(System.currentTimeMillis()))) - .add(voltagePV1) - .add(voltagePV2) - .add(voltagePV3) - .add(currentPCS) - .add(lat) - .add(lon) - ); - recordSensorData(new PowerSourceData(timestamp, block, voltagePV1, voltagePV2, voltagePV3, currentPCS, lat, lon)); - } - - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((PowerSourceData) sensorData); - realm.commitTransaction(); - } - - private void setSavedValue(PowerSourceData data) { - voltagePV1 = data.getPv1(); - voltagePV2 = data.getPv2(); - voltagePV3 = data.getPv3(); - currentPCS = data.getPcs(); - controllerPV1.setProgress(mapPowerToProgress(voltagePV1, PV1_CONTROLLER_MAX, - PV1_VOLTAGE_RANGE.getUpper(), PV1_VOLTAGE_RANGE.getLower())); - setMappedPower(Pin.PV1, mapPowerToProgress(voltagePV1, PV1_CONTROLLER_MAX, - PV1_VOLTAGE_RANGE.getUpper(), PV1_VOLTAGE_RANGE.getLower())); - controllerPV2.setProgress(mapPowerToProgress(voltagePV2, PV2_CONTROLLER_MAX, - PV2_VOLTAGE_RANGE.getUpper(), PV2_VOLTAGE_RANGE.getLower())); - setMappedPower(Pin.PV2, mapPowerToProgress(voltagePV2, PV2_CONTROLLER_MAX, - PV2_VOLTAGE_RANGE.getUpper(), PV2_VOLTAGE_RANGE.getLower())); - controllerPV3.setProgress(mapPowerToProgress(voltagePV3, PV3_CONTROLLER_MAX, - PV3_VOLTAGE_RANGE.getUpper(), PV3_VOLTAGE_RANGE.getLower())); - setMappedPower(Pin.PV3, mapPowerToProgress(voltagePV3, PV3_CONTROLLER_MAX, - PV3_VOLTAGE_RANGE.getUpper(), PV3_VOLTAGE_RANGE.getLower())); - controllerPCS.setProgress(mapPowerToProgress(currentPCS, PCS_CONTROLLER_MAX, - PCS_CURRENT_RANGE.getUpper(), PCS_CURRENT_RANGE.getLower())); - setMappedPower(Pin.PCS, mapPowerToProgress(currentPCS, PCS_CONTROLLER_MAX, - PCS_CURRENT_RANGE.getUpper(), PCS_CURRENT_RANGE.getLower())); - currentPosition++; - } - - @Override - protected void onDestroy() { - super.onDestroy(); - if (recordTimer != null) { - recordTimer.cancel(); - recordTimer = null; - } - } - - private void disableButtons() { - upPV1.setEnabled(false); - upPV2.setEnabled(false); - upPV3.setEnabled(false); - upPCS.setEnabled(false); - downPV1.setEnabled(false); - downPV2.setEnabled(false); - downPV3.setEnabled(false); - downPCS.setEnabled(false); - } - - private enum Pin { - PV1, PV2, PV3, PCS - } -} diff --git a/app/src/main/java/io/pslab/activity/RoboticArmActivity.java b/app/src/main/java/io/pslab/activity/RoboticArmActivity.java deleted file mode 100644 index 4a6b8a5de..000000000 --- a/app/src/main/java/io/pslab/activity/RoboticArmActivity.java +++ /dev/null @@ -1,712 +0,0 @@ -package io.pslab.activity; - -import android.content.Context; -import android.content.Intent; -import android.graphics.Point; -import android.location.Location; -import android.location.LocationManager; -import android.os.Build; -import android.os.Bundle; -import android.os.CountDownTimer; -import android.text.InputFilter; -import android.util.TypedValue; -import android.view.Display; -import android.view.DragEvent; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.WindowManager; -import android.view.inputmethod.EditorInfo; -import android.widget.EditText; -import android.widget.HorizontalScrollView; -import android.widget.LinearLayout; -import android.widget.RelativeLayout; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.widget.Toolbar; -import androidx.core.content.res.ResourcesCompat; - -import com.google.android.material.snackbar.Snackbar; -import com.triggertrap.seekarc.SeekArc; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import butterknife.ButterKnife; -import io.pslab.InputMinMaxFilter; -import io.pslab.R; -import io.pslab.activity.guide.GuideActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.models.SensorDataBlock; -import io.pslab.models.ServoData; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.GPSLogger; -import io.pslab.others.LocalDataLog; -import io.pslab.others.ScienceLabCommon; -import io.realm.Realm; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class RoboticArmActivity extends GuideActivity { - - private static final CSVDataLine CSV_HEADER = new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("Servo1") - .add("Servo2") - .add("Servo3") - .add("Servo4") - .add("Latitude") - .add("Longitude"); - private EditText degreeText1, degreeText2, degreeText3, degreeText4; - private SeekArc seekArc1, seekArc2, seekArc3, seekArc4; - private LinearLayout servo1TimeLine, servo2TimeLine, servo3TimeLine, servo4TimeLine; - private int degree; - private boolean editEnter = false; - private HorizontalScrollView scrollView; - private CountDownTimer timeLine; - private boolean isPlaying = false; - private CSVLogger servoCSVLogger; - private Realm realm; - private GPSLogger gpsLogger; - private RealmResults recordedServoData; - private final String KEY_LOG = "has_log"; - private final String DATA_BLOCK = "data_block"; - private int timelinePosition = 0; - private ScienceLab scienceLab; - private LinearLayout timeIndicatorLayout; - private LinearLayout.LayoutParams timeIndicatorParams; - private MenuItem playMenu; - - public RoboticArmActivity() { - super(R.layout.activity_robotic_arm); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ButterKnife.bind(this); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.robotic_arm); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - scienceLab = ScienceLabCommon.scienceLab; - if (!scienceLab.isConnected()) { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.device_not_connected), null, null, Snackbar.LENGTH_SHORT); - } - Display display = getWindowManager().getDefaultDisplay(); - Point size = new Point(); - display.getSize(size); - TypedValue tv = new TypedValue(); - int actionBarHeight = 0; - if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { - actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics()); - } - int screen_width = size.x; - int screen_height = size.y - actionBarHeight; - realm = LocalDataLog.with().getRealm(); - gpsLogger = new GPSLogger(this, - (LocationManager) getSystemService(Context.LOCATION_SERVICE)); - - View servo1Layout = findViewById(R.id.servo_1); - View servo2Layout = findViewById(R.id.servo_2); - View servo3Layout = findViewById(R.id.servo_3); - View servo4Layout = findViewById(R.id.servo_4); - degreeText1 = servo1Layout.findViewById(R.id.degreeText); - degreeText2 = servo2Layout.findViewById(R.id.degreeText); - degreeText3 = servo3Layout.findViewById(R.id.degreeText); - degreeText4 = servo4Layout.findViewById(R.id.degreeText); - seekArc1 = servo1Layout.findViewById(R.id.seek_arc); - seekArc2 = servo2Layout.findViewById(R.id.seek_arc); - seekArc3 = servo3Layout.findViewById(R.id.seek_arc); - seekArc4 = servo4Layout.findViewById(R.id.seek_arc); - servo1TimeLine = findViewById(R.id.servo1_timeline); - servo2TimeLine = findViewById(R.id.servo2_timeline); - servo3TimeLine = findViewById(R.id.servo3_timeline); - servo4TimeLine = findViewById(R.id.servo4_timeline); - scrollView = findViewById(R.id.horizontal_scroll_view); - servoCSVLogger = new CSVLogger(getResources().getString(R.string.robotic_arm)); - - degreeText1.setText(getResources().getString(R.string.zero)); - degreeText2.setText(getResources().getString(R.string.zero)); - degreeText3.setText(getResources().getString(R.string.zero)); - degreeText4.setText(getResources().getString(R.string.zero)); - - degreeText1.setFilters(new InputFilter[]{new InputMinMaxFilter(0, 360)}); - degreeText2.setFilters(new InputFilter[]{new InputMinMaxFilter(0, 360)}); - degreeText3.setFilters(new InputFilter[]{new InputMinMaxFilter(0, 360)}); - degreeText4.setFilters(new InputFilter[]{new InputMinMaxFilter(0, 360)}); - - LinearLayout.LayoutParams servoControllerParams = new LinearLayout.LayoutParams(screen_width / 4 - 4, screen_height / 2 - 4); - servoControllerParams.setMargins(2, 5, 2, 0); - servo1Layout.setLayoutParams(servoControllerParams); - servo2Layout.setLayoutParams(servoControllerParams); - servo3Layout.setLayoutParams(servoControllerParams); - servo4Layout.setLayoutParams(servoControllerParams); - - LinearLayout.LayoutParams servoTimeLineParams = new LinearLayout.LayoutParams(screen_width * 10, screen_height / 8 - 3); - servoTimeLineParams.setMargins(2, 0, 2, 4); - - servo1TimeLine.setLayoutParams(servoTimeLineParams); - servo2TimeLine.setLayoutParams(servoTimeLineParams); - servo3TimeLine.setLayoutParams(servoTimeLineParams); - servo4TimeLine.setLayoutParams(servoTimeLineParams); - - LinearLayout.LayoutParams servoTimeLineBoxParams = new LinearLayout.LayoutParams(screen_width / 6 - 2, screen_height / 8 - 2); - servoTimeLineBoxParams.setMargins(2, 0, 0, 0); - - for (int i = 0; i < 60; i++) { - RelativeLayout timeLineBox = (RelativeLayout) LayoutInflater.from(RoboticArmActivity.this).inflate(R.layout.robotic_arm_timeline_textview, null); - timeLineBox.setLayoutParams(servoTimeLineBoxParams); - timeLineBox.setPadding(5, 5, 5, 5); - TextView timeText = timeLineBox.findViewById(R.id.timeline_box_time_text); - timeText.setText((i + 1) + getResources().getString(R.string.robotic_arm_second_unit)); - timeLineBox.setOnDragListener(servo1DragListener); - servo1TimeLine.addView(timeLineBox, i); - } - - for (int i = 0; i < 60; i++) { - RelativeLayout timeLineBox = (RelativeLayout) LayoutInflater.from(RoboticArmActivity.this).inflate(R.layout.robotic_arm_timeline_textview, null); - timeLineBox.setLayoutParams(servoTimeLineBoxParams); - timeLineBox.setPadding(5, 5, 5, 5); - TextView timeText = timeLineBox.findViewById(R.id.timeline_box_time_text); - timeText.setText((i + 1) + getResources().getString(R.string.robotic_arm_second_unit)); - timeLineBox.setOnDragListener(servo2DragListener); - servo2TimeLine.addView(timeLineBox, i); - } - - for (int i = 0; i < 60; i++) { - RelativeLayout timeLineBox = (RelativeLayout) LayoutInflater.from(RoboticArmActivity.this).inflate(R.layout.robotic_arm_timeline_textview, null); - timeLineBox.setLayoutParams(servoTimeLineBoxParams); - timeLineBox.setPadding(5, 5, 5, 5); - TextView timeText = timeLineBox.findViewById(R.id.timeline_box_time_text); - timeText.setText((i + 1) + getResources().getString(R.string.robotic_arm_second_unit)); - timeLineBox.setOnDragListener(servo3DragListener); - servo3TimeLine.addView(timeLineBox, i); - } - - for (int i = 0; i < 60; i++) { - RelativeLayout timeLineBox = (RelativeLayout) LayoutInflater.from(RoboticArmActivity.this).inflate(R.layout.robotic_arm_timeline_textview, null); - timeLineBox.setLayoutParams(servoTimeLineBoxParams); - timeLineBox.setPadding(5, 5, 5, 5); - TextView timeText = timeLineBox.findViewById(R.id.timeline_box_time_text); - timeText.setText((i + 1) + getResources().getString(R.string.robotic_arm_second_unit)); - timeLineBox.setOnDragListener(servo4DragListener); - servo4TimeLine.addView(timeLineBox, i); - } - - TextView servo1Title = servo1Layout.findViewById(R.id.servo_title); - servo1Title.setText(getResources().getString(R.string.servo1_title)); - - TextView servo2Title = servo2Layout.findViewById(R.id.servo_title); - servo2Title.setText(getResources().getString(R.string.servo2_title)); - - TextView servo3Title = servo3Layout.findViewById(R.id.servo_title); - servo3Title.setText(getResources().getString(R.string.servo3_title)); - - TextView servo4Title = servo4Layout.findViewById(R.id.servo_title); - servo4Title.setText(getResources().getString(R.string.servo4_title)); - - removeStatusBar(); - - seekArc1.setOnSeekArcChangeListener(new SeekArc.OnSeekArcChangeListener() { - @Override - public void onProgressChanged(SeekArc seekArc, int i, boolean b) { - if (editEnter) { - degreeText1.setText(String.valueOf(degree)); - editEnter = false; - } else { - degreeText1.setText(String.valueOf((int) (i * 3.6))); - } - degreeText1.setCursorVisible(false); - } - - @Override - public void onStartTrackingTouch(SeekArc seekArc) { - - } - - @Override - public void onStopTrackingTouch(SeekArc seekArc) { - - } - }); - - seekArc2.setOnSeekArcChangeListener(new SeekArc.OnSeekArcChangeListener() { - @Override - public void onProgressChanged(SeekArc seekArc, int i, boolean b) { - if (editEnter) { - degreeText2.setText(String.valueOf(degree)); - editEnter = false; - } else { - degreeText2.setText(String.valueOf((int) (i * 3.6))); - } - degreeText2.setCursorVisible(false); - } - - @Override - public void onStartTrackingTouch(SeekArc seekArc) { - - } - - @Override - public void onStopTrackingTouch(SeekArc seekArc) { - - } - }); - - seekArc3.setOnSeekArcChangeListener(new SeekArc.OnSeekArcChangeListener() { - @Override - public void onProgressChanged(SeekArc seekArc, int i, boolean b) { - if (editEnter) { - degreeText3.setText(String.valueOf(degree)); - editEnter = false; - } else { - degreeText3.setText(String.valueOf((int) (i * 3.6))); - } - degreeText3.setCursorVisible(false); - } - - @Override - public void onStartTrackingTouch(SeekArc seekArc) { - - } - - @Override - public void onStopTrackingTouch(SeekArc seekArc) { - - } - }); - - seekArc4.setOnSeekArcChangeListener(new SeekArc.OnSeekArcChangeListener() { - @Override - public void onProgressChanged(SeekArc seekArc, int i, boolean b) { - if (editEnter) { - degreeText4.setText(String.valueOf(degree)); - editEnter = false; - } else { - degreeText4.setText(String.valueOf((int) (i * 3.6))); - } - degreeText4.setCursorVisible(false); - } - - @Override - public void onStartTrackingTouch(SeekArc seekArc) { - - } - - @Override - public void onStopTrackingTouch(SeekArc seekArc) { - - } - }); - - servo1Layout.findViewById(R.id.drag_handle).setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - View.DragShadowBuilder myShadow = new View.DragShadowBuilder(servo1Layout); - v.startDrag(null, myShadow, servo1Layout, 0); - return true; - } - }); - - servo2Layout.findViewById(R.id.drag_handle).setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - View.DragShadowBuilder myShadow = new View.DragShadowBuilder(servo2Layout); - v.startDrag(null, myShadow, servo2Layout, 0); - return true; - } - }); - - servo3Layout.findViewById(R.id.drag_handle).setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - View.DragShadowBuilder myShadow = new View.DragShadowBuilder(servo3Layout); - v.startDrag(null, myShadow, servo3Layout, 0); - return true; - } - }); - - servo4Layout.findViewById(R.id.drag_handle).setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - View.DragShadowBuilder myShadow = new View.DragShadowBuilder(servo4Layout); - v.startDrag(null, myShadow, servo4Layout, 0); - return true; - } - }); - - degreeText1.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - removeStatusBar(); - if (actionId == EditorInfo.IME_ACTION_DONE) { - degree = Integer.valueOf(degreeText1.getText().toString()); - if (degree > 360 || degree < 0) { - degreeText1.setText(getResources().getString(R.string.zero)); - seekArc1.setProgress(0); - toastInvalidValueMessage(); - } else { - seekArc1.setProgress((int) (degree / 3.6)); - editEnter = true; - } - } - return false; - } - }); - - degreeText1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - degreeText1.setCursorVisible(true); - } - }); - - degreeText2.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - removeStatusBar(); - if (actionId == EditorInfo.IME_ACTION_DONE) { - degree = Integer.valueOf(degreeText2.getText().toString()); - if (degree > 360 || degree < 0) { - degreeText2.setText(getResources().getString(R.string.zero)); - seekArc2.setProgress(0); - toastInvalidValueMessage(); - } else { - seekArc2.setProgress((int) (degree / 3.6)); - editEnter = true; - } - } - return false; - } - }); - - degreeText2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - degreeText2.setCursorVisible(true); - } - }); - - degreeText3.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - removeStatusBar(); - if (actionId == EditorInfo.IME_ACTION_DONE) { - degree = Integer.parseInt(degreeText3.getText().toString()); - if (degree > 360 || degree < 0) { - degreeText3.setText(getResources().getString(R.string.zero)); - seekArc3.setProgress(0); - toastInvalidValueMessage(); - } else { - seekArc3.setProgress((int) (degree / 3.6)); - editEnter = true; - } - } - return false; - } - }); - - degreeText3.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - degreeText3.setCursorVisible(true); - } - }); - - degreeText4.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - removeStatusBar(); - if (actionId == EditorInfo.IME_ACTION_DONE) { - degree = Integer.valueOf(degreeText4.getText().toString()); - if (degree > 360 || degree < 0) { - degreeText4.setText(getResources().getString(R.string.zero)); - seekArc4.setProgress(0); - toastInvalidValueMessage(); - } else { - seekArc4.setProgress((int) (degree / 3.6)); - editEnter = true; - } - } - return false; - } - }); - - degreeText4.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - degreeText4.setCursorVisible(true); - } - }); - - timeIndicatorLayout = findViewById(R.id.time_indicator); - timeIndicatorParams = new LinearLayout.LayoutParams(screen_width / 6 - 2, 12); - timeIndicatorParams.setMarginStart(3); - timeIndicatorLayout.setLayoutParams(timeIndicatorParams); - - timeLine = new CountDownTimer(60000, 1000) { - @Override - public void onTick(long millisUntilFinished) { - timeIndicatorParams.setMarginStart(timeIndicatorParams - .getMarginStart() + screen_width / 6); - timeIndicatorLayout.setLayoutParams(timeIndicatorParams); - scrollView.smoothScrollBy(screen_width / 6, 0); - String deg1 = ((TextView) servo1TimeLine.getChildAt(timelinePosition).findViewById(R.id.timeline_box_degree_text)).getText().toString(); - deg1 = (deg1.length() > 0) ? deg1.substring(0, deg1.length() - 1) : getResources().getString(R.string.zero); - String deg2 = ((TextView) servo2TimeLine.getChildAt(timelinePosition).findViewById(R.id.timeline_box_degree_text)).getText().toString(); - deg2 = (deg2.length() > 0) ? deg2.substring(0, deg2.length() - 1) : getResources().getString(R.string.zero); - String deg3 = ((TextView) servo3TimeLine.getChildAt(timelinePosition).findViewById(R.id.timeline_box_degree_text)).getText().toString(); - deg3 = (deg3.length() > 0) ? deg3.substring(0, deg3.length() - 1) : getResources().getString(R.string.zero); - String deg4 = ((TextView) servo4TimeLine.getChildAt(timelinePosition).findViewById(R.id.timeline_box_degree_text)).getText().toString(); - deg4 = (deg4.length() > 0) ? deg4.substring(0, deg4.length() - 1) : getResources().getString(R.string.zero); - if (scienceLab.isConnected()) { - scienceLab.servo4(Double.valueOf(deg1), Double.valueOf(deg2), Double.valueOf(deg3), Double.valueOf(deg4)); - } - timelinePosition++; - } - - @Override - public void onFinish() { - timeIndicatorLayout.setLayoutParams(timeIndicatorParams); - cancel(); - } - }; - - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - recordedServoData = LocalDataLog.with() - .getBlockOfServoRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - setReceivedData(); - } - - } - - private void toastInvalidValueMessage() { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.invalid_servo_value), null, null, Snackbar.LENGTH_SHORT); - } - - private void setReceivedData() { - final List servoDataList = new ArrayList<>(recordedServoData); - for (int i = 0; i < servoDataList.size(); i++) { - ServoData servoData = servoDataList.get(i); - ((TextView) servo1TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).setText(servoData.getDegree1() + getResources().getString(R.string.robotic_arm_degree_symbol)); - ((TextView) servo2TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).setText(servoData.getDegree2() + getResources().getString(R.string.robotic_arm_degree_symbol)); - ((TextView) servo3TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).setText(servoData.getDegree3() + getResources().getString(R.string.robotic_arm_degree_symbol)); - ((TextView) servo4TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).setText(servoData.getDegree4() + getResources().getString(R.string.robotic_arm_degree_symbol)); - } - } - - private void saveTimeline() { - long block = System.currentTimeMillis(); - servoCSVLogger.prepareLogFile(); - servoCSVLogger.writeMetaData(getResources().getString(R.string.robotic_arm)); - long timestamp; - recordSensorDataBlockID(new SensorDataBlock(block, getString(R.string.robotic_arm))); - String degree1, degree2, degree3, degree4; - double lat, lon; - servoCSVLogger.writeCSVFile(CSV_HEADER); - for (int i = 0; i < 60; i++) { - timestamp = System.currentTimeMillis(); - degree1 = degree2 = degree3 = degree4 = getResources().getString(R.string.zero); - if (((TextView) servo1TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).getText().length() > 0) { - degree1 = ((TextView) servo1TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).getText().toString(); - degree1 = degree1.substring(0, degree1.length() - 1); - } - if (((TextView) servo2TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).getText().length() > 0) { - degree2 = ((TextView) servo2TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).getText().toString(); - degree2 = degree2.substring(0, degree2.length() - 1); - } - if (((TextView) servo3TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).getText().length() > 0) { - degree3 = ((TextView) servo3TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).getText().toString(); - degree3 = degree3.substring(0, degree3.length() - 1); - } - if (((TextView) servo4TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).getText().length() > 0) { - degree4 = ((TextView) servo4TimeLine.getChildAt(i).findViewById(R.id.timeline_box_degree_text)).getText().toString(); - degree4 = degree4.substring(0, degree4.length() - 1); - } - if (gpsLogger.isGPSEnabled()) { - Location location = gpsLogger.getDeviceLocation(); - if (location != null) { - lat = location.getLatitude(); - lon = location.getLongitude(); - } else { - lat = 0.0; - lon = 0.0; - } - } else { - lat = 0.0; - lon = 0.0; - } - recordSensorData(new ServoData(timestamp, block, degree1, degree2, degree3, degree4, lat, lon)); - servoCSVLogger.writeCSVFile(new CSVDataLine().add(timestamp).add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))).add(degree1).add(degree2).add(degree3).add(degree4).add(lat).add(lon)); - } - CustomSnackBar.showSnackBar(findViewById(R.id.robotic_arm_coordinator), - getString(R.string.csv_store_text) + " " + servoCSVLogger.getCurrentFilePath() - , getString(R.string.open), new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(RoboticArmActivity.this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getResources().getString(R.string.robotic_arm)); - startActivity(intent); - } - }, Snackbar.LENGTH_SHORT); - } - - private final View.OnDragListener servo1DragListener = new View.OnDragListener() { - @Override - public boolean onDrag(View v, DragEvent event) { - if (event.getAction() == DragEvent.ACTION_DRAG_ENTERED) { - View view = (View) event.getLocalState(); - TextView text = view.findViewById(R.id.degreeText); - if (view.getId() == R.id.servo_1) { - ((TextView) v.findViewById(R.id.timeline_box_degree_text)).setText(text.getText().toString()); - } - } - return true; - } - }; - private final View.OnDragListener servo2DragListener = new View.OnDragListener() { - @Override - public boolean onDrag(View v, DragEvent event) { - if (event.getAction() == DragEvent.ACTION_DRAG_ENTERED) { - View view = (View) event.getLocalState(); - TextView text = view.findViewById(R.id.degreeText); - if (view.getId() == R.id.servo_2) { - ((TextView) v.findViewById(R.id.timeline_box_degree_text)).setText(text.getText().toString()); - } - } - return true; - } - }; - private final View.OnDragListener servo3DragListener = new View.OnDragListener() { - @Override - public boolean onDrag(View v, DragEvent event) { - if (event.getAction() == DragEvent.ACTION_DRAG_ENTERED) { - View view = (View) event.getLocalState(); - TextView text = view.findViewById(R.id.degreeText); - if (view.getId() == R.id.servo_3) { - ((TextView) v.findViewById(R.id.timeline_box_degree_text)).setText(text.getText().toString()); - } - } - return true; - } - }; - private final View.OnDragListener servo4DragListener = new View.OnDragListener() { - @Override - public boolean onDrag(View v, DragEvent event) { - if (event.getAction() == DragEvent.ACTION_DRAG_ENTERED) { - View view = (View) event.getLocalState(); - TextView text = view.findViewById(R.id.degreeText); - if (view.getId() == R.id.servo_4) { - ((TextView) v.findViewById(R.id.timeline_box_degree_text)).setText(text.getText().toString()); - } - } - return true; - } - }; - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.robotic_arm_menu, menu); - return true; - } - - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - playMenu = menu.findItem(R.id.play_data); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - finish(); - break; - case R.id.play_data: - if (isPlaying) { - isPlaying = false; - item.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_play_arrow_white_24dp, null)); - timeLine.onFinish(); - } else { - isPlaying = true; - item.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_pause_white_24dp, null)); - timeLine.start(); - } - break; - case R.id.stop_data: - timeLine.cancel(); - timeIndicatorParams.setMarginStart(3); - timeIndicatorLayout.setLayoutParams(timeIndicatorParams); - scrollView.fullScroll(HorizontalScrollView.FOCUS_LEFT); - isPlaying = false; - playMenu.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_play_arrow_white_24dp, null)); - timelinePosition = 0; - break; - case R.id.show_guide: - toggleGuide(); - break; - case R.id.show_logged_data: - Intent intent = new Intent(RoboticArmActivity.this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getResources().getString(R.string.robotic_arm)); - startActivity(intent); - break; - case R.id.save_data: - saveTimeline(); - break; - default: - break; - } - return true; - } - - @Override - protected void onResume() { - super.onResume(); - removeStatusBar(); - } - - private void removeStatusBar() { - if (Build.VERSION.SDK_INT < 16) { - getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, - WindowManager.LayoutParams.FLAG_FULLSCREEN); - } else { - View decorView = getWindow().getDecorView(); - - decorView.setSystemUiVisibility((View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)); - } - } - - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((ServoData) sensorData); - realm.commitTransaction(); - } -} diff --git a/app/src/main/java/io/pslab/activity/SensorActivity.java b/app/src/main/java/io/pslab/activity/SensorActivity.java deleted file mode 100644 index 5e9021968..000000000 --- a/app/src/main/java/io/pslab/activity/SensorActivity.java +++ /dev/null @@ -1,229 +0,0 @@ -package io.pslab.activity; - -import android.content.Intent; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.Menu; -import android.view.MenuItem; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.ListView; -import android.widget.TextView; - -import androidx.annotation.Nullable; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.widget.Toolbar; - -import com.google.android.material.snackbar.Snackbar; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import io.pslab.R; -import io.pslab.activity.guide.GuideActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.ScienceLabCommon; -import io.pslab.sensors.SensorADS1115; -import io.pslab.sensors.SensorAPDS9960; -import io.pslab.sensors.SensorBMP180; -import io.pslab.sensors.SensorCCS811; -import io.pslab.sensors.SensorHMC5883L; -import io.pslab.sensors.SensorMLX90614; -import io.pslab.sensors.SensorMPU6050; -import io.pslab.sensors.SensorMPU925X; -import io.pslab.sensors.SensorSHT21; -import io.pslab.sensors.SensorTSL2561; -import io.pslab.sensors.SensorVL53L0X; - -/** - * Created by asitava on 18/6/17. - */ - -public class SensorActivity extends GuideActivity { - - private I2C i2c; - private ScienceLab scienceLab; - private final Map sensorAddr = new LinkedHashMap<>(); - private final List dataAddress = new ArrayList<>(); - private final List dataName = new ArrayList<>(); - private ArrayAdapter adapter; - private ListView lvSensor; - private TextView tvSensorScan; - private Button buttonSensorAutoScan; - - public SensorActivity() { - super(R.layout.sensor_main); - } - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - scienceLab = ScienceLabCommon.scienceLab; - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.sensors); - actionBar.setDisplayHomeAsUpEnabled(true); - } - - i2c = scienceLab.i2c; - sensorAddr.put(0x48, "ADS1115"); - sensorAddr.put(0x77, "BMP180"); - sensorAddr.put(0x5A, "MLX90614"); - sensorAddr.put(0x1E, "HMC5883L"); - sensorAddr.put(0x68, "MPU6050"); - sensorAddr.put(0x40, "SHT21"); - sensorAddr.put(0x39, "TSL2561"); - sensorAddr.put(0x69, "MPU925x"); - sensorAddr.put(0x29, "VL53L0X"); - sensorAddr.put(0x5A, "CCS811"); - sensorAddr.put(0x39, "APDS9960"); - - adapter = new ArrayAdapter<>(getApplication(), R.layout.sensor_list_item, R.id.tv_sensor_list_item, dataName); - - buttonSensorAutoScan = findViewById(R.id.button_sensor_autoscan); - tvSensorScan = findViewById(R.id.tv_sensor_scan); - tvSensorScan.setText(getResources().getString(R.string.use_autoscan)); - lvSensor = findViewById(R.id.lv_sensor); - lvSensor.setAdapter(adapter); - - buttonSensorAutoScan.setOnClickListener(v -> { - buttonSensorAutoScan.setClickable(false); - tvSensorScan.setText(getResources().getString(R.string.scanning)); - new PopulateSensors().execute(); - }); - lvSensor.setOnItemClickListener((parent, view, position, id) -> { - String itemValue = (String) lvSensor.getItemAtPosition(position); - Intent intent; - switch (itemValue) { - case "ADS1115": - intent = new Intent(getApplication(), SensorADS1115.class); - startActivity(intent); - break; - case "BMP180": - intent = new Intent(getApplication(), SensorBMP180.class); - startActivity(intent); - break; - case "MLX90614": - intent = new Intent(getApplication(), SensorMLX90614.class); - startActivity(intent); - break; - case "HMC5883L": - intent = new Intent(getApplication(), SensorHMC5883L.class); - startActivity(intent); - break; - case "MPU6050": - intent = new Intent(getApplication(), SensorMPU6050.class); - startActivity(intent); - break; - case "SHT21": - intent = new Intent(getApplication(), SensorSHT21.class); - startActivity(intent); - break; - case "TSL2561": - intent = new Intent(getApplication(), SensorTSL2561.class); - startActivity(intent); - break; - case "MPU925x": - intent = new Intent(getApplication(), SensorMPU925X.class); - startActivity(intent); - break; - case "VL53L0X": - intent = new Intent(getApplication(), SensorVL53L0X.class); - startActivity(intent); - break; - case "CCS811": - intent = new Intent(getApplication(), SensorCCS811.class); - startActivity(intent); - break; - case "APDS9960": - intent = new Intent(getApplication(), SensorAPDS9960.class); - startActivity(intent); - break; - default: - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - "Sensor Not Supported", null, null, Snackbar.LENGTH_SHORT); - } - }); - } - - private class PopulateSensors extends AsyncTask { - private List data; - - @Override - protected Void doInBackground(Void... voids) { - data = new ArrayList<>(); - dataName.clear(); - dataAddress.clear(); - if (scienceLab.isConnected()) { - try { - data = i2c.scan(null); - } catch (IOException | NullPointerException e) { - e.printStackTrace(); - } - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - - StringBuilder tvData = new StringBuilder(); - if (data != null) { - for (Integer myInt : data) { - if (myInt != null && sensorAddr.get(myInt) != null) { - dataAddress.add(String.valueOf(myInt)); - } - } - - for (final String s : dataAddress) { - tvData.append(s).append(":").append(sensorAddr.get(Integer.parseInt(s))).append("\n"); - } - - } else { - tvData.append(getResources().getString(R.string.sensor_not_connected)); - } - - for (int key : sensorAddr.keySet()) { - dataName.add(sensorAddr.get(key)); - } - - if (scienceLab.isConnected()) { - tvSensorScan.setText(tvData); - } else { - tvSensorScan.setText(getString(R.string.not_connected)); - } - adapter.notifyDataSetChanged(); - buttonSensorAutoScan.setClickable(true); - } - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.sensor_menu, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - finish(); - break; - case R.id.show_guide: - toggleGuide(); - break; - default: - break; - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/activity/SensorDataLoggerActivity.java b/app/src/main/java/io/pslab/activity/SensorDataLoggerActivity.java deleted file mode 100644 index d71c61681..000000000 --- a/app/src/main/java/io/pslab/activity/SensorDataLoggerActivity.java +++ /dev/null @@ -1,334 +0,0 @@ -package io.pslab.activity; - -import android.Manifest; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.util.Log; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.FrameLayout; -import android.widget.ListView; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; -import androidx.coordinatorlayout.widget.CoordinatorLayout; -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; - -import com.afollestad.materialdialogs.DialogAction; -import com.afollestad.materialdialogs.MaterialDialog; -import com.google.android.material.floatingactionbutton.FloatingActionButton; -import com.google.android.material.snackbar.Snackbar; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedHashMap; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.MPU6050; -import io.pslab.models.DataMPU6050; -import io.pslab.models.SensorLogged; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.ScienceLabCommon; -import io.realm.Realm; -import io.realm.RealmResults; - - -public class SensorDataLoggerActivity extends AppCompatActivity { - - private static final int WRITE_EXTERNAL_STORAGE_REQUEST = 1; - private static boolean hasPermission = false; - private static boolean isLogging = false; - private final LinkedHashMap sensorAddress = new LinkedHashMap<>(); - private final ScienceLab scienceLab = ScienceLabCommon.scienceLab; - private final I2C i2c = scienceLab.i2c; - private final ArrayList sensorList = new ArrayList<>(); - private final ArrayList mpu6050DataList = new ArrayList<>(); - private Context context; - private Thread loggingThread; - private volatile boolean loggingThreadRunning = false; - private final Object lock = new Object(); - private View customView; - private Realm realm; - @BindView(R.id.toolbar) - Toolbar toolbar; - @BindView(R.id.fab) - FloatingActionButton scanFab; - @BindView(R.id.coordinator_layout) - CoordinatorLayout coordinatorLayout; - @BindView(R.id.layout_container) - FrameLayout container; - - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_data_sensor_logger); - ButterKnife.bind(this); - if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_REQUEST); - } else { - hasPermission = true; - } - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle("Sensor Data Logger"); - } - context = this; - realm = Realm.getDefaultInstance(); - scanFab.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (scienceLab.isConnected()) { - Runnable detectSensors = new Runnable() { - @Override - public void run() { - try { - ArrayList scanResult = i2c.scan(null); - final ArrayList listData = new ArrayList(); - if (scanResult != null) { - for (Integer temp : scanResult) { - if (sensorAddress.get(temp) != null) { - listData.add(sensorAddress.get(temp) + " : " + temp); - sensorList.add(sensorAddress.get(temp)); - } - } - } - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - ListView sensorList = new ListView(context); - ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, listData); - sensorList.setAdapter(adapter); - container.addView(sensorList); - sensorList.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - handleClick(position); - } - }); - } - }); - } catch (IOException e) { - e.printStackTrace(); - } - } - }; - new Thread(detectSensors).start(); - } else { - Snackbar snackbar = Snackbar.make(coordinatorLayout, "Device not connected", Snackbar.LENGTH_SHORT); - View snackBarView = snackbar.getView(); - TextView snackBarTextView = snackBarView.findViewById(R.id.snackbar_text); - snackBarTextView.setTextColor(Color.YELLOW); - snackbar.show(); - } - } - }); - sensorAddress.put(0x60, "MCP4728"); - sensorAddress.put(0x48, "ADS1115"); - sensorAddress.put(0x23, "BH1750"); - sensorAddress.put(0x77, "BMP180"); - sensorAddress.put(0x5A, "MLX90614"); - sensorAddress.put(0x1E, "HMC5883L"); - sensorAddress.put(0x68, "MPU6050"); - sensorAddress.put(0x40, "SHT21"); - sensorAddress.put(0x39, "TSL2561"); - } - - private void handleClick(int position) { - String sensor = sensorList.get(position); - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - sensor, null, null, Snackbar.LENGTH_SHORT); - switch (sensor) { - case "MPU6050": - MaterialDialog dialog = new MaterialDialog.Builder(context) - .customView(R.layout.sensor_mpu6050_data_card, true) - .positiveText(getResources().getString(R.string.start_logging)) - .onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull final DialogAction which) { - if (!isLogging) { - isLogging = true; - loggingThreadRunning = true; - dialog.getActionButton(DialogAction.POSITIVE).setText(getResources().getString(R.string.stop_logging)); - Runnable loggingRunnable = new Runnable() { - @Override - public void run() { - try { - MPU6050 sensorMPU6050 = new MPU6050(i2c, scienceLab); - while (loggingThreadRunning) { - TaskMPU6050 taskMPU6050 = new TaskMPU6050(sensorMPU6050); - taskMPU6050.execute(); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - Thread.sleep(500); - } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - } - }; - loggingThread = new Thread(loggingRunnable); - loggingThread.start(); - } else { - isLogging = false; - dialog.getActionButton(DialogAction.POSITIVE).setText(getResources().getString(R.string.start_logging)); - loggingThreadRunning = false; - } - } - }) - .negativeText(getResources().getString(R.string.cancel)) - .onNegative(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - if (isLogging) { - // stop and discard logging gracefully - } - dialog.dismiss(); - } - }) - .neutralText(getResources().getString(R.string.save_data)) - .onNeutral(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - realm.beginTransaction(); - long trial; - Number trialNumber = realm.where(DataMPU6050.class).max("trial"); - if (trialNumber == null) { - trial = 0; - } else { - trial = (long) trialNumber + 1; - } - for (int i = 0; i < mpu6050DataList.size(); i++) { - DataMPU6050 tempObject = mpu6050DataList.get(i); - tempObject.setTrial(trial); - tempObject.setId(i); - realm.copyToRealm(tempObject); - } - RealmResults results = realm.where(SensorLogged.class).equalTo("sensor", "MPU6050").findAll(); - if (results.size() == 0) { - SensorLogged sensorLogged = new SensorLogged("MPU6050"); - realm.copyToRealm(sensorLogged); - } - realm.commitTransaction(); - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - "Data Logged Successfully", null, null, Snackbar.LENGTH_SHORT); - dialog.dismiss(); - } - }) - .autoDismiss(false) - .build(); - dialog.show(); - customView = dialog.getCustomView(); - break; - } - } - - private class TaskMPU6050 extends AsyncTask { - - private final MPU6050 sensorMPU6050; - private ArrayList dataMPU6050 = new ArrayList<>(); - - TaskMPU6050(MPU6050 mpu6050) { - this.sensorMPU6050 = mpu6050; - } - - @Override - protected Void doInBackground(Void... params) { - try { - dataMPU6050 = sensorMPU6050.getRaw(); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - TextView tvAx = customView.findViewById(R.id.tv_sensor_mpu6050_ax); - TextView tvAy = customView.findViewById(R.id.tv_sensor_mpu6050_ay); - TextView tvAz = customView.findViewById(R.id.tv_sensor_mpu6050_az); - TextView tvGx = customView.findViewById(R.id.tv_sensor_mpu6050_gx); - TextView tvGy = customView.findViewById(R.id.tv_sensor_mpu6050_gy); - TextView tvGz = customView.findViewById(R.id.tv_sensor_mpu6050_gz); - TextView tvTemp = customView.findViewById(R.id.tv_sensor_mpu6050_temp); - tvAx.setText(DataFormatter.formatDouble(dataMPU6050.get(0), DataFormatter.HIGH_PRECISION_FORMAT)); - tvAx.setText(DataFormatter.formatDouble(dataMPU6050.get(1), DataFormatter.HIGH_PRECISION_FORMAT)); - tvAz.setText(DataFormatter.formatDouble(dataMPU6050.get(2), DataFormatter.HIGH_PRECISION_FORMAT)); - tvAz.setText(DataFormatter.formatDouble(dataMPU6050.get(4), DataFormatter.HIGH_PRECISION_FORMAT)); - tvAz.setText(DataFormatter.formatDouble(dataMPU6050.get(5), DataFormatter.HIGH_PRECISION_FORMAT)); - tvAz.setText(DataFormatter.formatDouble(dataMPU6050.get(6), DataFormatter.HIGH_PRECISION_FORMAT)); - tvAz.setText(DataFormatter.formatDouble(dataMPU6050.get(3), DataFormatter.HIGH_PRECISION_FORMAT)); - DataMPU6050 tempObject = new DataMPU6050(dataMPU6050.get(0), dataMPU6050.get(1), dataMPU6050.get(2), - dataMPU6050.get(4), dataMPU6050.get(5), dataMPU6050.get(6), dataMPU6050.get(3)); - mpu6050DataList.add(tempObject); - Log.v("MPU6050", mpu6050DataList.size() + ""); - synchronized (lock) { - lock.notify(); - } - } - } - - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults); - if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST) { - if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - hasPermission = true; - } else { - hasPermission = false; - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - "Can't log data", null, null, Snackbar.LENGTH_SHORT); - } - } - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.activity_sensor_data_logger, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.menu_logged_data: - Intent activityLoggedData = new Intent(this, ShowLoggedData.class); - startActivity(activityLoggedData); - break; - default: - // - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onBackPressed() { - finish(); - } -} diff --git a/app/src/main/java/io/pslab/activity/SettingsActivity.java b/app/src/main/java/io/pslab/activity/SettingsActivity.java deleted file mode 100644 index c718484ae..000000000 --- a/app/src/main/java/io/pslab/activity/SettingsActivity.java +++ /dev/null @@ -1,123 +0,0 @@ -package io.pslab.activity; - -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.pm.PackageManager; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.view.MenuItem; -import android.widget.FrameLayout; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; -import androidx.fragment.app.Fragment; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import io.pslab.R; -import io.pslab.fragment.AccelerometerSettingsFragment; -import io.pslab.fragment.BaroMeterSettingsFragment; -import io.pslab.fragment.CompassSettingsFragment; -import io.pslab.fragment.DustSensorSettingsFragment; -import io.pslab.fragment.GyroscopeSettingsFragment; -import io.pslab.fragment.LuxMeterSettingFragment; -import io.pslab.fragment.MultimeterSettingsFragment; -import io.pslab.fragment.SettingsFragment; -import io.pslab.fragment.SoundmeterSettingsFragment; -import io.pslab.fragment.ThermometerSettingsFragment; -import io.pslab.models.PSLabSensor; -import io.pslab.others.GPSLogger; - - -public class SettingsActivity extends AppCompatActivity { - - @BindView(R.id.setting_toolbar) - Toolbar toolbar; - @BindView(R.id.content) - FrameLayout content; - private Unbinder unBinder; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_settings); - unBinder = ButterKnife.bind(this); - - Intent intent = getIntent(); - String title = intent.getStringExtra("title"); - - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_24dp); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setTitle(title); - } - - Fragment fragment; - switch (title) { - case PSLabSensor.LUXMETER_CONFIGURATIONS: - fragment = new LuxMeterSettingFragment(); - break; - case PSLabSensor.BAROMETER_CONFIGURATIONS: - fragment = new BaroMeterSettingsFragment(); - break; - case PSLabSensor.GYROSCOPE_CONFIGURATIONS: - fragment = new GyroscopeSettingsFragment(); - break; - case PSLabSensor.ACCELEROMETER_CONFIGURATIONS: - fragment = new AccelerometerSettingsFragment(); - break; - case PSLabSensor.THERMOMETER_CONFIGURATIONS: - fragment = new ThermometerSettingsFragment(); - break; - case "Multimeter Configurations": - fragment = new MultimeterSettingsFragment(); - break; - case PSLabSensor.COMPASS_CONFIGURATIONS: - fragment = new CompassSettingsFragment(); - break; - case PSLabSensor.DUSTSENSOR_CONFIGURATIONS: - fragment = new DustSensorSettingsFragment(); - break; - case PSLabSensor.SOUNDMETER_CONFIGURATIONS: - fragment = new SoundmeterSettingsFragment(); - break; - default: - fragment = new SettingsFragment(); - break; - } - - if (savedInstanceState == null) { - getSupportFragmentManager().beginTransaction().add(R.id.content, fragment).commit(); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return super.onOptionsItemSelected(item); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - unBinder.unbind(); - } - - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults); - if (requestCode == GPSLogger.PSLAB_PERMISSION_FOR_MAPS && (grantResults.length <= 0 - || grantResults[0] != PackageManager.PERMISSION_GRANTED)) { - SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit(); - editor.putBoolean(LuxMeterSettingFragment.KEY_INCLUDE_LOCATION, false); - editor.apply(); - } - } -} diff --git a/app/src/main/java/io/pslab/activity/ShowLoggedData.java b/app/src/main/java/io/pslab/activity/ShowLoggedData.java deleted file mode 100644 index 96857cedc..000000000 --- a/app/src/main/java/io/pslab/activity/ShowLoggedData.java +++ /dev/null @@ -1,318 +0,0 @@ -package io.pslab.activity; - -import android.content.Context; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.os.Environment; -import android.preference.PreferenceManager; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; -import androidx.recyclerview.widget.DefaultItemAnimator; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import com.afollestad.materialdialogs.MaterialDialog; -import com.google.android.material.snackbar.Snackbar; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; - -import javax.annotation.Nullable; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.pslab.R; -import io.pslab.adapters.MPUDataAdapter; -import io.pslab.models.DataMPU6050; -import io.pslab.models.SensorLogged; -import io.pslab.others.CustomSnackBar; -import io.realm.Realm; -import io.realm.RealmResults; - -/** - * Created by viveksb007 on 12/8/17. - * deprecated - */ - -public class ShowLoggedData extends AppCompatActivity { - - - @BindView(R.id.toolbar) - Toolbar toolbar; - @BindView(R.id.layout_container) - LinearLayout linearLayout; - - private Realm realm; - private Context context; - private ListView sensorListView; - private ListView trialListView; - private RecyclerView recyclerView; - private String mSensor; - private String format; - private boolean isRecyclerViewOnStack = false; - private boolean isTrialListViewOnStack = false; - private boolean isSensorListViewOnStack = false; - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_show_logged_data); - ButterKnife.bind(this); - setSupportActionBar(toolbar); - realm = Realm.getDefaultInstance(); - context = this; - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setTitle(getResources().getString(R.string.sensor_logged_data)); - } - - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); - String formatValue = preferences.getString("export_data_format_list", "0"); - if ("0".equals(formatValue)) - format = "txt"; - else - format = "csv"; - - showSensorList(); - } - - private void showSensorList() { - sensorListView = new ListView(this); - linearLayout.addView(sensorListView); - isSensorListViewOnStack = true; - RealmResults results = realm.where(SensorLogged.class).findAll(); - ArrayList sensorList = new ArrayList<>(); - if (results != null) { - for (SensorLogged temp : results) { - sensorList.add(temp.getSensor()); - } - } - ArrayAdapter adapter = new ArrayAdapter(this, - android.R.layout.simple_list_item_1, - sensorList); - sensorListView.setAdapter(adapter); - sensorListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - String sensor = ((TextView) view).getText().toString(); - mSensor = sensor; - showSensorTrialData(sensor); - } - }); - - sensorListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { - final String sensor = ((TextView) view).getText().toString(); - final MaterialDialog dialog = new MaterialDialog.Builder(context) - .title(sensor) - .customView(R.layout.sensor_list_long_click_dailog, false) - .build(); - dialog.show(); - View customView = dialog.getCustomView(); - assert customView != null; - ListView clickOptions = customView.findViewById(R.id.lv_sensor_list_click); - ArrayAdapter arrayAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.sensor_click_list)); - clickOptions.setAdapter(arrayAdapter); - - clickOptions.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - switch (position) { - case 0: - // todo : check for permission first - exportCompleteSensorData(sensor); - break; - case 1: - break; - } - dialog.dismiss(); - } - }); - return true; - } - }); - } - - private void exportCompleteSensorData(String sensor) { - File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "PSLab Android"); - boolean success = true; - if (!folder.exists()) { - success = folder.mkdir(); - } - if (success) { - if ("txt".equals(format)) { - FileOutputStream stream = null; - File file; - switch (sensor) { - case "MPU6050": - file = new File(folder, "MPU6050_" + System.currentTimeMillis() + ".txt"); - RealmResults results = realm.where(DataMPU6050.class).findAll(); - try { - stream = new FileOutputStream(file); - for (DataMPU6050 temp : results) { - stream.write((temp.getAx() + " " + temp.getAy() + " " + temp.getAz() + " " + - temp.getGx() + " " + temp.getGy() + " " + temp.getGz() + " " + temp.getTemperature() + "\n").getBytes()); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - "MPU6050 data exported successfully", null, null, Snackbar.LENGTH_SHORT); - break; - } - } else { - File file; - PrintWriter writer; - switch (sensor) { - case "MPU6050": - file = new File(folder, "MPU6050_" + System.currentTimeMillis() + ".csv"); - RealmResults results = realm.where(DataMPU6050.class).findAll(); - try { - writer = new PrintWriter(file); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("Ax,Ay,Ax,Gx,Gy,Gz,Temperature\n"); - for (DataMPU6050 temp : results) { - stringBuilder.append(temp.getAx()); - stringBuilder.append(','); - stringBuilder.append(temp.getAy()); - stringBuilder.append(','); - stringBuilder.append(temp.getAz()); - stringBuilder.append(','); - stringBuilder.append(temp.getGx()); - stringBuilder.append(','); - stringBuilder.append(temp.getGy()); - stringBuilder.append(','); - stringBuilder.append(temp.getGz()); - stringBuilder.append(','); - stringBuilder.append(temp.getTemperature()); - stringBuilder.append('\n'); - } - writer.write(stringBuilder.toString()); - writer.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - "MPU6050 data exported successfully", null, null, Snackbar.LENGTH_SHORT); - break; - } - } - } else { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - "Can't write to storage", null, null, Snackbar.LENGTH_SHORT); - } - } - - private void showSensorTrialData(final String sensor) { - Number trial; - ArrayList trialList = new ArrayList<>(); - - switch (sensor) { - case "MPU6050": - trial = realm.where(DataMPU6050.class).max("trial"); - if (trial == null) return; - long maxTrials = (long) trial + 1; - for (int i = 0; i < maxTrials; i++) { - trialList.add("Trial #" + (i + 1)); - } - break; - default: - // Todo : Add cases for other sensor - } - - linearLayout.removeView(sensorListView); - isSensorListViewOnStack = false; - trialListView = new ListView(context); - linearLayout.addView(trialListView); - isTrialListViewOnStack = true; - ArrayAdapter adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, trialList); - trialListView.setAdapter(adapter); - trialListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - populateSensorData(sensor, position); - } - }); - } - - private void populateSensorData(String sensor, long trial) { - linearLayout.removeView(trialListView); - isTrialListViewOnStack = false; - recyclerView = new RecyclerView(this); - linearLayout.addView(recyclerView); - isRecyclerViewOnStack = true; - - switch (sensor) { - case "MPU6050": - RealmResults queryResults = realm.where(DataMPU6050.class).equalTo("trial", trial).findAll(); - MPUDataAdapter mpuDataAdapter = new MPUDataAdapter(queryResults); - RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); - recyclerView.setLayoutManager(layoutManager); - recyclerView.setItemAnimator(new DefaultItemAnimator()); - recyclerView.setAdapter(mpuDataAdapter); - break; - default: - // Todo : Add other cases - } - - } - - @Override - public void onBackPressed() { - if (isRecyclerViewOnStack) { - linearLayout.removeView(recyclerView); - isRecyclerViewOnStack = false; - showSensorTrialData(mSensor); - return; - } else if (isTrialListViewOnStack) { - linearLayout.removeView(trialListView); - isTrialListViewOnStack = false; - showSensorList(); - return; - } - super.onBackPressed(); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.activity_show_item_logged_data, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.export_logged_data: - // Exporting locally logged data - break; - case android.R.id.home: - onBackPressed(); - break; - } - return super.onOptionsItemSelected(item); - } -} diff --git a/app/src/main/java/io/pslab/activity/SoundMeterActivity.java b/app/src/main/java/io/pslab/activity/SoundMeterActivity.java deleted file mode 100644 index 98d482d2e..000000000 --- a/app/src/main/java/io/pslab/activity/SoundMeterActivity.java +++ /dev/null @@ -1,135 +0,0 @@ -package io.pslab.activity; - -import android.content.SharedPreferences; - -import androidx.appcompat.app.ActionBar; -import androidx.fragment.app.Fragment; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.fragment.SoundMeterDataFragment; -import io.pslab.fragment.SoundmeterSettingsFragment; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.models.SoundData; -import io.pslab.others.LocalDataLog; -import io.realm.RealmObject; -import io.realm.RealmResults; - -/** - * @author reckoner1429 - */ -public class SoundMeterActivity extends PSLabSensor { - - private static final String PREF_NAME = "customDialogPreference"; - public RealmResults recordedSoundData; - - @Override - public int getMenu() { - return R.menu.sensor_data_log_menu; - } - - @Override - public SharedPreferences getStateSettings() { - return this.getSharedPreferences(PREF_NAME, MODE_PRIVATE); - } - - @Override - public String getFirstTimeSettingID() { - return "SoundMeterFirstTime"; - } - - @Override - public String getSensorName() { - return getResources().getString(R.string.sound_meter); - } - - @Override - public int getGuideTitle() { - return R.string.sound_meter; - } - - @Override - public int getGuideAbstract() { - return R.string.sound_meter_intro; - } - - @Override - public int getGuideSchematics() { - return R.drawable.bh1750_schematic; - } - - @Override - public int getGuideDescription() { - return R.string.sound_meter_desc; - } - - @Override - public int getGuideExtraContent() { - return 0; - } - - @Override - public void recordSensorDataBlockID(SensorDataBlock categoryData) { - realm.beginTransaction(); - realm.copyToRealm(categoryData); - realm.commitTransaction(); - } - - @Override - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((SoundData) sensorData); - realm.commitTransaction(); - } - - @Override - public void stopRecordSensorData() { - LocalDataLog.with().refresh(); - } - - @Override - public Fragment getSensorFragment() { - return SoundMeterDataFragment.newInstance(); - } - - @Override - public void getDataFromDataLogger() { - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - //playingData = true; - viewingData = true; - recordedSoundData = LocalDataLog.with() - .getBlockOfSoundRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - final SoundData data = recordedSoundData.get(0); - if (data != null) { - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - final String title = titleFormat.format(data.getTime()); - actionBar.setTitle(title); - } - } - } - } - - @Override - public boolean sensorFound() { - return true; - } - - /** - * Once settings have been changed, those changes can be captured from onResume method. - * reinstateConfigurations() will update the logs with new settings - */ - @Override - protected void onResume() { - super.onResume(); - reinstateConfigurations(); - } - - private void reinstateConfigurations() { - SharedPreferences soundMeterConfigurations; - soundMeterConfigurations = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - locationEnabled = soundMeterConfigurations.getBoolean(SoundmeterSettingsFragment.KEY_INCLUDE_LOCATION, true); - SoundMeterDataFragment.setParameters(1d, 100); - } -} diff --git a/app/src/main/java/io/pslab/activity/SplashActivity.java b/app/src/main/java/io/pslab/activity/SplashActivity.java deleted file mode 100644 index 72b9b8274..000000000 --- a/app/src/main/java/io/pslab/activity/SplashActivity.java +++ /dev/null @@ -1,72 +0,0 @@ -package io.pslab.activity; - -import android.Manifest; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.os.Bundle; -import android.os.Handler; -import android.util.Log; -import android.widget.ImageView; -import android.widget.Toast; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; - -import butterknife.ButterKnife; -import io.pslab.R; -import io.pslab.others.PSLabPermission; - -/** - * Created by viveksb007 on 11/3/17. - */ - -public class SplashActivity extends AppCompatActivity { - - private Handler handler; - private Runnable runnable; - private ImageView logo; - private ImageView text; - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.splash_screen); - ButterKnife.bind(this); - logo = findViewById(R.id.imageView); - text = findViewById(R.id.PSLabText); - logo.animate().alpha(1f).setDuration(2500); - text.animate().alpha(1f).setDuration(2500); - PSLabPermission psLabPermission = PSLabPermission.getInstance(); - if (psLabPermission.checkPermissions(SplashActivity.this, - PSLabPermission.ALL_PERMISSION)) { - exitSplashScreen(); - } - } - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults); - if(requestCode == PSLabPermission.PERMISSIONS_REQUIRED) { - exitSplashScreen(); - } - } - - @Override - public void onBackPressed() { - super.onBackPressed(); - handler.removeCallbacks(runnable); - } - - private void exitSplashScreen() { - handler = new Handler(); - int SPLASH_TIME_OUT = 2000; - handler.postDelayed(runnable = new Runnable() { - @Override - public void run() { - Intent intent = new Intent(SplashActivity.this, MainActivity.class); - startActivity(intent); - finish(); - } - }, SPLASH_TIME_OUT); - } -} diff --git a/app/src/main/java/io/pslab/activity/ThermometerActivity.java b/app/src/main/java/io/pslab/activity/ThermometerActivity.java deleted file mode 100644 index 036a15939..000000000 --- a/app/src/main/java/io/pslab/activity/ThermometerActivity.java +++ /dev/null @@ -1,144 +0,0 @@ -package io.pslab.activity; - -import android.content.SharedPreferences; -import android.hardware.Sensor; -import android.hardware.SensorManager; - -import androidx.appcompat.app.ActionBar; -import androidx.fragment.app.Fragment; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.fragment.ThermometerDataFragment; -import io.pslab.fragment.ThermometerSettingsFragment; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.models.ThermometerData; -import io.pslab.others.LocalDataLog; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class ThermometerActivity extends PSLabSensor { - - private static final String PREF_NAME = "customDialogPreference"; - public RealmResults recordedThermometerData; - public final String THERMOMETER_MAX_LIMIT = "thermometer_max_limit"; - public final String THERMOMETER_MIN_LIMIT = "thermometer_min_limit"; - - @Override - public int getMenu() { - return R.menu.sensor_data_log_menu; - } - - @Override - public SharedPreferences getStateSettings() { - return this.getSharedPreferences(PREF_NAME, MODE_PRIVATE); - } - - @Override - public String getFirstTimeSettingID() { - return "ThermometerFirstTIme"; - } - - @Override - public String getSensorName() { - return getResources().getString(R.string.thermometer); - } - - @Override - public int getGuideTitle() { - return R.string.thermometer; - } - - @Override - public int getGuideAbstract() { - return R.string.thermometer_bottom_sheet_text; - } - - @Override - public int getGuideSchematics() { - return 0; - } - - @Override - public int getGuideDescription() { - return R.string.thermometer_bottom_sheet_desc; - } - - @Override - public int getGuideExtraContent() { - return 0; - } - - @Override - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - @Override - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((ThermometerData) sensorData); - realm.commitTransaction(); - } - - @Override - public void stopRecordSensorData() { - LocalDataLog.with().refresh(); - } - - @Override - public Fragment getSensorFragment() { - return ThermometerDataFragment.newInstance(); - } - - @Override - public void getDataFromDataLogger() { - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - viewingData = true; - recordedThermometerData = LocalDataLog.with() - .getBlockOfThermometerRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - final ThermometerData data = recordedThermometerData.get(0); - if (data != null) { - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - final String title = titleFormat.format(data.getTime()); - actionBar.setTitle(title); - } - } - } - } - - @Override - public boolean sensorFound() { - SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); - return sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) != null; - } - - @Override - protected void onResume() { - super.onResume(); - reinstateConfigurations(); - } - - private void reinstateConfigurations() { - SharedPreferences thermometerConfigurations; - thermometerConfigurations = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - locationEnabled = thermometerConfigurations.getBoolean(ThermometerSettingsFragment.KEY_INCLUDE_LOCATION, true); - ThermometerDataFragment.setParameters( - getValueFromText(thermometerConfigurations.getString(ThermometerSettingsFragment.KEY_UPDATE_PERIOD, "1000"), - 100, 1000), - thermometerConfigurations.getString(ThermometerSettingsFragment.KEY_THERMO_SENSOR_TYPE, "0"), - thermometerConfigurations.getString(ThermometerSettingsFragment.KEY_THERMO_UNIT, "°C")); - } - - private int getValueFromText(String strValue, int lowerBound, int upperBound) { - if (strValue.isEmpty()) return lowerBound; - int value = Integer.parseInt(strValue); - if (value > upperBound) return upperBound; - else if (value < lowerBound) return lowerBound; - else return value; - } -} diff --git a/app/src/main/java/io/pslab/activity/WaveGeneratorActivity.java b/app/src/main/java/io/pslab/activity/WaveGeneratorActivity.java deleted file mode 100644 index bf9b6790f..000000000 --- a/app/src/main/java/io/pslab/activity/WaveGeneratorActivity.java +++ /dev/null @@ -1,1503 +0,0 @@ -package io.pslab.activity; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.pm.ActivityInfo; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import android.location.Location; -import android.location.LocationManager; -import android.media.AudioFormat; -import android.media.AudioManager; -import android.media.AudioTrack; -import android.os.AsyncTask; -import android.os.Bundle; -import android.os.Handler; -import android.util.DisplayMetrics; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.MotionEvent; -import android.view.View; -import android.view.Window; -import android.widget.Button; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.RelativeLayout; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AlertDialog; -import androidx.appcompat.widget.Toolbar; -import androidx.constraintlayout.widget.ConstraintLayout; -import androidx.coordinatorlayout.widget.CoordinatorLayout; -import androidx.core.content.ContextCompat; -import androidx.core.content.res.ResourcesCompat; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; -import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; -import com.google.android.material.snackbar.Snackbar; -import com.warkiz.widget.IndicatorSeekBar; -import com.warkiz.widget.OnSeekChangeListener; -import com.warkiz.widget.SeekParams; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Objects; -import java.util.Timer; -import java.util.TimerTask; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.pslab.R; -import io.pslab.activity.guide.GuideActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.models.SensorDataBlock; -import io.pslab.models.WaveGeneratorData; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.GPSLogger; -import io.pslab.others.LocalDataLog; -import io.pslab.others.ScienceLabCommon; -import io.pslab.others.WaveGeneratorConstants; -import io.realm.Realm; -import io.realm.RealmObject; -import io.realm.RealmResults; - -public class WaveGeneratorActivity extends GuideActivity { - - //const values - public static final int SIN = 1; - public static final int TRIANGULAR = 2; - public static final int PWM = 3; - private static final CSVDataLine CSV_HEADER = new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("Mode") - .add("Wave") - .add("Shape") - .add("Freq") - .add("Phase") - .add("Duty") - .add("lat") - .add("lon"); - private static boolean waveMonSelected; - private final long LONG_CLICK_DELAY = 100; - private final String KEY_LOG = "has_log"; - private final String DATA_BLOCK = "data_block"; - private final String MODE_SQUARE = "Square"; - private final String MODE_PWM = "PWM"; - //waveform monitor - @BindView(R.id.wave_ic_img) - ImageView selectedWaveImg; - @BindView(R.id.wave_mon_select_wave) - TextView selectedWaveText; - @BindView(R.id.wave_freq_value) - TextView waveFreqValue; - @BindView(R.id.wave_phase_value) - TextView wavePhaseValue; - @BindView(R.id.wave_mon_select_prop) - TextView waveMonPropSelect; - @BindView(R.id.wave_mon_select_prop_value) - TextView waveMonPropValueSelect; - //pwm monitor - @BindView(R.id.pwm_ic_img) - ImageView pwmSelectedModeImg; - @BindView(R.id.pwm_mon_mode_select) - TextView pwmMonSelectMode; - @BindView(R.id.pwm_freq_value) - TextView pwmFreqValue; - @BindView(R.id.pwm_phase_value) - TextView pwmPhaseValue; - @BindView(R.id.pwm_duty_value) - TextView pwmDutyValue; - @BindView(R.id.pwm_mon_select_prop) - TextView pwmMonPropSelect; - @BindView(R.id.pwm_mon_select_prop_value) - TextView pwmMonPropSelectValue; - //buttons on waveform panel - @BindView(R.id.ctrl_btn_wave1) - Button btnCtrlWave1; - @BindView(R.id.ctrl_btn_wave2) - Button btnCtrlWave2; - @BindView(R.id.ctrl_btn_freq) - Button btnCtrlFreq; - @BindView(R.id.ctrl_btn_phase) - Button btnCtrlPhase; - @BindView(R.id.ctrl_img_btn_sin) - ImageButton imgBtnSin; - @BindView(R.id.ctrl_img_btn_tri) - ImageButton imgBtnTri; - //buttons on PWM panel - @BindView(R.id.pwm_btn_sq1) - Button btnPwmSq1; - @BindView(R.id.pwm_btn_sq2) - Button btnPwmSq2; - @BindView(R.id.pwm_btn_sq3) - Button btnPwmSq3; - @BindView(R.id.pwm_btn_sq4) - Button btnPwmSq4; - @BindView(R.id.analog_mode_btn) - Button btnAnalogMode; - @BindView(R.id.digital_mode_btn) - Button btnDigitalMode; - @BindView(R.id.pwm_btn_freq) - Button pwmBtnFreq; - @BindView(R.id.pwm_btn_duty) - Button pwmBtnDuty; - @BindView(R.id.pwm_btn_phase) - Button pwmBtnPhase; - //seek bar controls - @BindView(R.id.img_btn_up) - ImageButton imgBtnUp; - @BindView(R.id.img_btn_down) - ImageButton imgBtnDown; - @BindView(R.id.seek_bar_wave_gen) - IndicatorSeekBar seekBar; - @BindView(R.id.wave_phase) - TextView wavePhaseTitle; - @BindView(R.id.btn_produce_sound) - Button btnProduceSound; - ScienceLab scienceLab; - private int leastCount, seekMax, seekMin; - private String unit; - private Timer waveGenCounter; - private final Handler wavegenHandler = new Handler(); - private AlertDialog waveDialog; - private CSVLogger csvLogger; - private WaveConst waveBtnActive, pwmBtnActive, prop_active, digital_mode; - private TextView activePropTv; - private CoordinatorLayout coordinatorLayout; - private Realm realm; - private GPSLogger gpsLogger; - private RealmResults recordedWaveData; - private ConstraintLayout pwmModeLayout; - private ConstraintLayout squareModeLayout; - private RelativeLayout pwmModeControls; - private RelativeLayout squareModeControls; - private LineChart previewChart; - private boolean isPlayingSound = false; - private ProduceSoundTask produceSoundTask; - - private AudioTrack track; - - public WaveGeneratorActivity() { - super(R.layout.activity_wave_generator_main); - } - - @SuppressLint("ClickableViewAccessibility") - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ButterKnife.bind(this); - - realm = LocalDataLog.with().getRealm(); - gpsLogger = new GPSLogger(this, - (LocationManager) getSystemService(Context.LOCATION_SERVICE)); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(getString(R.string.wave_generator)); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - coordinatorLayout = findViewById(R.id.wave_generator_coordinator_layout); - squareModeLayout = findViewById(R.id.square_mode_layout); - pwmModeLayout = findViewById(R.id.pwm_mode_layout); - previewChart = findViewById(R.id.chart_preview); - - waveBtnActive = WaveConst.WAVE1; - pwmBtnActive = WaveConst.SQR1; - squareModeControls = findViewById(R.id.square_mode_controls); - pwmModeControls = findViewById(R.id.pwm_mode_controls); - csvLogger = new CSVLogger(getString(R.string.wave_generator)); - scienceLab = ScienceLabCommon.scienceLab; - seekBar.setSaveEnabled(false); - - if (savedInstanceState != null) { - switch (Objects.requireNonNull(savedInstanceState.getString("digital_mode"))) { - case "SQUARE": - toggleDigitalMode(WaveConst.SQUARE); - break; - case "PWM": - toggleDigitalMode(WaveConst.PWM); - break; - default: - break; - } - switch (Objects.requireNonNull(savedInstanceState.getString("waveBtnActive"))) { - case "WAVE1": - waveMonSelected = true; - selectBtn(WaveConst.WAVE1); - switch (Objects.requireNonNull(savedInstanceState.getString("prop_active"))) { - case "FREQUENCY": - waveMonSelected = true; - prop_active = WaveConst.FREQUENCY; - unit = getString(R.string.unit_hz); - activePropTv = waveFreqValue; - btnCtrlFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnCtrlPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - case "PHASE": - waveMonSelected = true; - prop_active = WaveConst.PHASE; - unit = getString(R.string.deg_text); - activePropTv = wavePhaseValue; - btnCtrlFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnCtrlPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - default: - break; - } - break; - case "WAVE2": - waveMonSelected = true; - selectBtn(WaveConst.WAVE2); - switch (Objects.requireNonNull(savedInstanceState.getString("prop_active"))) { - case "FREQUENCY": - waveMonSelected = true; - prop_active = WaveConst.FREQUENCY; - unit = getString(R.string.unit_hz); - activePropTv = waveFreqValue; - btnCtrlFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnCtrlPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - case "PHASE": - waveMonSelected = true; - prop_active = WaveConst.PHASE; - unit = getString(R.string.deg_text); - activePropTv = wavePhaseValue; - btnCtrlFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnCtrlPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - default: - break; - } - break; - default: - break; - } - switch (Objects.requireNonNull(savedInstanceState.getString("pwmBtnActive"))) { - case "SQR1": - waveMonSelected = false; - selectBtn(WaveConst.SQR1); - switch (Objects.requireNonNull(savedInstanceState.getString("prop_active"))) { - case "FREQUENCY": - waveMonSelected = false; - prop_active = WaveConst.FREQUENCY; - unit = getString(R.string.unit_hz); - activePropTv = pwmFreqValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - case "PHASE": - waveMonSelected = false; - prop_active = WaveConst.PHASE; - unit = getString(R.string.deg_text); - activePropTv = pwmPhaseValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - case "DUTY": - waveMonSelected = false; - prop_active = WaveConst.DUTY; - unit = getString(R.string.unit_percent); - activePropTv = pwmDutyValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - default: - break; - } - break; - case "SQR2": - selectBtn(WaveConst.SQR2); - switch (Objects.requireNonNull(savedInstanceState.getString("prop_active"))) { - case "FREQUENCY": - waveMonSelected = false; - prop_active = WaveConst.FREQUENCY; - unit = getString(R.string.unit_hz); - activePropTv = pwmFreqValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - case "PHASE": - waveMonSelected = false; - prop_active = WaveConst.PHASE; - unit = getString(R.string.deg_text); - activePropTv = pwmPhaseValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - case "DUTY": - waveMonSelected = false; - prop_active = WaveConst.DUTY; - unit = getString(R.string.unit_percent); - activePropTv = pwmDutyValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - default: - break; - } - break; - case "SQR3": - selectBtn(WaveConst.SQR3); - switch (Objects.requireNonNull(savedInstanceState.getString("prop_active"))) { - case "FREQUENCY": - waveMonSelected = false; - prop_active = WaveConst.FREQUENCY; - unit = getString(R.string.unit_hz); - activePropTv = pwmFreqValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - case "PHASE": - waveMonSelected = false; - prop_active = WaveConst.PHASE; - unit = getString(R.string.deg_text); - activePropTv = pwmPhaseValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - case "DUTY": - waveMonSelected = false; - prop_active = WaveConst.DUTY; - unit = getString(R.string.unit_percent); - activePropTv = pwmDutyValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - default: - break; - } - break; - case "SQR4": - selectBtn(WaveConst.SQR4); - switch (Objects.requireNonNull(savedInstanceState.getString("prop_active"))) { - case "FREQUENCY": - waveMonSelected = false; - prop_active = WaveConst.FREQUENCY; - unit = getString(R.string.unit_hz); - activePropTv = pwmFreqValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - case "PHASE": - waveMonSelected = false; - prop_active = WaveConst.PHASE; - unit = getString(R.string.deg_text); - activePropTv = pwmPhaseValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - case "DUTY": - waveMonSelected = false; - prop_active = WaveConst.DUTY; - unit = getString(R.string.unit_percent); - activePropTv = pwmDutyValue; - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - break; - default: - break; - } - break; - default: - break; - } - } else { - enableInitialState(); - } - waveDialog = createIntentDialog(); - - //wave panel - btnCtrlWave1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (!waveBtnActive.equals(WaveConst.WAVE1)) { - waveMonSelected = true; - selectBtn(WaveConst.WAVE1); - } - } - }); - btnCtrlWave2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (!waveBtnActive.equals(WaveConst.WAVE2)) { - waveMonSelected = true; - selectBtn(WaveConst.WAVE2); - } - } - }); - imgBtnSin.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - selectWaveform(SIN); - } - }); - - imgBtnTri.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - selectWaveform(TRIANGULAR); - } - }); - - btnCtrlFreq.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - waveMonSelected = true; - prop_active = WaveConst.FREQUENCY; - unit = getString(R.string.unit_hz); - activePropTv = waveFreqValue; - waveMonPropSelect.setText(getString(R.string.wave_frequency)); - setSeekBar(seekBar); - btnCtrlFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - btnCtrlPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - } - }); - - btnCtrlPhase.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - waveMonSelected = true; - prop_active = WaveConst.PHASE; - unit = getString(R.string.deg_text); - activePropTv = wavePhaseValue; - waveMonPropSelect.setText(getString(R.string.phase_offset)); - setSeekBar(seekBar); - btnCtrlFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnCtrlPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - } - }); - - btnAnalogMode.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - toggleDigitalMode(WaveConst.SQUARE); - } - }); - - btnDigitalMode.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - toggleDigitalMode(WaveConst.PWM); - } - }); - - btnPwmSq1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (!pwmBtnActive.equals(WaveConst.SQR1)) { - waveMonSelected = false; - selectBtn(WaveConst.SQR1); - } - } - }); - - btnPwmSq2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (!pwmBtnActive.equals(WaveConst.SQR2)) { - waveMonSelected = false; - selectBtn(WaveConst.SQR2); - } - } - }); - - btnPwmSq3.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (!pwmBtnActive.equals(WaveConst.SQR3)) { - waveMonSelected = false; - selectBtn(WaveConst.SQR3); - } - } - }); - - btnPwmSq4.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (!pwmBtnActive.equals(WaveConst.SQR4)) { - waveMonSelected = false; - selectBtn(WaveConst.SQR4); - } - } - }); - - pwmBtnFreq.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - waveMonSelected = false; - prop_active = WaveConst.FREQUENCY; - unit = getString(R.string.unit_hz); - activePropTv = pwmFreqValue; - pwmMonPropSelect.setText(getString(R.string.frequecy_colon)); - setSeekBar(seekBar); - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - } - }); - - pwmBtnPhase.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - waveMonSelected = false; - prop_active = WaveConst.PHASE; - unit = getString(R.string.deg_text); - activePropTv = pwmPhaseValue; - pwmMonPropSelect.setText(getString(R.string.pwm_phase)); - setSeekBar(seekBar); - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - } - }); - - pwmBtnDuty.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - waveMonSelected = false; - prop_active = WaveConst.DUTY; - unit = getString(R.string.unit_percent); - activePropTv = pwmDutyValue; - pwmMonPropSelect.setText(getString(R.string.duty_cycle)); - setSeekBar(seekBar); - pwmBtnFreq.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnDuty.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - } - }); - - monitorVariations(imgBtnUp, imgBtnDown); - - monitorLongClicks(imgBtnUp, imgBtnDown); - - seekBar.setOnSeekChangeListener(new OnSeekChangeListener() { - @Override - public void onSeeking(SeekParams seekParams) { - String valueText = formatWithUnit(seekParams.progress, unit); - - if (waveMonSelected) { - waveMonPropValueSelect.setText(valueText); - } else { - pwmMonPropSelectValue.setText(valueText); - } - setValue(); - } - - @Override - public void onStartTrackingTouch(IndicatorSeekBar seekBar) { - // Unused method override - } - - @Override - public void onStopTrackingTouch(IndicatorSeekBar seekBar) { - // Unused method override - } - }); - - if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(KEY_LOG)) { - recordedWaveData = LocalDataLog.with() - .getBlockOfWaveRecords(getIntent().getExtras().getLong(DATA_BLOCK)); - setReceivedData(); - } - chartInit(); - - btnProduceSound.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (isPlayingSound) { - btnProduceSound.setText(getResources().getString(R.string.produce_sound_text)); - produceSoundTask.cancel(true); - produceSoundTask = null; - isPlayingSound = false; - } else { - btnProduceSound.setText(getResources().getString(R.string.stop_sound_text)); - produceSoundTask = new ProduceSoundTask(); - produceSoundTask.execute(); - isPlayingSound = true; - } - } - }); - - if (getResources().getBoolean(R.bool.isTablet)) { - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER); - } - - activePropTv = prop_active == WaveConst.FREQUENCY ? waveFreqValue : wavePhaseValue; - } - - public void saveWaveConfig() { - long block = System.currentTimeMillis(); - csvLogger.prepareLogFile(); - csvLogger.writeMetaData(getResources().getString(R.string.wave_generator)); - long timestamp; - double lat, lon; - csvLogger.writeCSVFile(CSV_HEADER); - recordSensorDataBlockID(new SensorDataBlock(block, getResources().getString(R.string.wave_generator))); - double freq1 = (double) (WaveGeneratorConstants.wave.get(WaveConst.WAVE1).get(WaveConst.FREQUENCY)); - double freq2 = (double) WaveGeneratorConstants.wave.get(WaveConst.WAVE2).get(WaveConst.FREQUENCY); - double phase = (double) WaveGeneratorConstants.wave.get(WaveConst.WAVE2).get(WaveConst.PHASE); - - String waveType1 = WaveGeneratorConstants.wave.get(WaveConst.WAVE1).get(WaveConst.WAVETYPE) == SIN ? "sine" : "tria"; - String waveType2 = WaveGeneratorConstants.wave.get(WaveConst.WAVE2).get(WaveConst.WAVETYPE) == SIN ? "sine" : "tria"; - - if (gpsLogger.isGPSEnabled()) { - Location location = gpsLogger.getDeviceLocation(); - if (location != null) { - lat = location.getLatitude(); - lon = location.getLongitude(); - } else { - lat = 0.0; - lon = 0.0; - } - } else { - lat = 0.0; - lon = 0.0; - } - - timestamp = System.currentTimeMillis(); - String timeData = timestamp + "," + CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp)); - String locationData = lat + "," + lon; - String dateTime = CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp)); - if (scienceLab.isConnected()) { - if (digital_mode == WaveConst.SQUARE) { - csvLogger.writeCSVFile(new CSVDataLine().add(timestamp).add(dateTime).add("Square").add("Wave1").add(waveType1).add(freq1).add(0).add(0).add(lat).add(lon)); //wave1 - recordSensorData(new WaveGeneratorData(timestamp, block, "Square", "Wave1", waveType1, String.valueOf(freq1), "0", "0", lat, lon)); - csvLogger.writeCSVFile(new CSVDataLine().add(timestamp).add(dateTime).add("Square").add("Wave2").add(waveType2).add(freq2).add(phase).add(0).add(lat).add(lon)); //wave2 - recordSensorData(new WaveGeneratorData(timestamp + 1, block, "Square", "Wave2", waveType2, String.valueOf(freq2), String.valueOf(phase), "0", lat, lon)); - } else { - double freqSqr1 = (double) WaveGeneratorConstants.wave.get(WaveConst.SQR1).get(WaveConst.FREQUENCY); - double dutySqr1 = (double) WaveGeneratorConstants.wave.get(WaveConst.SQR1).get(WaveConst.DUTY) / 100; - double dutySqr2 = ((double) WaveGeneratorConstants.wave.get(WaveConst.SQR2).get(WaveConst.DUTY)) / 100; - double phaseSqr2 = (double) WaveGeneratorConstants.wave.get(WaveConst.SQR2).get(WaveConst.PHASE) / 360; - double dutySqr3 = ((double) WaveGeneratorConstants.wave.get(WaveConst.SQR3).get(WaveConst.DUTY)) / 100; - double phaseSqr3 = (double) WaveGeneratorConstants.wave.get(WaveConst.SQR3).get(WaveConst.PHASE) / 360; - double dutySqr4 = ((double) WaveGeneratorConstants.wave.get(WaveConst.SQR4).get(WaveConst.DUTY)) / 100; - double phaseSqr4 = (double) WaveGeneratorConstants.wave.get(WaveConst.SQR4).get(WaveConst.PHASE) / 360; - - csvLogger.writeCSVFile(new CSVDataLine().add(timestamp).add(dateTime).add("PWM").add("Sq1").add("PWM").add(freqSqr1).add(0).add(dutySqr1).add(lat).add(lon)); - recordSensorData(new WaveGeneratorData(timestamp, block, "PWM", "Sq1", "PWM", String.valueOf(freqSqr1), "0", String.valueOf(dutySqr1), lat, lon)); - csvLogger.writeCSVFile(new CSVDataLine().add(timestamp).add(dateTime).add("PWM").add("Sq2").add("PWM").add(freqSqr1).add(phaseSqr2).add(dutySqr2).add(lat).add(lon)); - recordSensorData(new WaveGeneratorData(timestamp + 1, block, "PWM", "Sq2", "PWM", String.valueOf(freqSqr1), String.valueOf(phaseSqr2), String.valueOf(dutySqr2), lat, lon)); - csvLogger.writeCSVFile(new CSVDataLine().add(timestamp).add(dateTime).add("PWM").add("Sq3").add("PWM").add(freqSqr1).add(phaseSqr3).add(dutySqr3).add(lat).add(lon)); - recordSensorData(new WaveGeneratorData(timestamp + 2, block, "PWM", "Sq3", "PWM", String.valueOf(freqSqr1), String.valueOf(phaseSqr3), String.valueOf(dutySqr3), lat, lon)); - csvLogger.writeCSVFile(new CSVDataLine().add(timestamp).add(dateTime).add("PWM").add("Sq4").add("PWM").add(freqSqr1).add(phaseSqr4).add(dutySqr4).add(lat).add(lon)); - recordSensorData(new WaveGeneratorData(timestamp + 3, block, "PWM", "Sq4", "PWM", String.valueOf(freqSqr1), String.valueOf(phaseSqr4), String.valueOf(dutySqr4), lat, lon)); - } - CustomSnackBar.showSnackBar(coordinatorLayout, - getString(R.string.csv_store_text) + " " + csvLogger.getCurrentFilePath() - , getString(R.string.open), new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(WaveGeneratorActivity.this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getResources().getString(R.string.wave_generator)); - startActivity(intent); - } - }, Snackbar.LENGTH_SHORT); - } else { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.device_not_connected), null, null, Snackbar.LENGTH_SHORT); - } - } - - public void setReceivedData() { - for (WaveGeneratorData data : recordedWaveData) { - Log.d("data", data.toString()); - if (data.getMode().equals(MODE_SQUARE)) { - WaveGeneratorConstants.mode_selected = WaveConst.SQUARE; - switch (data.getWave()) { - case "Wave1": - if (data.getShape().equals("sine")) { - WaveGeneratorConstants.wave.get(WaveConst.WAVE1).put(WaveConst.WAVETYPE, SIN); - } else { - WaveGeneratorConstants.wave.get(WaveConst.WAVE1).put(WaveConst.WAVETYPE, TRIANGULAR); - } - WaveGeneratorConstants.wave.get(WaveConst.WAVE1).put(WaveConst.FREQUENCY, Double.valueOf(data.getFreq()).intValue()); - break; - case "Wave2": - if (data.getShape().equals("sine")) { - WaveGeneratorConstants.wave.get(WaveConst.WAVE2).put(WaveConst.WAVETYPE, SIN); - } else { - WaveGeneratorConstants.wave.get(WaveConst.WAVE2).put(WaveConst.WAVETYPE, TRIANGULAR); - } - WaveGeneratorConstants.wave.get(WaveConst.WAVE2).put(WaveConst.FREQUENCY, Double.valueOf(data.getFreq()).intValue()); - WaveGeneratorConstants.wave.get(WaveConst.WAVE2).put(WaveConst.PHASE, Double.valueOf(data.getPhase()).intValue()); - break; - } - enableInitialState(); - } else if (data.getMode().equals(MODE_PWM)) { - WaveGeneratorConstants.mode_selected = WaveConst.PWM; - switch (data.getWave()) { - case "Sq1": - WaveGeneratorConstants.wave.get(WaveConst.SQR1).put(WaveConst.FREQUENCY, Double.valueOf(data.getFreq()).intValue()); - WaveGeneratorConstants.wave.get(WaveConst.SQR1).put(WaveConst.DUTY, ((Double) (Double.valueOf(data.getDuty()) * 100)).intValue()); - break; - case "Sq2": - WaveGeneratorConstants.wave.get(WaveConst.SQR2).put(WaveConst.DUTY, ((Double) (Double.valueOf(data.getDuty()) * 100)).intValue()); - WaveGeneratorConstants.wave.get(WaveConst.SQR2).put(WaveConst.PHASE, ((Double) (Double.valueOf(data.getPhase()) * 360)).intValue()); - break; - case "Sq3": - WaveGeneratorConstants.wave.get(WaveConst.SQR3).put(WaveConst.DUTY, ((Double) (Double.valueOf(data.getDuty()) * 100)).intValue()); - WaveGeneratorConstants.wave.get(WaveConst.SQR3).put(WaveConst.PHASE, ((Double) (Double.valueOf(data.getPhase()) * 360)).intValue()); - break; - case "Sq4": - WaveGeneratorConstants.wave.get(WaveConst.SQR4).put(WaveConst.DUTY, ((Double) (Double.valueOf(data.getDuty()) * 100)).intValue()); - WaveGeneratorConstants.wave.get(WaveConst.SQR4).put(WaveConst.PHASE, ((Double) (Double.valueOf(data.getPhase()) * 360)).intValue()); - break; - } - enableInitialStatePWM(); - } - } - } - - private void setWave() { - double freq1 = (double) (WaveGeneratorConstants.wave.get(WaveConst.WAVE1).get(WaveConst.FREQUENCY)); - double freq2 = (double) WaveGeneratorConstants.wave.get(WaveConst.WAVE2).get(WaveConst.FREQUENCY); - double phase = (double) WaveGeneratorConstants.wave.get(WaveConst.WAVE2).get(WaveConst.PHASE); - - String waveType1 = WaveGeneratorConstants.wave.get(WaveConst.WAVE1).get(WaveConst.WAVETYPE) == SIN ? "sine" : "tria"; - String waveType2 = WaveGeneratorConstants.wave.get(WaveConst.WAVE2).get(WaveConst.WAVETYPE) == SIN ? "sine" : "tria"; - - if (scienceLab.isConnected()) { - if (digital_mode == WaveConst.SQUARE) { - if (phase == WaveData.PHASE_MIN.getValue()) { - scienceLab.setSI1(freq1, waveType1); - scienceLab.setSI2(freq2, waveType2); - } else { - scienceLab.setWaves(freq1, phase, freq2); - } - } else { - double freqSqr1 = (double) WaveGeneratorConstants.wave.get(WaveConst.SQR1).get(WaveConst.FREQUENCY); - double dutySqr1 = (double) WaveGeneratorConstants.wave.get(WaveConst.SQR1).get(WaveConst.DUTY) / 100; - double dutySqr2 = ((double) WaveGeneratorConstants.wave.get(WaveConst.SQR2).get(WaveConst.DUTY)) / 100; - double phaseSqr2 = (double) WaveGeneratorConstants.wave.get(WaveConst.SQR2).get(WaveConst.PHASE) / 360; - double dutySqr3 = ((double) WaveGeneratorConstants.wave.get(WaveConst.SQR3).get(WaveConst.DUTY)) / 100; - double phaseSqr3 = (double) WaveGeneratorConstants.wave.get(WaveConst.SQR3).get(WaveConst.PHASE) / 360; - double dutySqr4 = ((double) WaveGeneratorConstants.wave.get(WaveConst.SQR4).get(WaveConst.DUTY)) / 100; - double phaseSqr4 = (double) WaveGeneratorConstants.wave.get(WaveConst.SQR4).get(WaveConst.PHASE) / 360; - - scienceLab.sqrPWM(freqSqr1, dutySqr1, phaseSqr2, dutySqr2, phaseSqr3, dutySqr3, phaseSqr4, dutySqr4, false); - } - - } - } - - private void viewWaveDialog() { - waveDialog.show(); - Window window = waveDialog.getWindow(); - window.setLayout(dpToPx(350), dpToPx(300)); - waveDialog.getButton(DialogInterface.BUTTON_NEGATIVE) - .setTextColor(ContextCompat.getColor(WaveGeneratorActivity.this, R.color.colorPrimary)); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.wave_generator_menu, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - if (produceSoundTask != null) - produceSoundTask.cancel(true); - produceSoundTask = null; - isPlayingSound = false; - finish(); - break; - case R.id.save_data: - saveWaveConfig(); - break; - case R.id.play_data: - setWave(); - if (scienceLab.isConnected()) { - viewWaveDialog(); - } else { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.device_not_connected), null, null, Snackbar.LENGTH_SHORT); - } - break; - case R.id.show_guide: - toggleGuide(); - break; - case R.id.show_logged_data: - Intent intent = new Intent(WaveGeneratorActivity.this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getString(R.string.wave_generator)); - startActivity(intent); - break; - default: - break; - } - return true; - } - - public void selectBtn(WaveConst btn_selected) { - - switch (btn_selected) { - - case WAVE1: - - waveBtnActive = WaveConst.WAVE1; - - btnCtrlWave1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - btnCtrlWave2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - - btnCtrlPhase.setEnabled(false); //disable phase for wave - btnCtrlPhase.setVisibility(View.INVISIBLE); - wavePhaseValue.setText("--"); - - selectWaveform(WaveGeneratorConstants.wave.get(waveBtnActive).get(WaveConst.WAVETYPE)); - - fetchPropertyValue(waveBtnActive, WaveConst.FREQUENCY, getString(R.string.unit_hz), waveFreqValue); - wavePhaseTitle.setText(getResources().getString(R.string.text_phase_colon)); - break; - - case WAVE2: - - waveBtnActive = WaveConst.WAVE2; - - btnCtrlWave2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - btnCtrlWave1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - - btnCtrlPhase.setEnabled(true); // enable phase for wave2 - btnCtrlPhase.setVisibility(View.VISIBLE); - - selectWaveform(WaveGeneratorConstants.wave.get(waveBtnActive).get(WaveConst.WAVETYPE)); - - fetchPropertyValue(waveBtnActive, WaveConst.FREQUENCY, getString(R.string.unit_hz), waveFreqValue); - fetchPropertyValue(waveBtnActive, WaveConst.PHASE, getString(R.string.deg_text), wavePhaseValue); - wavePhaseTitle.setText(getResources().getString(R.string.text_phase_colon)); - break; - - case SQR1: - pwmBtnActive = WaveConst.SQR1; - btnPwmSq1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - btnPwmSq2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnPwmSq3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnPwmSq4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setEnabled(false); //phase disabled for sq1 - pwmBtnPhase.setVisibility(View.INVISIBLE); - pwmPhaseValue.setText("--"); - fetchPropertyValue(pwmBtnActive, WaveConst.FREQUENCY, getString(R.string.unit_hz), pwmFreqValue); - fetchPropertyValue(pwmBtnActive, WaveConst.DUTY, getString(R.string.unit_percent), pwmDutyValue); - break; - - case SQR2: - - pwmBtnActive = WaveConst.SQR2; - btnPwmSq1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnPwmSq2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - btnPwmSq3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnPwmSq4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setEnabled(true); - pwmBtnPhase.setVisibility(View.VISIBLE); - fetchPropertyValue(WaveConst.SQR1, WaveConst.FREQUENCY, getString(R.string.unit_hz), pwmFreqValue); - fetchPropertyValue(pwmBtnActive, WaveConst.PHASE, getString(R.string.deg_text), pwmPhaseValue); - fetchPropertyValue(pwmBtnActive, WaveConst.DUTY, getString(R.string.unit_percent), pwmDutyValue); - break; - - case SQR3: - - pwmBtnActive = WaveConst.SQR3; - btnPwmSq1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnPwmSq2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnPwmSq3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - btnPwmSq4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - pwmBtnPhase.setEnabled(true); - pwmBtnPhase.setVisibility(View.VISIBLE); - fetchPropertyValue(WaveConst.SQR1, WaveConst.FREQUENCY, getString(R.string.unit_hz), pwmFreqValue); - fetchPropertyValue(pwmBtnActive, WaveConst.PHASE, getString(R.string.deg_text), pwmPhaseValue); - fetchPropertyValue(pwmBtnActive, WaveConst.DUTY, getString(R.string.unit_percent), pwmDutyValue); - break; - - case SQR4: - - pwmBtnActive = WaveConst.SQR4; - btnPwmSq1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnPwmSq2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnPwmSq3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnPwmSq4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - pwmBtnPhase.setEnabled(true); - pwmBtnPhase.setVisibility(View.VISIBLE); - fetchPropertyValue(WaveConst.SQR1, WaveConst.FREQUENCY, getString(R.string.unit_hz), pwmFreqValue); - fetchPropertyValue(pwmBtnActive, WaveConst.PHASE, getString(R.string.deg_text), pwmPhaseValue); - fetchPropertyValue(pwmBtnActive, WaveConst.DUTY, getString(R.string.unit_percent), pwmDutyValue); - break; - - default: - waveBtnActive = WaveConst.WAVE1; - btnCtrlWave1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - btnCtrlWave2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnCtrlPhase.setEnabled(false); //disable phase for wave - pwmBtnPhase.setVisibility(View.INVISIBLE); - wavePhaseValue.setText("--"); - selectWaveform(WaveGeneratorConstants.wave.get(waveBtnActive).get(WaveConst.WAVETYPE)); - fetchPropertyValue(waveBtnActive, WaveConst.FREQUENCY, getString(R.string.unit_hz), waveFreqValue); - break; - - } - prop_active = null; - toggleSeekBtns(false); - previewWave(); - } - - private void selectWaveform(final int waveType) { - String waveFormText; - Drawable image; - - switch (waveType) { - case SIN: - waveFormText = getString(R.string.sine); - imgBtnSin.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - imgBtnTri.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - WaveGeneratorConstants.wave.get(waveBtnActive).put(WaveConst.WAVETYPE, SIN); - image = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_sin, null); - break; - - case TRIANGULAR: - waveFormText = getString(R.string.triangular); - imgBtnSin.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - imgBtnTri.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - WaveGeneratorConstants.wave.get(waveBtnActive).put(WaveConst.WAVETYPE, TRIANGULAR); - image = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_triangular, null); - break; - case PWM: - waveFormText = getResources().getString(R.string.text_pwm); - WaveGeneratorConstants.wave.get(waveBtnActive).put(WaveConst.WAVETYPE, PWM); - image = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_pwm_pic, null); - break; - - default: - waveFormText = getString(R.string.sine); - WaveGeneratorConstants.wave.get(waveBtnActive).put(WaveConst.WAVETYPE, SIN); - image = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_sin, null); - } - selectedWaveText.setText(waveFormText); - selectedWaveImg.setImageDrawable(image); - previewWave(); - } - - private void toggleDigitalMode(WaveConst mode) { - waveMonSelected = false; - if (mode == WaveConst.SQUARE) { - digital_mode = WaveConst.SQUARE; - pwmModeLayout.setVisibility(View.GONE); - pwmModeControls.setVisibility(View.GONE); - squareModeLayout.setVisibility(View.VISIBLE); - squareModeControls.setVisibility(View.VISIBLE); - imgBtnSin.setEnabled(true); - imgBtnTri.setEnabled(true); - pwmSelectedModeImg.setImageResource(R.drawable.ic_square); - pwmMonSelectMode.setText(getString(R.string.square)); - btnPwmSq2.setEnabled(false); - btnPwmSq3.setEnabled(false); - btnPwmSq4.setEnabled(false); - pwmBtnPhase.setEnabled(false); - btnDigitalMode.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - btnAnalogMode.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - - } else { - digital_mode = WaveConst.PWM; - pwmModeLayout.setVisibility(View.VISIBLE); - pwmModeControls.setVisibility(View.VISIBLE); - squareModeLayout.setVisibility(View.GONE); - squareModeControls.setVisibility(View.GONE); - pwmSelectedModeImg.setImageResource(R.drawable.ic_pwm_pic); - pwmMonSelectMode.setText(getString(R.string.text_pwm)); - btnPwmSq2.setEnabled(true); - btnPwmSq3.setEnabled(true); - btnPwmSq4.setEnabled(true); - imgBtnSin.setEnabled(false); - imgBtnTri.setEnabled(false); - selectBtn(WaveConst.SQR2); - btnDigitalMode.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded, null)); - btnAnalogMode.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_back_rounded_light, null)); - } - WaveGeneratorConstants.mode_selected = mode; - previewWave(); - } - - private void fetchPropertyValue(WaveConst btnActive, WaveConst property, String unit, TextView propTextView) { - if (WaveGeneratorConstants.wave.get(btnActive).get(property) != null) { - int value = WaveGeneratorConstants.wave.get(btnActive).get(property); - propTextView.setText(formatWithUnit(value, unit)); - } else { - if (property == WaveConst.FREQUENCY) { - int value = WaveData.FREQ_MIN.getValue(); - propTextView.setText(formatWithUnit(value, unit)); - } else if (property == WaveConst.PHASE) { - int value = WaveData.PHASE_MIN.getValue(); - propTextView.setText(formatWithUnit(value, unit)); - } else { - int value = WaveData.DUTY_MIN.getValue(); - propTextView.setText(formatWithUnit(value, unit)); - } - } - } - - private void setSeekBar(IndicatorSeekBar seekBar) { - - int numTicks; - - switch (prop_active) { - case FREQUENCY: - seekMin = WaveData.FREQ_MIN.getValue(); - seekMax = WaveData.FREQ_MAX.getValue(); - numTicks = 50; - leastCount = 1; - break; - - case PHASE: - seekMin = WaveData.PHASE_MIN.getValue(); - seekMax = WaveData.PHASE_MAX.getValue(); - numTicks = 50; - leastCount = 1; - break; - - case DUTY: - seekMin = WaveData.DUTY_MIN.getValue(); - seekMax = WaveData.DUTY_MAX.getValue(); - numTicks = 50; - leastCount = 1; - unit = getString(R.string.unit_percent); - break; - - default: - seekMin = 0; - seekMax = 5000; - numTicks = 50; - leastCount = 1; - } - - seekBar.setMin(seekMin); - seekBar.setMax(seekMax); - seekBar.setTickCount(numTicks); - - if (!waveMonSelected) { - waveMonPropSelect.setText(""); - waveMonPropValueSelect.setText(""); - - if (prop_active.equals(WaveConst.FREQUENCY)) { - if (WaveGeneratorConstants.wave.get(WaveConst.SQR1).get(prop_active) != null) { - seekBar.setProgress(WaveGeneratorConstants.wave.get(WaveConst.SQR1).get(prop_active)); - } - } else { - if (WaveGeneratorConstants.wave.get(pwmBtnActive).get(prop_active) != null) { - seekBar.setProgress(WaveGeneratorConstants.wave.get(pwmBtnActive).get(prop_active)); - } - } - } else { - pwmMonPropSelect.setText(""); - pwmMonPropSelectValue.setText(""); - if (WaveGeneratorConstants.wave.get(waveBtnActive).get(prop_active) != null) { - seekBar.setProgress(WaveGeneratorConstants.wave.get(waveBtnActive).get(prop_active)); - } - } - toggleSeekBtns(true); - } - - private void incProgressSeekBar() { - seekBar.setProgress(seekBar.getProgress() + leastCount); - } - - private void decProgressSeekBar() { - seekBar.setProgress(seekBar.getProgress() - leastCount); - } - - private void setValue() { - int value = seekBar.getProgress(); - - if (!waveMonSelected) { - if (prop_active == WaveConst.FREQUENCY) { - WaveGeneratorConstants.wave.get(WaveConst.SQR1).put(prop_active, value); - } else { - if (prop_active == WaveConst.DUTY) { - if (value != WaveData.DUTY_MIN.getValue()) { - WaveGeneratorConstants.state.put(pwmBtnActive.toString(), 1); - } else - WaveGeneratorConstants.state.put(pwmBtnActive.toString(), 0); - } - WaveGeneratorConstants.wave.get(pwmBtnActive).put(prop_active, value); - } - } else { - WaveGeneratorConstants.wave.get(waveBtnActive).put(prop_active, value); - } - setWave(); - previewWave(); - activePropTv.setText(formatWithUnit(value, unit)); - } - - private static String formatWithUnit(int value, String unit) { - return value + ("\u00b0".equals(unit) ? "" : " ") + unit; - } - - private void previewWave() { - List dataSets = new ArrayList<>(); - ArrayList entries = getSamplePoints(false); - ArrayList refEntries = getSamplePoints(true); - LineDataSet dataSet; - LineDataSet refDataSet; - if (WaveGeneratorConstants.mode_selected == WaveConst.PWM) { - dataSet = new LineDataSet(entries, pwmBtnActive.toString()); - refDataSet = new LineDataSet(refEntries, getResources().getString(R.string.reference_wave_title)); - } else { - dataSet = new LineDataSet(entries, waveBtnActive.toString()); - refDataSet = new LineDataSet(refEntries, getResources().getString(R.string.reference_wave_title)); - } - dataSet.setDrawCircles(false); - dataSet.setColor(Color.WHITE); - refDataSet.setDrawCircles(false); - refDataSet.setColor(Color.GRAY); - dataSets.add(refDataSet); - dataSets.add(dataSet); - LineData data = new LineData(dataSets); - data.setDrawValues(false); - previewChart.setData(data); - previewChart.notifyDataSetChanged(); - previewChart.invalidate(); - } - - private ArrayList getSamplePoints(boolean isReference) { - ArrayList entries = new ArrayList<>(); - if (WaveGeneratorConstants.mode_selected == WaveConst.PWM) { - double freq = (double) WaveGeneratorConstants.wave.get(WaveConst.SQR1).get(WaveConst.FREQUENCY); - double duty = ((double) WaveGeneratorConstants.wave.get(pwmBtnActive).get(WaveConst.DUTY)) / 100; - double phase = 0; - if (pwmBtnActive != WaveConst.SQR1 && !isReference) { - phase = (double) WaveGeneratorConstants.wave.get(pwmBtnActive).get(WaveConst.PHASE); - } - for (int i = 0; i < 5000; i++) { - double t = 2 * Math.PI * freq * (i) / 1e6 + phase * Math.PI / 180; - double y; - if (t % (2 * Math.PI) < 2 * Math.PI * duty) { - y = 5; - } else { - y = -5; - } - entries.add(new Entry((float) i, (float) y)); - } - } else { - double phase = 0; - int shape = WaveGeneratorConstants.wave.get(waveBtnActive).get(WaveConst.WAVETYPE); - double freq = (double) WaveGeneratorConstants.wave.get(waveBtnActive).get(WaveConst.FREQUENCY); - - if (waveBtnActive != WaveConst.WAVE1 && !isReference) { - phase = (double) WaveGeneratorConstants.wave.get(WaveConst.WAVE2).get(WaveConst.PHASE); - } - if (shape == 1) { - for (int i = 0; i < 5000; i++) { - float y = (float) (5 * Math.sin(2 * Math.PI * (freq / 1e6) * i + phase * Math.PI / 180)); - entries.add(new Entry((float) i, y)); - } - } else { - for (int i = 0; i < 5000; i++) { - float y = (float) ((10 / Math.PI) * (Math.asin(Math.sin(2 * Math.PI * (freq / 1e6) * i + phase * Math.PI / 180)))); - entries.add(new Entry((float) i, y)); - } - } - } - return entries; - } - - private void chartInit() { - previewChart.setTouchEnabled(true); - previewChart.setHighlightPerDragEnabled(true); - previewChart.setDragEnabled(true); - previewChart.setScaleEnabled(true); - previewChart.setDrawGridBackground(false); - previewChart.setPinchZoom(true); - previewChart.setScaleYEnabled(false); - previewChart.setBackgroundColor(Color.BLACK); - previewChart.getDescription().setEnabled(false); - previewChart.getXAxis().setAxisMaximum(5000); - previewChart.getXAxis().setAxisMinimum(0); - previewChart.getXAxis().setTextColor(Color.WHITE); - previewChart.getAxisLeft().setAxisMaximum(10); - previewChart.getAxisLeft().setAxisMinimum(-10); - previewChart.getAxisRight().setAxisMaximum(10); - previewChart.getAxisRight().setAxisMinimum(-10); - previewChart.fitScreen(); - previewChart.invalidate(); - Legend l = previewChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - } - - private void toggleSeekBtns(boolean state) { - if (!state) { - waveMonPropSelect.setText(""); - waveMonPropValueSelect.setText(""); - pwmMonPropSelect.setText(""); - pwmMonPropSelectValue.setText(""); - } - imgBtnUp.setEnabled(state); - imgBtnDown.setEnabled(state); - seekBar.setEnabled(state); - } - - private void enableInitialState() { - selectBtn(WaveConst.WAVE1); - toggleDigitalMode(WaveConst.SQUARE); - } - - private void enableInitialStatePWM() { - selectBtn(WaveConst.SQR2); - toggleDigitalMode(WaveConst.PWM); - } - - @Override - protected void onSaveInstanceState(@NonNull Bundle outState) { - outState.putString("waveBtnActive", String.valueOf(waveBtnActive)); - outState.putString("pwmBtnActive", String.valueOf(pwmBtnActive)); - outState.putString("prop_active", String.valueOf(prop_active)); - outState.putString("digital_mode", String.valueOf(digital_mode)); - super.onSaveInstanceState(outState); - } - - /** - * Click listeners to increment and decrement buttons - * - * @param up increment button - * @param down decrement button - */ - private void monitorVariations(ImageButton up, ImageButton down) { - up.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - incProgressSeekBar(); - } - }); - up.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(final View view) { - fastCounter(true); - return true; - } - }); - down.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - decProgressSeekBar(); - } - }); - down.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(final View view) { - fastCounter(false); - return true; - } - }); - } - - /** - * Handles action when user releases long click on an increment or a decrement button - * - * @param up increment button - * @param down decrement button - */ - @SuppressLint("ClickableViewAccessibility") - private void monitorLongClicks(ImageButton up, ImageButton down) { - up.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View view, MotionEvent motionEvent) { - view.onTouchEvent(motionEvent); - if (motionEvent.getAction() == MotionEvent.ACTION_UP) { - stopCounter(); - } - return true; - } - }); - down.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View view, MotionEvent motionEvent) { - view.onTouchEvent(motionEvent); - if (motionEvent.getAction() == MotionEvent.ACTION_UP) { - stopCounter(); - } - return true; - } - }); - } - - /** - * Stops the Timer that is changing the seekbar value - */ - private void stopCounter() { - if (waveGenCounter != null) { - waveGenCounter.cancel(); - waveGenCounter.purge(); - } - } - - /** - * TimerTask implementation to increment or decrement value at the seekbar at a constant - * rate provided by LONG_CLICK_DELAY - * - * @param increaseValue flag for whether it is increase or decrease - */ - private void fastCounter(final boolean increaseValue) { - waveGenCounter = new Timer(); - TimerTask task = new TimerTask() { - public void run() { - wavegenHandler.post(new Runnable() { - public void run() { - if (increaseValue) { - incProgressSeekBar(); - } else { - decProgressSeekBar(); - } - } - }); - } - }; - waveGenCounter.schedule(task, 1, LONG_CLICK_DELAY); - } - - private AlertDialog createIntentDialog() { - AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); - LayoutInflater inflater = this.getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.wavegen_intent_dialog, null); - dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - waveDialog.cancel(); - } - }).setTitle(R.string.open_instrument); - - dialogView.findViewById(R.id.osc_btn).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(WaveGeneratorActivity.this, OscilloscopeActivity.class)); - waveDialog.cancel(); - } - }); - - dialogView.findViewById(R.id.la_btn).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(WaveGeneratorActivity.this, LogicalAnalyzerActivity.class)); - waveDialog.cancel(); - } - }); - - dialogBuilder.setView(dialogView); - return dialogBuilder.create(); - } - - private int dpToPx(int dp) { - DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics(); - return Math.round((float) dp * (displayMetrics.xdpi / 160.0F)); - } - - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((WaveGeneratorData) sensorData); - realm.commitTransaction(); - } - - public enum WaveConst {WAVETYPE, WAVE1, WAVE2, SQR1, SQR2, SQR3, SQR4, FREQUENCY, PHASE, DUTY, SQUARE, PWM} - - public enum WaveData { - FREQ_MIN(10), DUTY_MIN(0), PHASE_MIN(0), FREQ_MAX(5000), PHASE_MAX(360), DUTY_MAX(100); - - public final int value; - - WaveData(final int v) { - value = v; - } - - public final int getValue() { - return value; - } - } - - private class ProduceSoundTask extends AsyncTask { - - @Override - protected Void doInBackground(Void... voids) { - short[] buffer = new short[1024]; - track = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffer.length, AudioTrack.MODE_STREAM); - float angle = 0; - float[] samples = new float[1024]; - - track.play(); - double frequency; - while (isPlayingSound) { - if (WaveGeneratorConstants.mode_selected == WaveConst.SQUARE) { - frequency = WaveGeneratorConstants.wave.get(waveBtnActive).get(WaveConst.FREQUENCY); - } else { - frequency = WaveGeneratorConstants.wave.get(WaveConst.SQR1).get(WaveConst.FREQUENCY); - } - float increment = (float) ((2 * Math.PI) * frequency / 44100); - for (int i = 0; i < samples.length; i++) { - samples[i] = (float) Math.sin(angle); - if (WaveGeneratorConstants.mode_selected == WaveConst.PWM) { - samples[i] = (samples[i] >= 0.0) ? 1 : -1; - } else { - if (WaveGeneratorConstants.wave.get(waveBtnActive).get(WaveConst.WAVETYPE) == 2) { - samples[i] = (float) ((2 / Math.PI) * Math.asin(samples[i])); - } - } - buffer[i] = (short) (samples[i] * Short.MAX_VALUE); - angle += increment; - } - track.write(buffer, 0, buffer.length); - } - return null; - } - - @Override - protected void onCancelled() { - super.onCancelled(); - if (track != null) { - track.flush(); - track.stop(); - track.release(); - } - } - } - - @Override - public void onBackPressed() { - super.onBackPressed(); - if (produceSoundTask != null) - produceSoundTask.cancel(true); - produceSoundTask = null; - isPlayingSound = false; - } -} diff --git a/app/src/main/java/io/pslab/activity/guide/GuideActivity.java b/app/src/main/java/io/pslab/activity/guide/GuideActivity.java deleted file mode 100644 index 181296207..000000000 --- a/app/src/main/java/io/pslab/activity/guide/GuideActivity.java +++ /dev/null @@ -1,133 +0,0 @@ -package io.pslab.activity.guide; - -import android.annotation.SuppressLint; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.os.Handler; -import android.view.GestureDetector; -import android.view.MotionEvent; -import android.view.View; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; - -import com.google.android.material.bottomsheet.BottomSheetBehavior; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.pslab.R; -import io.pslab.others.MathUtils; -import io.pslab.others.SwipeGestureDetector; - -/** - * Base class for activities which have a guide. - */ -public class GuideActivity extends AppCompatActivity { - - public static final String PREFS_NAME = "customDialogPreference"; - - @BindView(R.id.bottom_sheet) - LinearLayout bottomSheet; - @BindView(R.id.shadow) - View shadowLayer; - @BindView(R.id.img_arrow) - ImageView arrowUpDown; - @BindView(R.id.sheet_slide_text) - TextView bottomSheetSlideText; - - BottomSheetBehavior bottomSheetBehavior; - GestureDetector gestureDetector; - - public GuideActivity(@LayoutRes int contentLayoutId) { - super(contentLayoutId); - } - - @SuppressLint("ClickableViewAccessibility") - @Override - protected void onCreate(final Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ButterKnife.bind(this); - - setUpBottomSheet(); - shadowLayer.setOnClickListener(v -> { - if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) - bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); - shadowLayer.setVisibility(View.GONE); - }); - shadowLayer.setVisibility(View.GONE); - } - - private void setUpBottomSheet() { - bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet); - - final SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, MODE_PRIVATE); - final boolean isFirstTime = settings.getBoolean("WaveGenFirstTime", true); - - if (isFirstTime) { - bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); - shadowLayer.setVisibility(View.VISIBLE); - shadowLayer.setAlpha(0.8f); - arrowUpDown.setRotation(180); - bottomSheetSlideText.setText(R.string.hide_guide_text); - SharedPreferences.Editor editor = settings.edit(); - editor.putBoolean("WaveGenFirstTime", false); - editor.apply(); - } else { - bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); - } - - bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { - private final Handler handler = new Handler(); - private final Runnable runnable = new Runnable() { - @Override - public void run() { - bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); - } - }; - - @Override - public void onStateChanged(@NonNull final View bottomSheet, int newState) { - switch (newState) { - case BottomSheetBehavior.STATE_EXPANDED: - handler.removeCallbacks(runnable); - bottomSheetSlideText.setText(R.string.hide_guide_text); - break; - - case BottomSheetBehavior.STATE_COLLAPSED: - handler.postDelayed(runnable, 2000); - break; - - default: - handler.removeCallbacks(runnable); - bottomSheetSlideText.setText(R.string.show_guide_text); - break; - } - } - - @Override - public void onSlide(@NonNull final View bottomSheet, float slideOffset) { - float value = (float) MathUtils.map(slideOffset, 0.0, 1.0, 0.0, 0.8); - shadowLayer.setVisibility(value <= 0.0 ? View.GONE : View.VISIBLE); - shadowLayer.setAlpha(value); - arrowUpDown.setRotation(slideOffset * 180); - } - }); - gestureDetector = new GestureDetector(this, new SwipeGestureDetector(bottomSheetBehavior)); - } - - @Override - public boolean onTouchEvent(final MotionEvent event) { - gestureDetector.onTouchEvent(event); //Gesture detector need this to transfer touch event to the gesture detector. - return super.onTouchEvent(event); - } - - protected void toggleGuide() { - bottomSheetBehavior.setState(bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_HIDDEN ? - BottomSheetBehavior.STATE_EXPANDED : BottomSheetBehavior.STATE_HIDDEN); - } - -} diff --git a/app/src/main/java/io/pslab/adapters/ApplicationAdapter.java b/app/src/main/java/io/pslab/adapters/ApplicationAdapter.java deleted file mode 100644 index 0e7cf1765..000000000 --- a/app/src/main/java/io/pslab/adapters/ApplicationAdapter.java +++ /dev/null @@ -1,82 +0,0 @@ -package io.pslab.adapters; - -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatDelegate; -import androidx.recyclerview.widget.RecyclerView; - -import java.util.List; - -import io.pslab.R; -import io.pslab.items.ApplicationItem; - - -public class ApplicationAdapter extends RecyclerView.Adapter { - - private final List applicationList; - private final OnItemClickListener listener; - - - static { - AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); - } - - /** - * View holder for application list item - */ - public static class Holder extends RecyclerView.ViewHolder { - - private final TextView header; - private final TextView description; - private final ImageView applicationIcon; - - public Holder(@NonNull final View itemView) { - super(itemView); - this.header = itemView.findViewById(R.id.heading_card); - this.description = itemView.findViewById(R.id.description_card); - this.applicationIcon = itemView.findViewById(R.id.application_icon); - } - - public void setup(@NonNull final ApplicationItem applicationItem, @NonNull final OnItemClickListener listener) { - header.setText(applicationItem.getApplicationName()); - description.setText(applicationItem.getApplicationDescription()); - applicationIcon.setLayerType(View.LAYER_TYPE_SOFTWARE, null); - applicationIcon.setImageResource(applicationItem.getApplicationIcon()); - - itemView.setOnClickListener(v -> listener.onItemClick(applicationItem)); - } - } - - public ApplicationAdapter(@NonNull final List applicationList, @NonNull final OnItemClickListener listener) { - this.applicationList = applicationList; - this.listener = listener; - } - - @NonNull - @Override - public Holder onCreateViewHolder(@NonNull final ViewGroup parent, int viewType) { - View itemView = LayoutInflater.from(parent.getContext()) - .inflate(R.layout.application_list_item, parent, false); - return new Holder(itemView); - } - - @Override - public void onBindViewHolder(@NonNull final Holder holder, int position) { - holder.setup(applicationList.get(position), listener); - } - - @Override - public int getItemCount() { - return applicationList.size(); - } - - public interface OnItemClickListener { - void onItemClick(ApplicationItem item); - } - -} diff --git a/app/src/main/java/io/pslab/adapters/CheckBoxAdapter.java b/app/src/main/java/io/pslab/adapters/CheckBoxAdapter.java deleted file mode 100644 index b2290f5be..000000000 --- a/app/src/main/java/io/pslab/adapters/CheckBoxAdapter.java +++ /dev/null @@ -1,75 +0,0 @@ -package io.pslab.adapters; - -import android.content.Context; -import androidx.recyclerview.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.CheckBox; -import android.widget.TextView; - -import java.util.ArrayList; -import java.util.List; - -import io.pslab.CheckBoxGetter; -import io.pslab.R; - - -public class CheckBoxAdapter extends RecyclerView.Adapter { - - private Context boxcontext; - private List list = new ArrayList<>(); - - public CheckBoxAdapter(Context boxcontext, List list) { - this.boxcontext = boxcontext; - this.list = list; - } - - @Override - public CheckBoxHolder onCreateViewHolder(ViewGroup parent, int viewType) { - - View view = LayoutInflater.from(boxcontext).inflate(R.layout.item_checkbox, parent, false); - return new CheckBoxHolder(view); - } - - @Override - public void onBindViewHolder(final CheckBoxHolder holder, final int position) { - - final CheckBoxGetter check = list.get(position); - - holder.tv_name.setText(check.getName()); - - holder.checkBox.setChecked(check.isSelected()); - holder.checkBox.setTag(list.get(position)); - - holder.checkBox.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - CheckBoxGetter check1 = (CheckBoxGetter) holder.checkBox.getTag(); - check1.setSelected(holder.checkBox.isChecked()); - list.get(position).setSelected(holder.checkBox.isChecked()); - } - }); - } - - @Override - public int getItemCount() { - return list.size(); - } - - public List getCheckList() { - return list; - } - - public static class CheckBoxHolder extends RecyclerView.ViewHolder { - - private TextView tv_name; - private CheckBox checkBox; - - public CheckBoxHolder(View itemView) { - super(itemView); - tv_name = itemView.findViewById(R.id.tv_checkbox); - checkBox = itemView.findViewById(R.id.checkBox_select); - } - } -} diff --git a/app/src/main/java/io/pslab/adapters/ControlMainAdapter.java b/app/src/main/java/io/pslab/adapters/ControlMainAdapter.java deleted file mode 100644 index c658a55a6..000000000 --- a/app/src/main/java/io/pslab/adapters/ControlMainAdapter.java +++ /dev/null @@ -1,985 +0,0 @@ -package io.pslab.adapters; - -import android.graphics.Color; -import android.text.Editable; -import android.text.TextWatcher; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.EditText; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.cardview.widget.CardView; -import androidx.recyclerview.widget.RecyclerView; - -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.others.ScienceLabCommon; -import static io.pslab.others.MathUtils.map; - -import java.text.DecimalFormat; -import io.pslab.DataFormatter; -import static io.pslab.others.MathUtils.map; - -public class ControlMainAdapter extends RecyclerView.Adapter { - - private String[] mDataset; - private ScienceLab scienceLab = ScienceLabCommon.scienceLab; - private boolean manualSeekBarChange = false; - - private boolean isSet1 = false; - private boolean isSet2 = false; - private boolean isSet3 = false; - private boolean isSet4 = false; - private boolean isSet5 = false; - private boolean isSet6 = false; - private boolean isSet7 = false; - - static class ViewHolder extends RecyclerView.ViewHolder { - - CardView mCardView; - TextView tvControlMain1; - TextView tvControlMain2; - EditText editTextControlMain; - Button buttonControlMain1; - Button buttonControlMain2; - Button buttonControlMain3; - SeekBar seekBarControlMain; - - public ViewHolder(View view) { - super(view); - mCardView = view.findViewById(R.id.cardview_control_main); - tvControlMain1 = view.findViewById(R.id.tv_control_main1); - tvControlMain2 = view.findViewById(R.id.tv_control_main2); - editTextControlMain = view.findViewById(R.id.edittext_control_main); - buttonControlMain1 = view.findViewById(R.id.button_control_main1); - buttonControlMain2 = view.findViewById(R.id.button_control_main2); - buttonControlMain3 = view.findViewById(R.id.button_control_main3); - seekBarControlMain = view.findViewById(R.id.seekbar_control_main); - editTextControlMain.setText("0"); - } - - } - - public ControlMainAdapter(String[] myDataset) { - mDataset = myDataset; - } - - @Override - public ControlMainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.control_main_list_item, parent, false); - return new ViewHolder(v); - } - - @Override - public void onBindViewHolder(final ViewHolder holder, final int position) { - holder.setIsRecyclable(true); - holder.tvControlMain1.setText(mDataset[position]); - - final Button buttonControlMain1 = holder.buttonControlMain1; - final Button buttonControlMain2 = holder.buttonControlMain2; - final Button buttonControlMain3 = holder.buttonControlMain3; - - final SeekBar seekBarControlMain = holder.seekBarControlMain; - final EditText editTextControlMain = holder.editTextControlMain; - - switch (position) { - case 0: - buttonControlMain1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet1) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet1 = false; - } - Double data = Double.parseDouble(editTextControlMain.getText().toString()); - Double dataDecrement = data - 0.0025; - if (dataDecrement < -5.0) - dataDecrement = -5.0; - else if (dataDecrement > 5.0) - dataDecrement = 5.0; - int setProgress = (int) ((dataDecrement + 5) * 100); - manualSeekBarChange = true; - seekBarControlMain.setProgress(setProgress); - manualSeekBarChange = false; - editTextControlMain.setText(DataFormatter.formatDouble(dataDecrement, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } catch (NumberFormatException e) { - editTextControlMain.setText(DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - }); - - buttonControlMain2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet1) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet1 = false; - } - Double data1 = Double.parseDouble(editTextControlMain.getText().toString()); - Double dataIncrement = data1 + 0.0025; - if (dataIncrement < -5.0) - dataIncrement = -5.0; - else if (dataIncrement > 5.0) - dataIncrement = 5.0; - int setProgress = (int) ((dataIncrement + 5) * 100); - manualSeekBarChange = true; - seekBarControlMain.setProgress(setProgress); - manualSeekBarChange = false; - editTextControlMain.setText(DataFormatter.formatDouble(dataIncrement, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } catch (NumberFormatException e) { - DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT); - } - } - }); - - buttonControlMain3.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - Float value = Float.parseFloat(editTextControlMain.getText().toString()); - if (value > 5) - value = 5f; - else if (value < -5) - value = -5f; - editTextControlMain.setText(DataFormatter.formatDouble(value, DataFormatter.MEDIUM_PRECISION_FORMAT)); - manualSeekBarChange = true; - seekBarControlMain.setProgress((int) map(value, -5, 5, 0, 1000)); - manualSeekBarChange = false; - if (scienceLab.isConnected()) { - scienceLab.setPV1(value); - if (!isSet1) { - buttonControlMain3.setBackgroundColor(Color.GREEN); - isSet1 = true; - } - } - } catch (NumberFormatException e) { - editTextControlMain.setText(DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - - } - }); - //Text focus listener to figure out if the value has changed. Change color of SET button - editTextControlMain.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { - if (isSet1) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet1 = false; - } - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - seekBarControlMain.setMax(1000); - editTextControlMain.setText(DataFormatter.formatDouble(-5f, DataFormatter.MEDIUM_PRECISION_FORMAT)); - - - seekBarControlMain.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (!manualSeekBarChange) { - double text = map(progress, 0, 1000, -5.0, 5.0); - DecimalFormat df = new DecimalFormat("0.0000"); - editTextControlMain.setText( - DataFormatter.formatDouble(text, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - if (isSet1) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet1 = false; - } - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - - break; - - case 1: - buttonControlMain1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet2) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet2 = false; - } - Double data = Double.parseDouble(editTextControlMain.getText().toString()); - Double dataDecrement = data - 0.0025; - if (dataDecrement < -3.3) - dataDecrement = -3.3; - else if (dataDecrement > 3.3) - dataDecrement = 3.3; - int setProgress = (int) ((dataDecrement + 3.3) * 100); - manualSeekBarChange = true; - seekBarControlMain.setProgress(setProgress); - manualSeekBarChange = false; - editTextControlMain.setText(DataFormatter.formatDouble(dataDecrement, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } catch (NumberFormatException e) { - editTextControlMain.setText("0"); - } - } - }); - - buttonControlMain2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet2) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet2 = false; - } - Double data1 = Double.parseDouble(editTextControlMain.getText().toString()); - Double dataIncrement = data1 + 0.0025; - if (dataIncrement < -3.3) - dataIncrement = -3.3; - else if (dataIncrement > 3.3) - dataIncrement = 3.3; - int setProgress = (int) ((dataIncrement + 3.3) * 100); - manualSeekBarChange = true; - seekBarControlMain.setProgress(setProgress); - manualSeekBarChange = false; - editTextControlMain.setText(DataFormatter.formatDouble(dataIncrement, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } catch (NumberFormatException e) { - editTextControlMain.setText(DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - }); - - buttonControlMain3.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - Float value = Float.parseFloat(editTextControlMain.getText().toString()); - if (value > 3.3) - value = 3.3f; - else if (value < -3.3) - value = -3.3f; - editTextControlMain.setText(DataFormatter.formatDouble(value, DataFormatter.MEDIUM_PRECISION_FORMAT)); - manualSeekBarChange = true; - seekBarControlMain.setProgress((int) ((value + 3.3) * 100)); - manualSeekBarChange = false; - if (scienceLab.isConnected()) { - scienceLab.setPV2(value); - if (!isSet2) { - buttonControlMain3.setBackgroundColor(Color.GREEN); - isSet2 = true; - } - } - } catch (NumberFormatException e) { - editTextControlMain.setText(DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - }); - - //Text focus listener to figure out if the value has changed. Change color of SET button - editTextControlMain.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { - if (isSet2) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet2 = false; - } - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - seekBarControlMain.setMax(660); - editTextControlMain.setText(DataFormatter.formatDouble(-3.3, DataFormatter.MEDIUM_PRECISION_FORMAT)); - - seekBarControlMain.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (!manualSeekBarChange) { - double text = map(progress, 0, 660, -3.3, 3.3); - editTextControlMain.setText(DataFormatter.formatDouble(text, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - if (isSet2) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet2 = false; - } - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - break; - - case 2: - buttonControlMain1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet3) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet3 = false; - } - Double data = Double.parseDouble(editTextControlMain.getText().toString()); - Double dataDecrement = data - 0.0025; - if (dataDecrement < 0.0) - dataDecrement = 0.0; - else if (dataDecrement > 3.3) - dataDecrement = 3.3; - manualSeekBarChange = true; - seekBarControlMain.setProgress((int) (dataDecrement * 100)); - manualSeekBarChange = false; - editTextControlMain.setText(DataFormatter.formatDouble(dataDecrement, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } catch (NumberFormatException e) { - editTextControlMain.setText(DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - }); - - buttonControlMain2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet3) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet3 = false; - } - Double data1 = Double.parseDouble(editTextControlMain.getText().toString()); - Double dataIncrement = data1 + 0.0025; - if (dataIncrement < 0.0) - dataIncrement = 0.0; - else if (dataIncrement > 3.3) - dataIncrement = 3.3; - manualSeekBarChange = true; - seekBarControlMain.setProgress((int) (dataIncrement * 100)); - manualSeekBarChange = false; - editTextControlMain.setText(DataFormatter.formatDouble(dataIncrement, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } catch (NumberFormatException e) { - editTextControlMain.setText(DataFormatter.formatDouble(0f, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - }); - - buttonControlMain3.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - Float value = Float.parseFloat(editTextControlMain.getText().toString()); - if (value > 3.3) - value = 3.3f; - else if (value < 0) - value = 0f; - editTextControlMain.setText(DataFormatter.formatDouble(value, DataFormatter.MEDIUM_PRECISION_FORMAT)); - manualSeekBarChange = true; - seekBarControlMain.setProgress((int) map(value, 0, 3.3, 0, 330)); - manualSeekBarChange = false; - if (scienceLab.isConnected()) { - scienceLab.setPV3(value); - if (!isSet3) { - buttonControlMain3.setBackgroundColor(Color.GREEN); - isSet3 = true; - } - } - } catch (NumberFormatException e) { - editTextControlMain.setText(DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - - } - }); - - //Text focus listener to figure out if the value has changed. Change color of SET button - editTextControlMain.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { - if (isSet3) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet3 = false; - } - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - seekBarControlMain.setMax(330); - editTextControlMain.setText(DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT)); - - - seekBarControlMain.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (!manualSeekBarChange) { - double text = map(progress, 0, 330, 0, 3.3); - editTextControlMain.setText(DataFormatter.formatDouble(text, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - if (isSet3) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet3 = false; - } - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - - break; - - case 3: - buttonControlMain1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet4) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet4 = false; - } - Double data = Double.parseDouble(editTextControlMain.getText().toString()); - Double dataDecrement = data - 0.0025; - if (dataDecrement < 0.0) - dataDecrement = 0.0; - else if (dataDecrement > 3.3) - dataDecrement = 3.3; - manualSeekBarChange = true; - seekBarControlMain.setProgress((int) (dataDecrement * 100)); - manualSeekBarChange = false; - editTextControlMain.setText(DataFormatter.formatDouble(dataDecrement, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } catch (NumberFormatException e) { - editTextControlMain.setText(DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - }); - - buttonControlMain2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet4) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet4 = false; - } - Double data1 = Double.parseDouble(editTextControlMain.getText().toString()); - Double dataIncrement = data1 + 0.0025; - if (dataIncrement < 0.0) - dataIncrement = 0.0; - else if (dataIncrement > 3.3) - dataIncrement = 3.3; - manualSeekBarChange = true; - seekBarControlMain.setProgress((int) (dataIncrement * 100)); - manualSeekBarChange = false; - editTextControlMain.setText(DataFormatter.formatDouble(dataIncrement, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } catch (NumberFormatException e) { - editTextControlMain.setText(DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - }); - - buttonControlMain3.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - Float value = Float.parseFloat(editTextControlMain.getText().toString()); - if (value > 3.3) - value = 3.3f; - else if (value < 0) - value = 0f; - editTextControlMain.setText(DataFormatter.formatDouble(value, DataFormatter.MEDIUM_PRECISION_FORMAT)); - manualSeekBarChange = true; - seekBarControlMain.setProgress((int) (value * 100)); - manualSeekBarChange = false; - if (scienceLab.isConnected()) { - scienceLab.setPCS(value); - if (!isSet4) { - buttonControlMain3.setBackgroundColor(Color.GREEN); - isSet4 = true; - } - } - } catch (NumberFormatException e) { - editTextControlMain.setText(DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - }); - - //Text focus listener to figure out if the value has changed. Change color of SET button - editTextControlMain.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { - if (isSet4) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet4 = false; - } - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - seekBarControlMain.setMax(330); - DataFormatter.formatDouble(0, DataFormatter.MEDIUM_PRECISION_FORMAT); - - seekBarControlMain.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (!manualSeekBarChange) { - double text = map(progress, 0, 330, 0.0, 3.3); - editTextControlMain.setText(DataFormatter.formatDouble(text, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - if (isSet4) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet4 = false; - } - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - break; - - case 4: - buttonControlMain1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet5) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet5 = false; - } - int data = Integer.parseInt(editTextControlMain.getText().toString()); - int dataDecrement = data - 1; - if (dataDecrement < 10) - dataDecrement = 10; - else if (dataDecrement > 5000) - dataDecrement = 5000; - manualSeekBarChange = true; - seekBarControlMain.setProgress(dataDecrement - 10); - manualSeekBarChange = false; - DecimalFormat df = new DecimalFormat("####"); - editTextControlMain.setText(df.format(dataDecrement)); - } catch (NumberFormatException e) { - editTextControlMain.setText("0"); - } - } - }); - - buttonControlMain2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet5) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet5 = false; - } - int data1 = Integer.parseInt(editTextControlMain.getText().toString()); - int dataIncrement = data1 + 1; - if (dataIncrement < 10) - dataIncrement = 10; - else if (dataIncrement > 5000) - dataIncrement = 5000; - manualSeekBarChange = true; - seekBarControlMain.setProgress(dataIncrement - 10); - manualSeekBarChange = false; - DecimalFormat df = new DecimalFormat("####"); - editTextControlMain.setText(df.format(dataIncrement)); - } catch (NumberFormatException e) { - editTextControlMain.setText("0"); - } - } - }); - - buttonControlMain3.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - int value = Integer.parseInt(editTextControlMain.getText().toString()); - if (value < 10) - value = 10; - else if (value > 5000) - value = 5000; - editTextControlMain.setText(String.valueOf(value)); - manualSeekBarChange = true; - seekBarControlMain.setProgress(value - 10); - manualSeekBarChange = false; - if (scienceLab.isConnected()) { - scienceLab.setSine1(value); - if (!isSet5) { - buttonControlMain3.setBackgroundColor(Color.GREEN); - isSet5 = true; - } - } - } catch (NumberFormatException e) { - editTextControlMain.setText("0"); - } - } - }); - - //Text focus listener to figure out if the value has changed. Change color of SET button - editTextControlMain.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { - if (isSet5) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet5 = false; - } - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - seekBarControlMain.setMax(4990); - editTextControlMain.setText("10"); - - seekBarControlMain.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (!manualSeekBarChange) { - int frequency = (int) map(progress, 0, 4990, 10, 5000); - DecimalFormat df = new DecimalFormat("####"); - editTextControlMain.setText(df.format(frequency)); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - if (isSet5) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet5 = false; - } - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - break; - - case 5: - buttonControlMain1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet6) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet6 = false; - } - int data = Integer.parseInt(editTextControlMain.getText().toString()); - int dataDecrement = data - 1; - if (dataDecrement < 10) - dataDecrement = 10; - else if (dataDecrement > 5000) - dataDecrement = 5000; - manualSeekBarChange = true; - seekBarControlMain.setProgress(dataDecrement - 10); - manualSeekBarChange = false; - DecimalFormat df = new DecimalFormat("####"); - editTextControlMain.setText(df.format(dataDecrement)); - } catch (NumberFormatException e) { - editTextControlMain.setText("0"); - } - } - }); - - buttonControlMain2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet6) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet6 = false; - } - int data1 = Integer.parseInt(editTextControlMain.getText().toString()); - int dataIncrement = data1 + 1; - if (dataIncrement < 10) - dataIncrement = 10; - else if (dataIncrement > 5000) - dataIncrement = 5000; - manualSeekBarChange = true; - seekBarControlMain.setProgress(dataIncrement - 10); - manualSeekBarChange = false; - DecimalFormat df = new DecimalFormat("####"); - editTextControlMain.setText(df.format(dataIncrement)); - } catch (NumberFormatException e) { - editTextControlMain.setText("0"); - } - } - }); - - buttonControlMain3.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - int value = Integer.parseInt(editTextControlMain.getText().toString()); - if (value < 10) - value = 10; - else if (value > 5000) - value = 5000; - editTextControlMain.setText(String.valueOf(value)); - manualSeekBarChange = true; - seekBarControlMain.setProgress(value - 10); - manualSeekBarChange = false; - if (scienceLab.isConnected()) { - scienceLab.setSine2(value); - if (!isSet6) { - buttonControlMain3.setBackgroundColor(Color.GREEN); - isSet6 = true; - } - } - } catch (NumberFormatException e) { - editTextControlMain.setText("0"); - } - } - }); - - //Text focus listener to figure out if the value has changed. Change color of SET button - editTextControlMain.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { - if (isSet6) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet6 = false; - } - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - seekBarControlMain.setMax(4990); - editTextControlMain.setText("10"); - seekBarControlMain.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (!manualSeekBarChange) { - int frequency = (int) map(progress, 0, 4990, 10, 5000); - DecimalFormat df = new DecimalFormat("####"); - editTextControlMain.setText(df.format(frequency)); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - if (isSet6) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet6 = false; - } - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - break; - - case 6: - buttonControlMain1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet7) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet7 = false; - } - int data = Integer.parseInt(editTextControlMain.getText().toString()); - int dataDecrement = data - 1; - if (dataDecrement < 10) - dataDecrement = 10; - else if (dataDecrement > 5000) - dataDecrement = 5000; - manualSeekBarChange = true; - seekBarControlMain.setProgress(dataDecrement - 10); - manualSeekBarChange = false; - DecimalFormat df = new DecimalFormat("####"); - editTextControlMain.setText(df.format(dataDecrement)); - } catch (NumberFormatException e) { - editTextControlMain.setText("0"); - } - } - }); - - buttonControlMain2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - if (isSet7) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet7 = false; - } - int data1 = Integer.parseInt(editTextControlMain.getText().toString()); - int dataIncrement = data1 + 1; - if (dataIncrement < 10) - dataIncrement = 10; - else if (dataIncrement > 5000) - dataIncrement = 5000; - manualSeekBarChange = true; - seekBarControlMain.setProgress(dataIncrement - 10); - manualSeekBarChange = false; - DecimalFormat df = new DecimalFormat("####"); - editTextControlMain.setText(df.format(dataIncrement)); - } catch (NumberFormatException e) { - editTextControlMain.setText("0"); - } - } - }); - - buttonControlMain3.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - int value = Integer.parseInt(editTextControlMain.getText().toString()); - if (value < 10) - value = 10; - else if (value > 5000) - value = 5000; - editTextControlMain.setText(String.valueOf(value)); - manualSeekBarChange = true; - seekBarControlMain.setProgress(value - 10); - manualSeekBarChange = false; - // Setting a SQUARE Wave in SQR1 by default - if (scienceLab.isConnected()) { - scienceLab.setSqr1(value, -1, false); - if (!isSet7) { - buttonControlMain3.setBackgroundColor(Color.GREEN); - isSet7 = true; - } - } - } catch (NumberFormatException e) { - editTextControlMain.setText("0"); - } - } - }); - - //Text focus listener to figure out if the value has changed. Change color of SET button - editTextControlMain.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { - if (isSet7) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet7 = false; - } - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - seekBarControlMain.setMax(5000); - editTextControlMain.setText("10"); - seekBarControlMain.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (!manualSeekBarChange) { - int frequency = (int) map(progress, 0, 4990, 10, 5000); - DecimalFormat df = new DecimalFormat("####"); - editTextControlMain.setText(df.format(frequency)); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - if (isSet7) { - buttonControlMain3.setBackgroundColor(Color.parseColor("#c72c2c")); - isSet7 = false; - } - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - break; - } - - } - - - @Override - public int getItemCount() { - return mDataset.length; - } - -} diff --git a/app/src/main/java/io/pslab/adapters/MPUDataAdapter.java b/app/src/main/java/io/pslab/adapters/MPUDataAdapter.java deleted file mode 100644 index d22cfe3c5..000000000 --- a/app/src/main/java/io/pslab/adapters/MPUDataAdapter.java +++ /dev/null @@ -1,70 +0,0 @@ -package io.pslab.adapters; - -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import androidx.recyclerview.widget.RecyclerView; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.models.DataMPU6050; -import io.realm.RealmResults; - -/** - * Created by viveksb007 on 13/8/17. - */ - -public class MPUDataAdapter extends RecyclerView.Adapter { - - private RealmResults results; - - public MPUDataAdapter(RealmResults results) { - this.results = results; - } - - @Override - public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.sensor_mpu6050_data_card, parent, false); - return new ViewHolder(itemView); - } - - @Override - public void onBindViewHolder(ViewHolder holder, int position) { - DataMPU6050 temp = results.get(position); - if (temp != null) { - holder.tvAx.setText(DataFormatter.formatDouble(temp.getAx(), DataFormatter.LOW_PRECISION_FORMAT)); - holder.tvAy.setText(DataFormatter.formatDouble(temp.getAy(), DataFormatter.LOW_PRECISION_FORMAT)); - holder.tvAz.setText(DataFormatter.formatDouble(temp.getAz(), DataFormatter.LOW_PRECISION_FORMAT)); - holder.tvGx.setText(DataFormatter.formatDouble(temp.getGx(), DataFormatter.LOW_PRECISION_FORMAT)); - holder.tvGy.setText(DataFormatter.formatDouble(temp.getGy(), DataFormatter.LOW_PRECISION_FORMAT)); - holder.tvGz.setText(DataFormatter.formatDouble(temp.getGz(), DataFormatter.LOW_PRECISION_FORMAT)); - holder.tvTemperature.setText(DataFormatter.formatDouble(temp.getTemperature(), DataFormatter.LOW_PRECISION_FORMAT)); - holder.tvTitle.setText("Raw Data #" + (position + 1)); - } - } - - @Override - public int getItemCount() { - return results.size(); - } - - public class ViewHolder extends RecyclerView.ViewHolder { - - private TextView tvAx, tvAy, tvAz, tvGx, tvGy, tvGz, tvTemperature, tvTitle; - - ViewHolder(View itemView) { - super(itemView); - tvAx = itemView.findViewById(R.id.tv_sensor_mpu6050_ax); - tvAy = itemView.findViewById(R.id.tv_sensor_mpu6050_ay); - tvAz = itemView.findViewById(R.id.tv_sensor_mpu6050_az); - tvTemperature = itemView.findViewById(R.id.tv_sensor_mpu6050_temp); - tvGx = itemView.findViewById(R.id.tv_sensor_mpu6050_gx); - tvGy = itemView.findViewById(R.id.tv_sensor_mpu6050_gy); - tvGz = itemView.findViewById(R.id.tv_sensor_mpu6050_gz); - tvTitle = itemView.findViewById(R.id.card_title); - } - } - -} diff --git a/app/src/main/java/io/pslab/adapters/OscilloscopeMeasurementsAdapter.java b/app/src/main/java/io/pslab/adapters/OscilloscopeMeasurementsAdapter.java deleted file mode 100644 index f79acaa46..000000000 --- a/app/src/main/java/io/pslab/adapters/OscilloscopeMeasurementsAdapter.java +++ /dev/null @@ -1,77 +0,0 @@ -package io.pslab.adapters; - -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; - -import java.math.RoundingMode; -import java.text.DecimalFormat; - -import io.pslab.R; -import io.pslab.activity.OscilloscopeActivity.ChannelMeasurements; -import io.pslab.activity.OscilloscopeActivity.CHANNEL; -import io.pslab.others.OscilloscopeMeasurements; - -public class OscilloscopeMeasurementsAdapter extends RecyclerView.Adapter { - - private final String[] channels; - private final Integer[] channelColors; - - public static class ViewHolder extends RecyclerView.ViewHolder { - - private final TextView measurementsView; - - public ViewHolder(@NonNull View itemView) { - super(itemView); - this.measurementsView = itemView.findViewById(R.id.textview_measurements); - } - - public void setMeasurements(@NonNull String channelString, @NonNull Integer channelColor) { - CHANNEL channel = CHANNEL.valueOf(channelString); - double frequency = OscilloscopeMeasurements.channel.get(channel).get(ChannelMeasurements.FREQUENCY); - double amplitude = OscilloscopeMeasurements.channel.get(channel).get(ChannelMeasurements.AMPLITUDE); - double period = OscilloscopeMeasurements.channel.get(channel).get(ChannelMeasurements.PERIOD); - double positivePeak = OscilloscopeMeasurements.channel.get(channel).get(ChannelMeasurements.POSITIVE_PEAK); - double negativePeak = OscilloscopeMeasurements.channel.get(channel).get(ChannelMeasurements.NEGATIVE_PEAK); - DecimalFormat df = new DecimalFormat("#.##"); - df.setRoundingMode(RoundingMode.CEILING); - if (frequency >= 1000) { - frequency /= 1000; - String string = "Vpp: " + df.format(amplitude) + " V\nVp+: " + df.format(positivePeak) + " V Vp-: " + df.format(negativePeak) + " V\nf: " + df.format(frequency) + " kHz P: " + df.format(period) + " ms"; - measurementsView.setTextColor(channelColor); - measurementsView.setText(string); - } else { - String string = "Vpp: " + df.format(amplitude) + " V\nVp+: " + df.format(positivePeak) + " V Vp-: " + df.format(negativePeak) + " V\nf: " + df.format(frequency) + " Hz P: " + df.format(period) + " ms"; - measurementsView.setTextColor(channelColor); - measurementsView.setText(string); - } - } - } - - public OscilloscopeMeasurementsAdapter(@NonNull String[] channels, @NonNull Integer[] channelColors) { - this.channels = channels; - this.channelColors = channelColors; - } - - @NonNull - @Override - public OscilloscopeMeasurementsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - View itemView = LayoutInflater.from(parent.getContext()) - .inflate(R.layout.measurement_item, parent, false); - return new ViewHolder(itemView); - } - - @Override - public void onBindViewHolder(@NonNull OscilloscopeMeasurementsAdapter.ViewHolder holder, int position) { - holder.setMeasurements(channels[position], channelColors[position]); - } - - @Override - public int getItemCount() { - return channels.length; - } -} diff --git a/app/src/main/java/io/pslab/adapters/SensorLoggerListAdapter.java b/app/src/main/java/io/pslab/adapters/SensorLoggerListAdapter.java deleted file mode 100644 index 2c341d8f3..000000000 --- a/app/src/main/java/io/pslab/adapters/SensorLoggerListAdapter.java +++ /dev/null @@ -1,588 +0,0 @@ -package io.pslab.adapters; - -import android.app.Activity; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Environment; -import androidx.annotation.NonNull; - -import com.google.android.material.snackbar.Snackbar; - -import androidx.appcompat.app.AlertDialog; -import androidx.cardview.widget.CardView; -import androidx.core.content.res.ResourcesCompat; -import androidx.recyclerview.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.File; -import java.util.Date; - -import io.pslab.R; -import io.pslab.activity.AccelerometerActivity; -import io.pslab.activity.BarometerActivity; -import io.pslab.activity.CompassActivity; -import io.pslab.activity.GasSensorActivity; -import io.pslab.activity.GyroscopeActivity; -import io.pslab.activity.LogicalAnalyzerActivity; -import io.pslab.activity.LuxMeterActivity; -import io.pslab.activity.MapsActivity; -import io.pslab.activity.MultimeterActivity; -import io.pslab.activity.OscilloscopeActivity; -import io.pslab.activity.PowerSourceActivity; -import io.pslab.activity.RoboticArmActivity; -import io.pslab.activity.SoundMeterActivity; -import io.pslab.activity.ThermometerActivity; -import io.pslab.activity.WaveGeneratorActivity; -import io.pslab.models.AccelerometerData; -import io.pslab.models.BaroData; -import io.pslab.models.CompassData; -import io.pslab.models.GasSensorData; -import io.pslab.models.GyroData; -import io.pslab.models.LogicAnalyzerData; -import io.pslab.models.LuxData; -import io.pslab.models.MultimeterData; -import io.pslab.models.OscilloscopeData; -import io.pslab.models.PSLabSensor; -import io.pslab.models.PowerSourceData; -import io.pslab.models.SensorDataBlock; -import io.pslab.models.ServoData; -import io.pslab.models.SoundData; -import io.pslab.models.ThermometerData; -import io.pslab.models.WaveGeneratorData; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.LocalDataLog; -import io.realm.RealmRecyclerViewAdapter; -import io.realm.RealmResults; - -/** - * Created by Avjeet on 03-08-2018. - */ -public class SensorLoggerListAdapter extends RealmRecyclerViewAdapter { - - - private final String KEY_LOG = "has_log"; - private final String DATA_BLOCK = "data_block"; - private Activity context; - - public SensorLoggerListAdapter(RealmResults results, Activity context) { - super(results, true, true); - this.context = context; - } - - @NonNull - @Override - public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - View itemView = LayoutInflater.from(parent.getContext()).inflate( - R.layout.logger_data_item, parent, false); - return new ViewHolder(itemView); - } - - @Override - public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { - final SensorDataBlock block = getItem(position); - assert block != null; - switch (block.getSensorType()) { - case PSLabSensor.LUXMETER: - holder.sensor.setText(context.getResources().getString(R.string.lux_meter)); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tile_icon_lux_meter_log, null)); - break; - case PSLabSensor.BAROMETER: - holder.sensor.setText(context.getResources().getString(R.string.baro_meter)); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tile_icon_barometer_log, null)); - break; - case PSLabSensor.GYROSCOPE: - holder.sensor.setText(context.getResources().getString(R.string.gyroscope)); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.gyroscope_logo, null)); - break; - case PSLabSensor.COMPASS: - holder.sensor.setText(context.getResources().getString(R.string.compass)); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tile_icon_compass_log, null)); - break; - case PSLabSensor.ACCELEROMETER: - holder.sensor.setText(context.getResources().getString(R.string.accelerometer)); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tile_icon_accelerometer, null)); - break; - case PSLabSensor.THERMOMETER: - holder.sensor.setText(R.string.thermometer); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.thermometer_logo, null)); - break; - case PSLabSensor.ROBOTIC_ARM: - holder.sensor.setText(R.string.robotic_arm); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.robotic_arm, null)); - break; - case PSLabSensor.WAVE_GENERATOR: - holder.sensor.setText(R.string.wave_generator); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tile_icon_wave_generator, null)); - break; - case PSLabSensor.OSCILLOSCOPE: - holder.sensor.setText(R.string.oscilloscope); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tile_icon_oscilloscope, null)); - break; - case PSLabSensor.POWER_SOURCE: - holder.sensor.setText(R.string.power_source); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tile_icon_power_source, null)); - break; - case PSLabSensor.MULTIMETER: - holder.sensor.setText(R.string.multimeter); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tile_icon_multimeter, null)); - break; - case PSLabSensor.LOGIC_ANALYZER: - holder.sensor.setText(R.string.logical_analyzer); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tile_icon_logic_analyzer, null)); - break; - case PSLabSensor.GAS_SENSOR: - holder.sensor.setText(R.string.gas_sensor); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tile_icon_gas, null)); - break; - case PSLabSensor.SOUND_METER: - holder.sensor.setText(R.string.sound_meter); - holder.tileIcon.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tile_icon_gas, null)); - break; - default: - break; - } - holder.dateTime.setText(String.valueOf(CSVLogger.FILE_NAME_FORMAT.format(new Date(block.getBlock())))); - holder.cardView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - handleCardViewClick(block); - } - }); - holder.deleteIcon.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - handleDeleteItem(block); - } - }); - holder.mapIcon.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - populateMapData(block); - } - }); - } - - private void handleCardViewClick(SensorDataBlock block) { - if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.lux_meter))) { - Intent LuxMeter = new Intent(context, LuxMeterActivity.class); - LuxMeter.putExtra(KEY_LOG, true); - LuxMeter.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(LuxMeter); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.baro_meter))) { - Intent BaroMeter = new Intent(context, BarometerActivity.class); - BaroMeter.putExtra(KEY_LOG, true); - BaroMeter.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(BaroMeter); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.gyroscope))) { - Intent Gyroscope = new Intent(context, GyroscopeActivity.class); - Gyroscope.putExtra(KEY_LOG, true); - Gyroscope.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(Gyroscope); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.compass))) { - Intent Compass = new Intent(context, CompassActivity.class); - Compass.putExtra(KEY_LOG, true); - Compass.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(Compass); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.accelerometer))) { - Intent Accelerometer = new Intent(context, AccelerometerActivity.class); - Accelerometer.putExtra(KEY_LOG, true); - Accelerometer.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(Accelerometer); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.thermometer))) { - Intent Thermometer = new Intent(context, ThermometerActivity.class); - Thermometer.putExtra(KEY_LOG, true); - Thermometer.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(Thermometer); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.robotic_arm))) { - Intent RoboticArm = new Intent(context, RoboticArmActivity.class); - RoboticArm.putExtra(KEY_LOG, true); - RoboticArm.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(RoboticArm); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.wave_generator))) { - Intent waveGenerator = new Intent(context, WaveGeneratorActivity.class); - waveGenerator.putExtra(KEY_LOG, true); - waveGenerator.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(waveGenerator); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.oscilloscope))) { - Intent oscilloscope = new Intent(context, OscilloscopeActivity.class); - oscilloscope.putExtra(KEY_LOG, true); - oscilloscope.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(oscilloscope); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.power_source))) { - Intent powerSource = new Intent(context, PowerSourceActivity.class); - powerSource.putExtra(KEY_LOG, true); - powerSource.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(powerSource); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.multimeter))) { - Intent multimeter = new Intent(context, MultimeterActivity.class); - multimeter.putExtra(KEY_LOG, true); - multimeter.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(multimeter); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.logical_analyzer))) { - Intent laIntent = new Intent(context, LogicalAnalyzerActivity.class); - laIntent.putExtra(KEY_LOG, true); - laIntent.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(laIntent); - } else if (block.getSensorType().equalsIgnoreCase(context.getResources().getString(R.string.gas_sensor))) { - Intent gasSensorIntent = new Intent(context, GasSensorActivity.class); - gasSensorIntent.putExtra(KEY_LOG, true); - gasSensorIntent.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(gasSensorIntent); - } else if (block.getSensorType().equalsIgnoreCase(context.getString(R.string.sound_meter))) { - Intent soundMeterIntent = new Intent(context, SoundMeterActivity.class); - soundMeterIntent.putExtra(KEY_LOG, true); - soundMeterIntent.putExtra(DATA_BLOCK, block.getBlock()); - context.startActivity(soundMeterIntent); - } - } - - private void handleDeleteItem(final SensorDataBlock block) { - new AlertDialog.Builder(context) - .setTitle(context.getString(R.string.delete)) - .setMessage(context.getString(R.string.delete_confirmation) + " " + - CSVLogger.FILE_NAME_FORMAT.format(block.getBlock()) + "?") - .setPositiveButton(context.getString(R.string.delete), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - File logDirectory = new File( - Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSVLogger.CSV_DIRECTORY + - File.separator + block.getSensorType() + - File.separator + CSVLogger.FILE_NAME_FORMAT.format(block.getBlock()) + ".csv"); - CustomSnackBar.showSnackBar(context.findViewById(android.R.id.content), context.getString(R.string.log_deleted), null, null, Snackbar.LENGTH_LONG); - if (block.getSensorType().equalsIgnoreCase(PSLabSensor.LUXMETER)) { - LocalDataLog.with().clearBlockOfLuxRecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.BAROMETER)) { - LocalDataLog.with().clearBlockOfBaroRecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.GYROSCOPE)) { - LocalDataLog.with().clearBlockOfBaroRecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.COMPASS)) { - LocalDataLog.with().clearBlockOfCompassRecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.ACCELEROMETER_CONFIGURATIONS)) { - LocalDataLog.with().clearBlockOfAccelerometerRecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.ROBOTIC_ARM)) { - LocalDataLog.with().clearBlockOfServoRecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.WAVE_GENERATOR)) { - LocalDataLog.with().clearBlockOfWaveRecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.OSCILLOSCOPE)) { - LocalDataLog.with().clearBlockOfOscilloscopeRecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.POWER_SOURCE)) { - LocalDataLog.with().clearBlockOfPowerRecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.MULTIMETER)) { - LocalDataLog.with().clearBlockOfMultimeterRecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.LOGIC_ANALYZER)) { - LocalDataLog.with().clearBlockOfLARecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.GAS_SENSOR)) { - LocalDataLog.with().clearBlockOfGasSensorRecords(block.getBlock()); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.SOUND_METER)) { - LocalDataLog.with().clearBlockOfSoundRecords(block.getBlock()); - } - LocalDataLog.with().clearSensorBlock(block.getBlock()); - dialog.dismiss(); - if (LocalDataLog.with().getAllSensorBlocks().size() <= 0) { - context.findViewById(R.id.data_logger_blank_view).setVisibility(View.VISIBLE); - } else { - context.findViewById(R.id.data_logger_blank_view).setVisibility(View.GONE); - } - } - }) - .setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }) - .create().show(); - } - - private void populateMapData(SensorDataBlock block) { - - if (block.getSensorType().equalsIgnoreCase(PSLabSensor.LUXMETER)) { - RealmResults data = LocalDataLog.with().getBlockOfLuxRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (LuxData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("data", d.getLux()); - i.put("lon", d.getLon()); - i.put("lat", d.getLat()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.BAROMETER)) { - RealmResults data = LocalDataLog.with().getBlockOfBaroRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (BaroData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("data", d.getBaro()); - i.put("altitude", d.getAltitude()); - i.put("lon", d.getLon()); - i.put("lat", d.getLat()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.GYROSCOPE)) { - RealmResults data = LocalDataLog.with().getBlockOfGyroRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (GyroData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("dataX", d.getGyroX()); - i.put("dataY", d.getGyroY()); - i.put("dataZ", d.getGyroZ()); - i.put("lon", d.getLon()); - i.put("lat", d.getLat()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.COMPASS)) { - RealmResults data = LocalDataLog.with().getBlockOfCompassRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (CompassData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("dataX", d.getBx()); - i.put("dataY", d.getBy()); - i.put("dataZ", d.getBz()); - i.put("Axis", d.getAxis()); - i.put("lon", d.getLon()); - i.put("lat", d.getLat()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.ACCELEROMETER)) { - RealmResults data = LocalDataLog.with().getBlockOfAccelerometerRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (AccelerometerData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("dataX", d.getAccelerometerX()); - i.put("dataY", d.getAccelerometerY()); - i.put("dataZ", d.getAccelerometerZ()); - i.put("lon", d.getLon()); - i.put("lat", d.getLat()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.THERMOMETER)) { - RealmResults data = LocalDataLog.with().getBlockOfThermometerRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (ThermometerData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("Axis", d.getTemp()); - i.put("lon", d.getLon()); - i.put("lat", d.getLat()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.ROBOTIC_ARM)) { - RealmResults data = LocalDataLog.with().getBlockOfServoRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (ServoData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("Servo1", d.getDegree1()); - i.put("Servo2", d.getDegree2()); - i.put("Servo3", d.getDegree3()); - i.put("Servo4", d.getDegree4()); - i.put("lon", d.getLon()); - i.put("lat", d.getLat()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.WAVE_GENERATOR)) { - RealmResults data = LocalDataLog.with().getBlockOfWaveRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (WaveGeneratorData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("Mode", d.getMode()); - i.put("Wave", d.getWave()); - i.put("Shape", d.getShape()); - i.put("Freq", d.getFreq()); - i.put("Phase", d.getPhase()); - i.put("Duty", d.getDuty()); - i.put("lon", d.getLon()); - i.put("lat", d.getLat()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.OSCILLOSCOPE)) { - RealmResults data = LocalDataLog.with().getBlockOfOscilloscopeRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (OscilloscopeData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("channel", d.getChannel()); - i.put("xData", d.getDataX()); - i.put("yData", d.getDataY()); - i.put("timebase", d.getTimebase()); - i.put("lat", d.getLat()); - i.put("lon", d.getLon()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.POWER_SOURCE)) { - RealmResults data = LocalDataLog.with().getBlockOfPowerRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (PowerSourceData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("PV1", d.getPv1()); - i.put("PV2", d.getPv2()); - i.put("PV3", d.getPv3()); - i.put("PCS", d.getPcs()); - i.put("lat", d.getLat()); - i.put("lon", d.getLon()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.MULTIMETER)) { - RealmResults data = LocalDataLog.with().getBlockOfMultimeterRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (MultimeterData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("data", d.getData()); - i.put("value", d.getValue()); - i.put("lat", d.getLat()); - i.put("lon", d.getLon()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.LOGIC_ANALYZER)) { - RealmResults data = LocalDataLog.with().getBlockOfLARecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (LogicAnalyzerData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("channel", d.getChannel()); - i.put("channel_mode", d.getChannelMode()); - i.put("xaxis", d.getDataX()); - i.put("yaxis", d.getDataY()); - i.put("lat", d.getLat()); - i.put("lon", d.getLon()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.GAS_SENSOR)) { - RealmResults data = LocalDataLog.with().getBlockOfGasSensorRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (GasSensorData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("ppmValue", d.getPpmValue()); - i.put("lon", d.getLon()); - i.put("lat", d.getLat()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } else if (block.getSensorType().equalsIgnoreCase(PSLabSensor.SOUND_METER)) { - RealmResults data = LocalDataLog.with().getBlockOfSoundRecords(block.getBlock()); - JSONArray array = new JSONArray(); - for (SoundData d : data) { - try { - JSONObject i = new JSONObject(); - i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime())); - i.put("dB", d.getdB()); - i.put("lon", d.getLon()); - i.put("lat", d.getLat()); - if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i); - } catch (JSONException e) { - e.printStackTrace(); - } - } - setMapDataToIntent(array); - } - } - - private void setMapDataToIntent(JSONArray array) { - Intent map = new Intent(context, MapsActivity.class); - if (array.length() > 0) { - map.putExtra("hasMarkers", true); - map.putExtra("markers", array.toString()); - context.startActivity(map); - } else { - map.putExtra("hasMarkers", false); - CustomSnackBar.showSnackBar(context.findViewById(android.R.id.content), - context.getString(R.string.no_location_data), null, null, Snackbar.LENGTH_LONG); - } - } - - public class ViewHolder extends RecyclerView.ViewHolder { - private TextView sensor, dateTime; - private ImageView deleteIcon, mapIcon, tileIcon; - private CardView cardView; - - public ViewHolder(View itemView) { - super(itemView); - dateTime = itemView.findViewById(R.id.date_time); - sensor = itemView.findViewById(R.id.sensor_name); - deleteIcon = itemView.findViewById(R.id.delete_item); - mapIcon = itemView.findViewById(R.id.map_item); - tileIcon = itemView.findViewById(R.id.sensor_tile_icon); - cardView = itemView.findViewById(R.id.data_item_card); - } - } -} diff --git a/app/src/main/java/io/pslab/communication/AnalyticsClass.java b/app/src/main/java/io/pslab/communication/AnalyticsClass.java deleted file mode 100644 index 8a0019ed5..000000000 --- a/app/src/main/java/io/pslab/communication/AnalyticsClass.java +++ /dev/null @@ -1,602 +0,0 @@ -package io.pslab.communication; - -import android.util.Log; - -import org.apache.commons.math3.analysis.ParametricUnivariateFunction; -import org.apache.commons.math3.complex.Complex; -import org.apache.commons.math3.fitting.CurveFitter; -import org.apache.commons.math3.optim.nonlinear.vector.jacobian.LevenbergMarquardtOptimizer; -import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; -import org.apache.commons.math3.transform.DftNormalization; -import org.apache.commons.math3.transform.FastFourierTransformer; -import org.apache.commons.math3.transform.TransformType; - -import io.pslab.filters.BandstopFilter; -import io.pslab.filters.Lfilter; - -import java.util.ArrayList; -import java.util.Arrays; - -import static java.lang.Math.cos; -import static org.apache.commons.lang3.math.NumberUtils.min; -import static org.apache.commons.lang3.math.NumberUtils.max; -import static org.apache.commons.math3.util.FastMath.abs; -import static org.apache.commons.math3.util.FastMath.exp; -import static org.apache.commons.math3.util.FastMath.sin; - -/** - * Created by akarshan on 5/13/17. - *

- * Unlike python, the curve fitting and the fourier transorm methods only accepts the arrays - * of length of power of 2. - *

- * JAVA equivalent of scipy.fftpack.rfft, scipy.fftpack.rfftfreq and scipy.fftpack.fftfreq functions are'nt - * available so they are been added in this class by the name fftToRfft, rfftFrequency and fftFrequency - * respectively. - *

- * The fit functions have passed some dry tests but required to be tested with data points generated by PSLab. - *

- */ - -@SuppressWarnings("ALL") -public class AnalyticsClass { - - // todo : check the accuracy of the all the curve fitting methods with data points generated by PSLab - //-------------------------- Exponential Fit ----------------------------------------// - - private ParametricUnivariateFunction exponentialParametricUnivariateFunction = new ParametricUnivariateFunction() { - @Override - public double value(double x, double... parameters) { - double a = parameters[0]; - double b = parameters[1]; - double c = parameters[2]; - return a * exp(-x / b) + c; - } - - @Override - public double[] gradient(double x, double... parameters) { - double a = parameters[0]; - double b = parameters[1]; - double c = parameters[2]; - - return new double[]{ - exp(-x / b), - (a * exp(-x / b) * x) / (b * b), - 1 - }; //partial derivatives - } - }; - - public ArrayList fitExponential(double time[], double voltage[]) { - //length of time and voltage arrays should be in the power of 2 - double size = time.length; - double v80 = voltage[0] * 0.8; - double rc = 0; - double[] vf = new double[time.length]; - for (int k = 0; k < size - 1; k++) { - if (voltage[k] < v80) { - rc = time[k] / .223; - break; - } - } - double[] initialGuess = new double[]{voltage[0], rc, 0}; - //initialize the optimizer and curve fitter. - LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(); - CurveFitter fitter = new CurveFitter(optimizer); - for (int i = 0; i < time.length; i++) - fitter.addObservedPoint(time[i], voltage[i]); - double[] result = fitter.fit(exponentialParametricUnivariateFunction, initialGuess); //result -> the fitted parameters. - for (int i = 0; i < time.length; i++) - vf[i] = result[0] * exp(-time[i] / result[1]) + result[2]; - return new ArrayList(Arrays.asList(result, vf)); - } - - //-------------------------- Sine Fit ----------------------------------------// - - private ParametricUnivariateFunction sineParametricUnivariateFunction = new ParametricUnivariateFunction() { - @Override - public double value(double x, double... parameters) { - double a1 = parameters[0]; - double a2 = parameters[1]; - double a3 = parameters[2]; - double a4 = parameters[3]; - return a4 + a1 * sin(abs(a2 * (2 * Math.PI)) * x + a3); - } - - @Override - public double[] gradient(double x, double... parameters) { - double a = parameters[0]; - double b = parameters[1]; - double c = parameters[2]; - double d = parameters[3]; - return new double[]{ - Math.sin(c + 2 * Math.PI * b * x), - 2 * a * Math.PI * x * cos(c + 2 * b * Math.PI * x), - a * cos(c + 2 * b * Math.PI * x), - 1 - }; - } - }; - - public double[] sineFit(double[] xReal, double[] yReal) { - int n = xReal.length; - int index = 0; - double[] frequencyArray = new double[]{}; - double[] yReal2 = new double[yReal.length]; - double yHat[]; - double yHatSquare[]; - double max = 0.; - double returnOffset = 0; - double frequency; - double returnFrequency; - double amplitude; - double returnAmplitude; - double phase; - double returnPhase; - double[] guess; - Complex complex[]; - - double offset = ((double) max(yReal) + (double) min(yReal)) / 2; - for (int i = 0; i < yReal.length; i++) - yReal2[i] = yReal[i] - offset; - - FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD); - complex = fastFourierTransformer.transform(yReal2, TransformType.FORWARD); - yHat = fftToRfft(complex); //yHat is an array of Discrete Fourier transform of a real sequence - yHatSquare = new double[yHat.length]; - for (int i = 0; i < yHat.length; i++) { - yHatSquare[i] = Math.pow(yHat[i], 2); - if (yHatSquare[i] > max) { //yHatSquare is an array square of each element of yHat - max = yHatSquare[i]; - index = i; - } - } - - frequencyArray = rfftFrequency(n, (xReal[1] - xReal[0]) / (2 * Math.PI)); - frequency = frequencyArray[index]; - frequency /= (2 * Math.PI); - - amplitude = (max(yReal) - min(yReal)) / 2.0; - - phase = 0; - - LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(); - CurveFitter fitter = new CurveFitter(optimizer); - for (int i = 0; i < n; i++) - fitter.addObservedPoint(xReal[i], yReal2[i]); - - guess = new double[]{amplitude, frequency, phase, 0}; - double[] result = fitter.fit(sineParametricUnivariateFunction, guess); - - amplitude = result[0]; - frequency = result[1]; - phase = result[2]; - returnOffset = result[3]; - - if (frequency < 0) - Log.v("sineFit", "negative frequency"); - - returnOffset += offset; - returnPhase = ((phase) * 180 / (3.14)); - if (amplitude < 0) - returnPhase -= 180; - if (returnPhase < 0) - returnPhase = (returnPhase + 720) % 360; - returnFrequency = 1e6 * abs(frequency); - returnAmplitude = abs(amplitude); - return new double[]{returnAmplitude, returnFrequency, returnOffset, returnPhase}; - } - - ParametricUnivariateFunction squareParametricUnivariateFunction = new ParametricUnivariateFunction() { - @Override - public double value(double x, double... parameters) { - double amp = parameters[0]; - double freq = parameters[1]; - double phase = parameters[2]; - double dc = parameters[3]; //dc - duty cycle - double offset = parameters[4]; - return offset + amp * signalSquare(2 * Math.PI * freq * (x - phase), freq, dc); - } - - @Override - public double[] gradient(double x, double... parameters) { - /*partial derivatives w.r.t all the five variables. Square functions are not differentiable - at finitely many points, still we have used it anyway since the curve fitter uses the value of - gradients. The values are true except at points where the transition from high to low or low to high - takes place.*/ - double a = parameters[0]; //unused for partial derivative - double b = parameters[1]; - double c = parameters[2]; - double d = parameters[3]; - double e = parameters[4]; //unused for partial derivative - - return new double[]{ - signalSquare(2 * Math.PI * b * (x - c), b, d), 0, 0, 0, 1 - }; - } - }; - - public double[] squareFit(double[] xReal, double[] yReal) { - int n = xReal.length; - double mx = max(yReal); - double mn = min(xReal); - double offset = (mx + mn) / 2; - double sumGreaterThanOffset = 0; - double sumLesserThanOffset = 0; - double n1 = 0; // count of numbers less than offset - double n2 = 0; // count of numbers less than offset - double[] yTmp = new double[yReal.length]; - double[] yReal2 = new double[yReal.length]; - double[] guess; - double returnOffset; - double returnFrequency; - double returnAmplitude; - double returnPhase; - double returnDC; - - for (int i = 0; i < yReal.length; i++) - yReal2[i] = yReal[i] - offset; - - for (int i = 0; i < yReal.length; i++) { - if (yReal[i] > offset) { - sumGreaterThanOffset += yReal[i]; - yTmp[i] = 2; - n1++; - } else if (yReal[i] < offset) { - sumLesserThanOffset += yReal[i]; - yTmp[i] = 0; - n2++; - } - } - - double amplitude = (sumGreaterThanOffset / n1) - (sumLesserThanOffset / n2); - boolean[] bools = new boolean[yTmp.length]; - double tmp; - for (int i = 0; i < yTmp.length - 1; i++) { - tmp = yTmp[i + 1] - yTmp[i]; - tmp = abs(tmp); - bools[i] = tmp > 1; - } - double[] edges = new double[bools.length]; - double[] levels = new double[bools.length]; - int j = 0; - for (int i = 0; i < bools.length; i++) { - if (bools[i]) { - edges[j] = xReal[i]; - levels[j] = yTmp[i]; - j++; - } - } - - double frequency = 1 / (edges[2] - edges[0]); - double phase = edges[0]; - double dc = 0.5; - - if (edges.length >= 4) { - if (levels[0] == 0) - dc = (edges[1] - edges[0]) / (edges[2] - edges[0]); - else { - dc = (edges[2] - edges[1]) / (edges[3] - edges[1]); - phase = edges[1]; - } - } - - LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(); - CurveFitter fitter = new CurveFitter(optimizer); - for (int i = 0; i < n; i++) - fitter.addObservedPoint(xReal[i], yReal2[i]); - - guess = new double[]{amplitude, frequency, phase, dc, 0}; - double[] result = fitter.fit(squareParametricUnivariateFunction, guess); - - amplitude = result[0]; - frequency = result[1]; - phase = result[2]; - dc = result[3]; - returnOffset = result[4]; - - if (frequency < 0) - Log.v("squareFit", "negative frequency"); - - returnOffset += offset; - returnFrequency = 1e6 * abs(frequency); - returnAmplitude = abs(amplitude); - returnPhase = phase; - returnDC = dc; - - return new double[]{returnAmplitude, returnFrequency, returnPhase, returnDC, returnOffset}; - } - - public double findSignalFrequency(double[] voltage, double samplingInterval) { - int voltageLength = voltage.length; - double[] frequency; - double[] amplitude; - int index = 0; - double max = 0; - Complex[] complex; - DescriptiveStatistics stats = new DescriptiveStatistics(); - for (int i = 0; i < voltageLength; i++) - stats.addValue(voltage[i]); - double voltageMean = stats.getMean(); - for (int i = 0; i < voltageLength; i++) - voltage[i] = voltage[i] - voltageMean; // remove DC component - frequency = Arrays.copyOfRange(fftFrequency(voltageLength, samplingInterval), 0, voltageLength / 2); // take only the +ive half of the frequncy array - FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD); - complex = fastFourierTransformer.transform(voltage, TransformType.FORWARD); - amplitude = new double[complex.length / 2]; - for (int i = 0; i < complex.length / 2; i++) { // take only the +ive half of the fft result - amplitude[i] = complex[i].abs() / voltageLength; - if (amplitude[i] > max) { // search for the tallest peak, the fundamental - max = amplitude[i]; - index = i; - } - } - double noiseThreshold = 0.1; - if (max >= noiseThreshold) { - return frequency[index]; - } else { - return -1; - } - } - - public double findFrequency(double[] voltage, double samplingInterval) { - int voltageLength = voltage.length; - double[] frequency; - double[] amplitude; - int index = 0; - double max = 0; - Complex[] complex; - DescriptiveStatistics stats = new DescriptiveStatistics(); - for (int i = 0; i < voltageLength; i++) - stats.addValue(voltage[i]); - double voltageMean = stats.getMean(); - for (int i = 0; i < voltageLength; i++) - voltage[i] = voltage[i] - voltageMean; // remove DC component - frequency = Arrays.copyOfRange(fftFrequency(voltageLength, samplingInterval), 0, voltageLength / 2); // take only the +ive half of the frequncy array - FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD); - complex = fastFourierTransformer.transform(voltage, TransformType.FORWARD); - amplitude = new double[complex.length / 2]; - for (int i = 0; i < complex.length / 2; i++) { // take only the +ive half of the fft result - amplitude[i] = complex[i].abs() / voltageLength; - if (amplitude[i] > max) { // search for the tallest peak, the fundamental - max = amplitude[i]; - index = i; - } - } - return frequency[index]; - } - - public ArrayList amplitudeSpectrum(double[] voltage, int samplingInterval, int nHarmonics) { - int voltageLength = voltage.length; - Complex[] complex; - double[] amplitude; - double[] newAmplitude; - int index = 0; - double max = 0; - double[] frequency = Arrays.copyOfRange(fftFrequency(voltageLength, samplingInterval), 0, voltageLength / 2); // take only the +ive half of the frequncy array - FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD); - complex = fastFourierTransformer.transform(voltage, TransformType.FORWARD); - amplitude = new double[complex.length / 2]; - for (int i = 0; i < complex.length / 2; i++) { // take only the +ive half of the fft result - amplitude[i] = complex[i].abs() / voltageLength; - if (amplitude[i] > max) { // search for the tallest peak, the fundamental - max = amplitude[i]; - index = i; - } - } - if (index == 0) { // DC component is dominating - max = 0; - newAmplitude = Arrays.copyOfRange(amplitude, 4, amplitude.length); // skip frequencies close to zero - for (int i = 0; i < newAmplitude.length; i++) { - if (newAmplitude[i] > max) { - max = newAmplitude[i]; - index = i; - } - } - } - return new ArrayList(Arrays.asList( // restrict to 'nHarmonics' harmonics - Arrays.copyOfRange(frequency, index * nHarmonics, frequency.length), - Arrays.copyOfRange(amplitude, index * nHarmonics, amplitude.length) - )); - } - - //-------------------------- Damped Sine Fit ----------------------------------------// - - public ParametricUnivariateFunction dampedSineParametricUnivariateFunction = new ParametricUnivariateFunction() { - @Override - public double value(double x, double... parameters) { - double amplitude = parameters[0]; - double frequency = parameters[1]; - double phase = parameters[2]; - double offset = parameters[3]; - double damp = parameters[4]; - return offset + amplitude * exp(-damp * x) * sin(Math.abs(frequency) * x + phase); - } - - @Override - public double[] gradient(double x, double... parameters) { - double amplitude = parameters[0]; - double frequency = parameters[1]; - double phase = parameters[2]; - double offset = parameters[3]; - double damp = parameters[4]; - return new double[]{ - exp(-damp * x) * sin(x * frequency + phase), - amplitude * exp(-damp * x) * x * cos(x * frequency + phase), - amplitude * exp(-damp * x) * cos(x * frequency + phase), - -amplitude * exp(-damp * x) * x * sin(x * frequency + phase), - 1 - }; - } - }; - - - public double[] getGuessValues(double xReal[], double yReal[], String function) { - if (function.equals("sine") || function.equals("damped sine")) { - int n = xReal.length; - Complex[] complex; - double[] yReal2 = new double[yReal.length]; - double[] yHatSquare; - double[] yHat; - double[] frequencyArray; - double frequency; - double amplitude; - double phase; - double max = 0; - int index = 0; - DescriptiveStatistics stats = new DescriptiveStatistics(); - for (int i = 0; i < yReal.length; i++) - stats.addValue(yReal[i]); - double offset = stats.getMean(); - for (int i = 0; i < yReal.length; i++) - yReal2[i] = yReal[i] - offset; - FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD); - complex = fastFourierTransformer.transform(yReal, TransformType.FORWARD); - yHat = fftToRfft(complex); - yHatSquare = new double[yHat.length]; - for (int i = 0; i < yHat.length; i++) { - yHatSquare[i] = Math.pow(yHat[i], 2); - if (yHatSquare[i] > max) { //yHatSquare is an array square of each element of yHat - max = yHatSquare[i]; - index = i; - } - } - frequencyArray = rfftFrequency(n, (xReal[1] - xReal[0]) / 2); - frequency = frequencyArray[index]; - amplitude = (max(yReal) - min(yReal)) / 2.0; - phase = 0; - if (function.equals("sine")) - return new double[]{amplitude, frequency, phase, offset}; - if (function.equals("damped sine")) - return new double[]{amplitude, frequency, phase, offset, 0}; - } - return null; - } - - public double[] arbitFit(double[] xReal, double[] yReal, ParametricUnivariateFunction function, double[] guessValues) { - int n = xReal.length; - LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(); - CurveFitter fitter = new CurveFitter(optimizer); - for (int i = 0; i < n; i++) - fitter.addObservedPoint(xReal[i], yReal[i]); - double[] result = fitter.fit(function, guessValues); - return result; - } - - ArrayList butterNotch(double lowCut, double highCut, double fs, int order) { - double nyq = 0.5 * fs; - double low = lowCut / nyq; - double high = highCut / nyq; - BandstopFilter bandstopFilter = new BandstopFilter(order, new double[]{low, high}); - return bandstopFilter.abGetter(); - } - - double[] butterNotchFilter(double[] data, double lowCut, double highCut, double fs, int order) { - ArrayList arrayList = butterNotch(lowCut, highCut, fs, order); - double[] b = arrayList.get(0); - double[] a = arrayList.get(1); - Lfilter lfilter = new Lfilter(); - return lfilter.filter(b, a, data); - } - - public ArrayList fft(double[] signal, double samplingInterval) { - /* - Returns positive half of the Fourier transform of the signal. - Sampling interval 'samplingInterval', in milliseconds - */ - int ns = signal.length; - Complex[] complex; - double[] terms; - double[] frequencyArray; - double[] x; - double[] y; - if (ns % 2 == 1) { - ns = ns - 1; - signal = Arrays.copyOfRange(signal, 0, ns); - } - FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD); - complex = fastFourierTransformer.transform(signal, TransformType.FORWARD); - terms = new double[complex.length]; - for (int i = 0; i < complex.length; i++) - terms[i] = complex[i].abs() / ns; - frequencyArray = fftFrequency(ns, samplingInterval); - x = Arrays.copyOfRange(frequencyArray, 0, ns / 2); - y = Arrays.copyOfRange(terms, 0, ns / 2); - return new ArrayList(Arrays.asList(x, y)); - } - - public double[] rfftFrequency(int n, double space) { - /* - The returned array contains the frequency bins in - cycles/unit (with zero at the start) given a window length `n` and a - sample spacing `space` - */ - double[] returnArray = new double[n + 1]; - for (int i = 0; i < n + 1; i++) { - returnArray[i] = Math.floor(i / 2) / (n * space); - } - return Arrays.copyOfRange(returnArray, 1, returnArray.length); - } - - public double[] fftFrequency(int n, double space) { - /* - Return the Discrete Fourier Transform sample frequencies. - The returned array contains the frequency bin centers in cycles - per unit of the sample spacing (with zero at the start). For instance, if - the sample spacing is in seconds, then the frequency unit is cycles/second. - Given a window length `n` and a sample spacing `spacing`. - */ - double value = 1.0 / (n * space); - int N = Math.floorDiv(n - 1, 2) + 1; - double[] results = new double[n]; - for (int i = 0; i < N; i++) { - results[i] = i; - results[i] = results[i] * value; - } - int j = N; - for (int i = -Math.floorDiv(n, 2); i < 0; i++) { - - results[j] = i; - results[j] = results[j] * value; - j++; - } - return results; - } - - public double[] fftToRfft(Complex[] complex) { - //The returned array contains Discrete Fourier transform of a real sequence. - double[] real = new double[complex.length]; - double[] imaginary = new double[complex.length]; - double[] result = new double[complex.length]; - int j = 0; - int k = 0; - int l = 0; - for (int i = 0; i < complex.length / 2 + 1; i++) { - real[i] = complex[i].getReal(); - imaginary[i] = complex[i].getImaginary(); - } - - for (int i = 0; i < complex.length / 2 + 1; i++) { - if (real[j] == 0.0 && imaginary[k] == 0) { - result[l++] = 0.0; - j++; - k++; - } else if (real[j] != 0 && imaginary[k] == 0) { - result[l++] = real[j++]; - k++; - } else { - result[l++] = real[j++]; - result[l++] = imaginary[k++]; - } - } - return result; - } - - public double signalSquare(double xAxisValue, double freq, double dc) { - //This method determines whether at a given x value, the value of y is in the upper half or lower half - if (xAxisValue % (2 * Math.PI * freq) <= dc) - return 1; - else - return -1; - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/communication/CommandsProto.java b/app/src/main/java/io/pslab/communication/CommandsProto.java deleted file mode 100644 index 6ee80f60d..000000000 --- a/app/src/main/java/io/pslab/communication/CommandsProto.java +++ /dev/null @@ -1,285 +0,0 @@ -package io.pslab.communication; - -import android.util.Log; - -public class CommandsProto { - - private static String TAG = "CommandsProto"; - - public int ACKNOWLEDGE = 254; - public int MAX_SAMPLES = 10000; - public int DATA_SPLITTING = 60; - - public int ADC = 2; - public int CAPTURE_ONE = 1; - public int CAPTURE_TWO = 2; - public int CAPTURE_DMASPEED = 3; - public int CAPTURE_FOUR = 4; - public int CONFIGURE_TRIGGER = 5; - public int GET_CAPTURE_STATUS = 6; - public int GET_CAPTURE_CHANNEL = 7; - public int SET_PGA_GAIN = 8; - public int GET_VOLTAGE = 9; - public int GET_VOLTAGE_SUMMED = 10; - // public int START_ADC_STREAMING = 11; - public int SELECT_PGA_CHANNEL = 12; - public int CAPTURE_12BIT = 13; - // public int CAPTURE_MULTIPLE = 14; - public int SET_HI_CAPTURE = 15; - public int SET_LO_CAPTURE = 16; - - public int MULTIPOINT_CAPACITANCE = 20; - public int SET_CAP = 21; - public int PULSE_TRAIN = 22; - - public int SPI_HEADER = 3; - public int START_SPI = 1; - public int SEND_SPI8 = 2; - public int SEND_SPI16 = 3; - public int STOP_SPI = 4; - public int SET_SPI_PARAMETERS = 5; - public int SEND_SPI8_BURST = 6; - public int SEND_SPI16_BURST = 7; - - public int I2C_HEADER = 4; - public int I2C_START = 1; - public int I2C_SEND = 2; - public int I2C_STOP = 3; - public int I2C_RESTART = 4; - public int I2C_READ_END = 5; - public int I2C_READ_MORE = 6; - public int I2C_WAIT = 7; - public int I2C_SEND_BURST = 8; - public int I2C_CONFIG = 9; - public int I2C_STATUS = 10; - public int I2C_READ_BULK = 11; - public int I2C_WRITE_BULK = 12; - public int I2C_ENABLE_SMBUS = 13; - public int I2C_INIT = 14; - public int I2C_PULLDOWN_SCL = 15; - public int I2C_DISABLE_SMBUS = 16; - - - public int UART_2 = 5; - public int SEND_BYTE = 1; - public int SEND_INT = 2; - public int SEND_ADDRESS = 3; - public int SET_BAUD = 4; - public int SET_MODE = 5; - public int READ_BYTE = 6; - public int READ_INT = 7; - public int READ_UART2_STATUS = 8; - - - public int DAC = 6; - public int SET_DAC = 1; - public int SET_CALIBRATED_DAC = 2; - public int SET_POWER = 3; - - - public int WAVEGEN = 7; - public int SET_WG = 1; - public int SET_SQR1 = 3; - public int SET_SQR2 = 4; - public int SET_SQRS = 5; - public int TUNE_SINE_OSCILLATOR = 6; - public int SQR4 = 7; - public int MAP_REFERENCE = 8; - public int SET_BOTH_WG = 9; - public int SET_WAVEFORM_TYPE = 10; - public int SELECT_FREQ_REGISTER = 11; - public int DELAY_GENERATOR = 12; - public int SET_SINE1 = 13; - public int SET_SINE2 = 14; - - public int LOAD_WAVEFORM1 = 15; - public int LOAD_WAVEFORM2 = 16; - public int SQR1_PATTERN = 17; - - - public int DOUT = 8; - public int SET_STATE = 1; - - - public int DIN = 9; - public int GET_STATE = 1; - public int GET_STATES = 2; - - - public int LA1 = 0; - public int LA2 = 1; - public int LA3 = 2; - public int LA4 = 3; - public int LMETER = 4; - - - public int TIMING = 10; - public int GET_TIMING = 1; - public int GET_PULSE_TIME = 2; - public int GET_DUTY_CYCLE = 3; - public int START_ONE_CHAN_LA = 4; - public int START_TWO_CHAN_LA = 5; - public int START_FOUR_CHAN_LA = 6; - public int FETCH_DMA_DATA = 7; - public int FETCH_INT_DMA_DATA = 8; - public int FETCH_LONG_DMA_DATA = 9; - public int GET_LA_PROGRESS = 10; - public int GET_INITIAL_DIGITAL_STATES = 11; - - public int TIMING_MEASUREMENTS = 12; - public int INTERVAL_MEASUREMENTS = 13; - public int CONFIGURE_COMPARATOR = 14; - public int START_ALTERNATE_ONE_CHAN_LA = 15; - public int START_THREE_CHAN_LA = 16; - public int STOP_LA = 17; - - - public int COMMON = 11; - - public int GET_CTMU_VOLTAGE = 1; - public int GET_CAPACITANCE = 2; - public int GET_FREQUENCY = 3; - public int GET_INDUCTANCE = 4; - - public int GET_VERSION = 5; - public int GET_FW_VERSION = 6; - public int DEBUG_IS_ENABLED = 7; - - public int RETRIEVE_BUFFER = 8; - public int GET_HIGH_FREQUENCY = 9; - public int CLEAR_BUFFER = 10; - public int SET_RGB1 = 11; - public int READ_PROGRAM_ADDRESS = 12; - public int WRITE_PROGRAM_ADDRESS = 13; - public int READ_DATA_ADDRESS = 14; - public int WRITE_DATA_ADDRESS = 15; - - public int GET_CAP_RANGE = 16; - public int SET_RGB2 = 17; - public int READ_LOG = 18; - public int RESTORE_STANDALONE = 19; - public int GET_ALTERNATE_HIGH_FREQUENCY = 20; - public int SET_RGB_COMMON = 21; - public int SET_RGB3 = 22; - - public int START_CTMU = 23; - public int STOP_CTMU = 24; - - public int START_COUNTING = 25; - public int FETCH_COUNT = 26; - public int FILL_BUFFER = 27; - - - public int SETBAUD = 12; - public int BAUD9600 = 1; - public int BAUD14400 = 2; - public int BAUD19200 = 3; - public int BAUD28800 = 4; - public int BAUD38400 = 5; - public int BAUD57600 = 6; - public int BAUD115200 = 7; - public int BAUD230400 = 8; - public int BAUD1000000 = 9; - - - public int NRFL01 = 13; - public int NRF_SETUP = 1; - public int NRF_RXMODE = 2; - public int NRF_TXMODE = 3; - public int NRF_POWER_DOWN = 4; - public int NRF_RXCHAR = 5; - public int NRF_TXCHAR = 6; - public int NRF_HASDATA = 7; - public int NRF_FLUSH = 8; - public int NRF_WRITEREG = 9; - public int NRF_READREG = 10; - public int NRF_GETSTATUS = 11; - public int NRF_WRITECOMMAND = 12; - public int NRF_WRITEPAYLOAD = 13; - public int NRF_READPAYLOAD = 14; - public int NRF_WRITEADDRESS = 15; - public int NRF_TRANSACTION = 16; - public int NRF_START_TOKEN_MANAGER = 17; - public int NRF_STOP_TOKEN_MANAGER = 18; - public int NRF_TOTAL_TOKENS = 19; - public int NRF_REPORTS = 20; - public int NRF_WRITE_REPORT = 21; - public int NRF_DELETE_REPORT_ROW = 22; - - public int NRF_WRITEADDRESSES = 23; - - - public int NONSTANDARD_IO = 14; - // public int HX711_HEADER = 1; - public int HCSR04_HEADER = 2; - // public int AM2302_HEADER = 3; - // public int TCD1304_HEADER = 4; - // public int STEPPER_MOTOR = 5; - - - public int PASSTHROUGHS = 15; - public int PASS_UART = 1; - - // public int STOP_STREAMING = 253; - - public int EVERY_SIXTEENTH_RISING_EDGE = 0b101; - public int EVERY_FOURTH_RISING_EDGE = 0b100; - public int EVERY_RISING_EDGE = 0b011; - public int EVERY_FALLING_EDGE = 0b010; - public int EVERY_EDGE = 0b001; - public int DISABLED = 0b000; - - public int CSA1 = 1; - public int CSA2 = 2; - public int CSA3 = 3; - public int CSA4 = 4; - public int CSA5 = 5; - public int CS1 = 6; - public int CS2 = 7; - - public int TEN_BIT = 10; - public int TWELVE_BIT = 12; - - public byte[] pack(int value) { - int intValue = value; - byte[] bytes = new byte[4]; - int length = bytes.length; - for (int i = 0; i < length; i++) { - bytes[length - i - 1] = (byte) (intValue & 0xFF); - intValue >>= 8; - } - return bytes; - } - - public String applySIPrefix(double value, String unit, int precision) { - boolean negative = false; - if (value < 0) { - negative = true; - value *= -1; - } else if (value == 0) - return "0 " + unit; - int exponent = (int) Math.log10(value); - if (exponent > 0) { - exponent = (exponent / 3) * 3; - } else { - exponent = ((-1 * exponent + 3) / 3) * (-3); - } - value *= (Math.pow(10, -exponent)); - if (value >= 1000.0) { - value /= 1000.0; - exponent += 3; - } - if (negative) value *= -1; - String PREFIXES = "yzafpnum KMGTPEZY"; - int prefixLevel = (PREFIXES.length() - 1) / 2; - int siLevel = exponent / 3; - if (Math.abs(siLevel) > prefixLevel) { - Log.e(TAG, "Value Error : Exponent out range of available prefixes."); - return ""; - } else { - String format = "%." + precision + "f %s%s"; - return String.format(format, precision, value, PREFIXES.charAt(siLevel + prefixLevel), unit); - } - } - -} diff --git a/app/src/main/java/io/pslab/communication/CommunicationHandler.java b/app/src/main/java/io/pslab/communication/CommunicationHandler.java deleted file mode 100644 index 14a1ad618..000000000 --- a/app/src/main/java/io/pslab/communication/CommunicationHandler.java +++ /dev/null @@ -1,152 +0,0 @@ -package io.pslab.communication; - -import android.hardware.usb.UsbDevice; -import android.hardware.usb.UsbDeviceConnection; -import android.hardware.usb.UsbManager; -import android.util.Log; - -import com.hoho.android.usbserial.driver.CdcAcmSerialDriver; -import com.hoho.android.usbserial.driver.Cp21xxSerialDriver; -import com.hoho.android.usbserial.driver.ProbeTable; -import com.hoho.android.usbserial.driver.UsbSerialDriver; -import com.hoho.android.usbserial.driver.UsbSerialPort; -import com.hoho.android.usbserial.driver.UsbSerialProber; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -public class CommunicationHandler { - private final String TAG = this.getClass().getSimpleName(); - private static final int PSLAB_VENDOR_ID_V5 = 1240; - private static final int PSLAB_PRODUCT_ID_V5 = 223; - private static final int PSLAB_VENDOR_ID_V6 = 0x10C4; - private static final int PSLAB_PRODUCT_ID_V6 = 0xEA60; - public static int PSLAB_VERSION; - private boolean connected = false, device_found = false; - private UsbManager mUsbManager; - private UsbDeviceConnection mConnection; - private UsbSerialDriver driver; - private UsbSerialPort port; - public UsbDevice mUsbDevice; - List drivers; - - public static final int DEFAULT_READ_BUFFER_SIZE = 32 * 1024; - public static final int DEFAULT_WRITE_BUFFER_SIZE = 32 * 1024; - - private byte[] mReadBuffer; - private byte[] mWriteBuffer; - - public CommunicationHandler(UsbManager usbManager) { - this.mUsbManager = usbManager; - mUsbDevice = null; - ProbeTable customTable = new ProbeTable(); - customTable.addProduct(PSLAB_VENDOR_ID_V5, PSLAB_PRODUCT_ID_V5, CdcAcmSerialDriver.class); - customTable.addProduct(PSLAB_VENDOR_ID_V6, PSLAB_PRODUCT_ID_V6, Cp21xxSerialDriver.class); - - UsbSerialProber prober = new UsbSerialProber(customTable); - drivers = prober.findAllDrivers(usbManager); - - if (drivers.isEmpty()) { - Log.d(TAG, "No drivers found"); - } else { - Log.d(TAG, "Found PSLab device"); - device_found = true; - driver = drivers.get(0); - mUsbDevice = driver.getDevice(); - } - mReadBuffer = new byte[DEFAULT_READ_BUFFER_SIZE]; - mWriteBuffer = new byte[DEFAULT_WRITE_BUFFER_SIZE]; - } - - public void open(int baudRate) throws IOException { - if (!device_found) { - throw new IOException("Device not Connected"); - } - mConnection = mUsbManager.openDevice(mUsbDevice); - if (mConnection == null) { - throw new IOException("Could not open device."); - } - if (mUsbDevice.getProductId() == PSLAB_PRODUCT_ID_V6 && mUsbDevice.getVendorId() == PSLAB_VENDOR_ID_V6) { - PSLAB_VERSION = 6; - } - else { - PSLAB_VERSION = 5; - } - connected = true; - port = driver.getPorts().get(0); - port.open(mConnection); - port.setParameters(baudRate, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); - clear(); - } - - public boolean isDeviceFound() { - return device_found; - } - - public boolean isConnected() { - return connected; - } - - public void close() throws IOException { - if (mConnection == null) { - return; - } - port.close(); - connected = false; - } - - public int read(byte[] dest, int bytesToBeRead, int timeoutMillis) throws IOException { - if (PSLAB_VERSION == 5) { - return readCdcAcm(dest, bytesToBeRead, timeoutMillis); - } - int numBytesRead = 0; - int readNow; - Log.v(TAG, "TO read : " + bytesToBeRead); - int bytesToBeReadTemp = bytesToBeRead; - while (numBytesRead < bytesToBeRead) { - readNow = port.read(mReadBuffer, bytesToBeReadTemp, timeoutMillis); - if (readNow == 0) { - Log.e(TAG, Arrays.toString(Thread.currentThread().getStackTrace())); - Log.e(TAG, "Read Error: " + bytesToBeReadTemp); - return numBytesRead; - } else { - System.arraycopy(mReadBuffer, 0, dest, numBytesRead, readNow); - numBytesRead += readNow; - bytesToBeReadTemp -= readNow; - } - } - Log.v("Bytes Read", "" + numBytesRead); - return numBytesRead; - } - - public int readCdcAcm(byte[] dest, int bytesToBeRead, int timeoutMillis) throws IOException { - int numBytesRead = 0; - int readNow; - Log.v(TAG, "TO read : " + bytesToBeRead); - int bytesToBeReadTemp = bytesToBeRead; - while (numBytesRead < bytesToBeRead) { - readNow = mConnection.bulkTransfer(mUsbDevice.getInterface(1).getEndpoint(1), mReadBuffer, bytesToBeReadTemp, timeoutMillis); - if (readNow < 0) { - Log.e(TAG, "Read Error: " + bytesToBeReadTemp); - return numBytesRead; - } else { - System.arraycopy(mReadBuffer, 0, dest, numBytesRead, readNow); - numBytesRead += readNow; - bytesToBeReadTemp -= readNow; - } - } - Log.v("Bytes Read", "" + numBytesRead); - return numBytesRead; - } - - public void write(byte[] src, int timeoutMillis) throws IOException { - int writeLength; - writeLength = src.length; - port.write(src, writeLength, timeoutMillis); - } - - private void clear() throws IOException { - port.read(mReadBuffer, 100, 50); - } -} diff --git a/app/src/main/java/io/pslab/communication/HttpAsyncTask.java b/app/src/main/java/io/pslab/communication/HttpAsyncTask.java deleted file mode 100644 index 4aae41545..000000000 --- a/app/src/main/java/io/pslab/communication/HttpAsyncTask.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.pslab.communication; - -import android.os.AsyncTask; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.IOException; - -import io.pslab.interfaces.HttpCallback; - -public class HttpAsyncTask extends AsyncTask { - - private HttpHandler mHttpHandler; - private HttpCallback mHttpCallback; - - public HttpAsyncTask(String baseIP, HttpCallback httpCallback) { - mHttpHandler = new HttpHandler(baseIP); - mHttpCallback = httpCallback; - } - - @Override - protected Void doInBackground(byte[]... data) { - int res = 0; - try { - if (data.length != 0) { - res = mHttpHandler.write(data[0]); - - } else { - res = mHttpHandler.read(); - } - } catch (IOException | JSONException e) { - mHttpCallback.error(e); - e.printStackTrace(); - } - if (res == 1) { - mHttpCallback.success(mHttpHandler.getReceivedData()); - } else { - mHttpCallback.error(new Exception()); - } - return null; - } -} diff --git a/app/src/main/java/io/pslab/communication/HttpHandler.java b/app/src/main/java/io/pslab/communication/HttpHandler.java deleted file mode 100644 index a2f7bed38..000000000 --- a/app/src/main/java/io/pslab/communication/HttpHandler.java +++ /dev/null @@ -1,87 +0,0 @@ -package io.pslab.communication; - -import android.util.Log; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.IOException; -import java.net.URL; - -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; - -public class HttpHandler { - - private final String TAG = this.getClass().getSimpleName(); - private String baseIP; - private String sendDataEndPoint = "send"; - private String getDataEndPoint = "get"; - private String dataKeyString = "data"; - private OkHttpClient client; - private JSONObject receivedData; - - public HttpHandler(String baseIP) { - this.baseIP = baseIP; - this.client = new OkHttpClient(); - } - - /** - * Method to send data to ESP - * - * @param data data to be sent in byte array - * @return 1 if response code is "200" 0 otherwise; - */ - public int write(byte[] data) throws IOException, JSONException { - int result = 1; - URL baseURL = new URL("http://" + baseIP + "/" + sendDataEndPoint); - int written = 0; - JSONArray responseArray = new JSONArray(); - while (written < data.length) { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(dataKeyString, data[written]); - RequestBody body = RequestBody.create(jsonObject.toString(), MediaType.get("application/json; charset=utf-8")); - Request request = new Request.Builder() - .url(baseURL) - .post(body) - .build(); - Response response = client.newCall(request).execute(); - responseArray.put(new JSONObject(response.body().string())); - if (response.code() != 200) { - Log.e(TAG, "Error writing byte:" + written); - return 0; - } - written++; - } - receivedData = new JSONObject(responseArray.toString()); - return result; - } - - /** - * Method to get data from ESP - * @return 1 if data was received 0 otherwise - */ - public int read() throws IOException, JSONException { - int result = 1; - URL baseURL = new URL("http://" + baseIP + "/" + getDataEndPoint); - Request request = new Request.Builder() - .url(baseURL) - .build(); - Response response = client.newCall(request).execute(); - if (response.code() != 200) { - Log.e(TAG, "Error reading data"); - return 0; - } else { - receivedData = new JSONObject(response.body().string()); - } - return result; - } - - public JSONObject getReceivedData() { - return receivedData; - } -} diff --git a/app/src/main/java/io/pslab/communication/PacketHandler.java b/app/src/main/java/io/pslab/communication/PacketHandler.java deleted file mode 100644 index 709b26659..000000000 --- a/app/src/main/java/io/pslab/communication/PacketHandler.java +++ /dev/null @@ -1,295 +0,0 @@ -package io.pslab.communication; - -import android.util.Log; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; - -import io.pslab.interfaces.HttpCallback; -import io.pslab.others.ScienceLabCommon; - -/** - * Created by viveksb007 on 28/3/17. - */ - -public class PacketHandler { - - private static final String TAG = "PacketHandler"; - private final int BUFSIZE = 10000; - private byte[] buffer = new byte[BUFSIZE]; - private boolean loadBurst, connected; - private int inputQueueSize = 0, BAUD = 1000000; - private CommunicationHandler mCommunicationHandler = null; - public static String version = ""; - private CommandsProto mCommandsProto; - private int timeout = 500, VERSION_STRING_LENGTH = 8, FW_VERSION_LENGTH = 3; - public static int PSLAB_FW_VERSION = 0; - ByteBuffer burstBuffer = ByteBuffer.allocate(2000); - private HttpAsyncTask httpAsyncTask; - - public PacketHandler(int timeout, CommunicationHandler communicationHandler) { - this.loadBurst = false; - this.connected = false; - this.timeout = timeout; - this.mCommandsProto = new CommandsProto(); - this.mCommunicationHandler = communicationHandler; - connected = (mCommunicationHandler.isConnected() || ScienceLabCommon.isWifiConnected()); - } - - public boolean isConnected() { - connected = (mCommunicationHandler.isConnected() || ScienceLabCommon.isWifiConnected()); - return connected; - } - - public String getVersion() { - try { - sendByte(mCommandsProto.COMMON); - sendByte(mCommandsProto.GET_VERSION); - // Read "\n" - commonRead(VERSION_STRING_LENGTH + 1); - // Only use first line, just like in the Python implementation. - version = new BufferedReader( - new InputStreamReader( - new ByteArrayInputStream(buffer, 0, VERSION_STRING_LENGTH), - StandardCharsets.UTF_8)) - .readLine(); - } catch (IOException e) { - Log.e("Error in Communication", e.toString()); - } - return version; - } - - public int getFirmwareVersion() { - try { - sendByte(mCommandsProto.COMMON); - sendByte(mCommandsProto.GET_FW_VERSION); - int numByteRead = commonRead(FW_VERSION_LENGTH); - if (numByteRead == 1) { - return 2; - } else { - return buffer[0]; - } - } catch (IOException e) { - Log.e("Error in Communication", e.toString()); - } - return 0; - } - - public String readLine() { - String line = ""; - try { - commonRead(CommunicationHandler.DEFAULT_READ_BUFFER_SIZE); - line = new BufferedReader( - new InputStreamReader( - new ByteArrayInputStream(buffer, 0, CommunicationHandler.DEFAULT_READ_BUFFER_SIZE), - StandardCharsets.UTF_8)) - .readLine(); - return line; - } catch (IOException e) { - Log.e("Error in Communication", e.toString()); - } - return line; - } - - public void sendByte(int val) throws IOException { - if (!connected) { - throw new IOException("Device not connected"); - } - if (!loadBurst) { - try { - commonWrite(new byte[]{(byte) (val & 0xff)}); - } catch (IOException | NullPointerException e) { - Log.e("Error in sending byte", e.toString()); - e.printStackTrace(); - } - } else { - burstBuffer.put((byte) (val & 0xff)); - } - } - - public void sendInt(int val) throws IOException { - if (!connected) { - throw new IOException("Device not connected"); - } - if (!loadBurst) { - try { - commonWrite(new byte[]{(byte) (val & 0xff), (byte) ((val >> 8) & 0xff)}); - } catch (IOException e) { - Log.e("Error in sending int", e.toString()); - e.printStackTrace(); - } - } else { - burstBuffer.put(new byte[]{(byte) (val & 0xff), (byte) ((val >> 8) & 0xff)}); - } - } - - public int getAcknowledgement() { - /* - fetches the response byte - 1 SUCCESS - 2 ARGUMENT_ERROR - 3 FAILED - used as a handshake - */ - if (loadBurst) { - inputQueueSize++; - return 1; - } else { - try { - commonRead(1); - return buffer[0]; - } catch (IOException | NullPointerException e) { - e.printStackTrace(); - return 3; - } - } - } - - public byte getByte() { - try { - int numByteRead = commonRead(1); - if (numByteRead == 1) { - return buffer[0]; - } else { - Log.e(TAG, "Error in reading byte"); - } - } catch (IOException e) { - e.printStackTrace(); - } - return -1; - } - - int getVoltageSummation() { - try { - // Note : bytesToBeRead has to be +1 than the requirement - int numByteRead = commonRead(3); - if (numByteRead == 3) { - return (buffer[0] & 0xff) | ((buffer[1] << 8) & 0xff00); - } else { - Log.e(TAG, "Error in reading byte"); - } - } catch (IOException e) { - e.printStackTrace(); - } - return -1; - } - - public int getInt() { - try { - int numByteRead = commonRead(2); - if (numByteRead == 2) { - // LSB is read first - return (buffer[0] & 0xff) | ((buffer[1] << 8) & 0xff00); - } else { - Log.e(TAG, "Error in reading byte"); - } - } catch (IOException e) { - e.printStackTrace(); - } - return -1; - } - - public long getLong() { - try { - int numByteRead = commonRead(4); - if (numByteRead == 4) { - // C++ has long of 4-bytes but in Java int has 4-bytes - // refer "https://stackoverflow.com/questions/7619058/convert-a-byte-array-to-integer-in-java-and-vice-versa" for Endian - return ByteBuffer.wrap(Arrays.copyOfRange(buffer, 0, 4)).order(ByteOrder.LITTLE_ENDIAN).getInt(); - } else { - Log.e(TAG, "Error in reading byte"); - } - } catch (IOException e) { - e.printStackTrace(); - } - return -1; - } - - public boolean waitForData() { - return false; - } - - public int read(byte[] dest, int bytesToRead) throws IOException { - int numBytesRead = commonRead(bytesToRead); - for (int i = 0; i < bytesToRead; i++) { - dest[i] = buffer[i]; - } - if (numBytesRead == bytesToRead) { - return numBytesRead; - } else { - Log.e(TAG, "Error in packetHandler Reading"); - } - return -1; - } - - public byte[] sendBurst() { - try { - commonWrite(burstBuffer.array()); - burstBuffer.clear(); - loadBurst = false; - int bytesRead = commonRead(inputQueueSize); - inputQueueSize = 0; - return Arrays.copyOfRange(buffer, 0, bytesRead); - } catch (IOException e) { - e.printStackTrace(); - } - return new byte[]{-1}; - } - - public int commonRead(int bytesToRead) throws IOException { - final int[] bytesRead = {0}; - if (mCommunicationHandler.isConnected()) { - bytesRead[0] = mCommunicationHandler.read(buffer, bytesToRead, timeout); - } else if (ScienceLabCommon.isWifiConnected()) { - httpAsyncTask = new HttpAsyncTask(ScienceLabCommon.getEspIP(), new HttpCallback() { - @Override - public void success(JSONObject jsonObject) { - try { - //Server will send byte array - buffer = (byte[]) jsonObject.get("data"); - bytesRead[0] = buffer.length; - } catch (JSONException e) { - e.printStackTrace(); - } - } - - @Override - public void error(Exception e) { - Log.e(TAG, "Error reading data over ESP"); - } - }); - httpAsyncTask.execute(new byte[]{}); - } - return bytesRead[0]; - } - - public void commonWrite(byte[] data) throws IOException { - if (mCommunicationHandler.isConnected()) { - mCommunicationHandler.write(data, timeout); - } else if (ScienceLabCommon.isWifiConnected()) { - httpAsyncTask = new HttpAsyncTask(ScienceLabCommon.getEspIP(), new HttpCallback() { - @Override - public void success(JSONObject jsonObject) { - Log.v(TAG, "write response:" + jsonObject.toString()); - } - - @Override - public void error(Exception e) { - Log.e(TAG, "Error writing data over ESP"); - } - }); - - httpAsyncTask.execute(data); - } - - } -} diff --git a/app/src/main/java/io/pslab/communication/ScienceLab.java b/app/src/main/java/io/pslab/communication/ScienceLab.java deleted file mode 100644 index 7b8430d1c..000000000 --- a/app/src/main/java/io/pslab/communication/ScienceLab.java +++ /dev/null @@ -1,2932 +0,0 @@ -package io.pslab.communication; - -import static java.lang.Math.pow; -import static io.pslab.others.MathUtils.linSpace; - -import android.os.Build; -import android.os.Handler; -import android.os.Looper; -import android.util.Log; - - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; - -import io.pslab.activity.MainActivity; -import io.pslab.communication.analogChannel.AnalogAquisitionChannel; -import io.pslab.communication.analogChannel.AnalogConstants; -import io.pslab.communication.analogChannel.AnalogInputSource; -import io.pslab.communication.digitalChannel.DigitalChannel; -import io.pslab.communication.peripherals.DACChannel; -import io.pslab.communication.peripherals.I2C; -import io.pslab.fragment.HomeFragment; -import io.pslab.others.InitializationVariable; - -/** - * Created by viveksb007 on 28/3/17. - */ - -public class ScienceLab { - - private static final String TAG = "ScienceLab"; - public static Thread initialisationThread; - public int DDS_CLOCK, MAX_SAMPLES, samples, triggerLevel, triggerChannel, errorCount, - channelsInBuffer, digitalChannelsInBuffer, dataSplitting; - public double sin1Frequency, sin2Frequency; - double[] currents, gainValues, buffer; - int[] currentScalars; - double SOCKET_CAPACITANCE, resistanceScaling, timebase; - private static final double CAPACITOR_DISCHARGE_VOLTAGE = 0.01 * 3.3; - private static final int CTMU_CHANNEL = 0b11110; - public boolean streaming; - String[] allAnalogChannels, allDigitalChannels; - HashMap analogInputSources = new HashMap<>(); - HashMap squareWaveFrequency = new HashMap<>(); - HashMap gains = new HashMap<>(); - HashMap waveType = new HashMap<>(); - ArrayList aChannels = new ArrayList<>(); - ArrayList dChannels = new ArrayList<>(); - public Map dacChannels = new LinkedHashMap<>(); - private Map values = new LinkedHashMap<>(); - - private CommunicationHandler mCommunicationHandler; - private PacketHandler mPacketHandler; - private CommandsProto mCommandsProto; - private AnalogConstants mAnalogConstants; - private int LAChannelFrequency; - public I2C i2c; - - /** - * Constructor - * - * @param communicationHandler - */ - public ScienceLab(CommunicationHandler communicationHandler) { - mCommandsProto = new CommandsProto(); - mAnalogConstants = new AnalogConstants(); - mCommunicationHandler = communicationHandler; - if (isDeviceFound() && MainActivity.hasPermission) { - try { - mCommunicationHandler.open(1000000); - //Thread.sleep(200); - mPacketHandler = new PacketHandler(50, mCommunicationHandler); - } catch (IOException | NullPointerException e) { - e.printStackTrace(); - } - } - if (isConnected()) { - initializeVariables(); - new Handler().postDelayed(new Runnable() { - @Override - public void run() { - initialisationThread = new Thread(new Runnable() { - - @Override - public void run() { - try { - runInitSequence(); - } catch (IOException e) { - e.printStackTrace(); - } - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - if (HomeFragment.booleanVariable == null) { - HomeFragment.booleanVariable = new InitializationVariable(); - } - HomeFragment.booleanVariable.setVariable(true); - } - }); - } - }); - initialisationThread.start(); - - } - }, 1000); - } - } - - private void initializeVariables() { - DDS_CLOCK = 0; - timebase = 40; - MAX_SAMPLES = mCommandsProto.MAX_SAMPLES; - samples = MAX_SAMPLES; - triggerChannel = 0; - triggerLevel = 550; - errorCount = 0; - channelsInBuffer = 0; - digitalChannelsInBuffer = 0; - currents = new double[]{0.55e-3, 0.55e-6, 0.55e-5, 0.55e-4}; - currentScalars = new int[]{1, 2, 3, 0}; - dataSplitting = mCommandsProto.DATA_SPLITTING; - allAnalogChannels = mAnalogConstants.allAnalogChannels; - LAChannelFrequency = 0; - for (String aChannel : allAnalogChannels) { - analogInputSources.put(aChannel, new AnalogInputSource(aChannel)); - } - sin1Frequency = 0; - sin2Frequency = 0; - squareWaveFrequency.put("SQR1", 0.0); - squareWaveFrequency.put("SQR2", 0.0); - squareWaveFrequency.put("SQR3", 0.0); - squareWaveFrequency.put("SQR4", 0.0); - if (CommunicationHandler.PSLAB_VERSION == 6) { - dacChannels.put("PCS", new DACChannel("PCS", new double[]{0, 3.3}, 0, 0)); - dacChannels.put("PV3", new DACChannel("PV3", new double[]{0, 3.3}, 1, 1)); - dacChannels.put("PV2", new DACChannel("PV2", new double[]{-3.3, 3.3}, 2, 0)); - dacChannels.put("PV1", new DACChannel("PV1", new double[]{-5., 5.}, 3, 1)); - } else { - dacChannels.put("PCS", new DACChannel("PCS", new double[]{0, 3.3}, 0, 0)); - dacChannels.put("PV3", new DACChannel("PV3", new double[]{0, 3.3}, 1, 1)); - dacChannels.put("PV2", new DACChannel("PV2", new double[]{-3.3, 3.3}, 2, 2)); - dacChannels.put("PV1", new DACChannel("PV1", new double[]{-5., 5.}, 3, 3)); - } - values.put("PV1", 0.); - values.put("PV2", 0.); - values.put("PV3", 0.); - values.put("PCS", 0.); - } - - private void runInitSequence() throws IOException { - fetchFirmwareVersion(); - ArrayList aboutArray = new ArrayList<>(); - if (!isConnected()) { - Log.e(TAG, "Check hardware connections. Not connected"); - } - streaming = false; - for (String aChannel : mAnalogConstants.biPolars) { - aChannels.add(new AnalogAquisitionChannel(aChannel)); - } - gainValues = mAnalogConstants.gains; - this.buffer = new double[10000]; - Arrays.fill(this.buffer, 0); - SOCKET_CAPACITANCE = 46e-12; - resistanceScaling = 1; - allDigitalChannels = DigitalChannel.digitalChannelNames; - gains.put("CH1", 0); - gains.put("CH2", 0); - for (int i = 0; i < 4; i++) { - dChannels.add(new DigitalChannel(i)); - } - i2c = new I2C(mPacketHandler); - if (isConnected()) { - for (String temp : new String[]{"CH1", "CH2"}) { - this.setGain(temp, 0, true); - } - for (String temp : new String[]{"SI1", "SI2"}) { - loadEquation(temp, "sine"); - } - } - this.clearBuffer(0, samples); - } - - /** - * @return Resistance of connected resistor between RES an GND pins - */ - public Double getResistance() { - double volt = this.getAverageVoltage("RES", null); - if (volt > 3.295) return null; - double current = (3.3 - volt) / 5.1e3; - return (volt / current) * this.resistanceScaling; - } - - public String getVersion() throws IOException { - if (isConnected()) { - return mPacketHandler.getVersion(); - } else { - return "Not Connected"; - } - } - - public void fetchFirmwareVersion() { - if (isConnected()) { - PacketHandler.PSLAB_FW_VERSION = mPacketHandler.getFirmwareVersion(); - if (PacketHandler.PSLAB_FW_VERSION == 2) { - MainActivity.getInstance().runOnUiThread(new Runnable() { - @Override - public void run() { - MainActivity.getInstance().showFirmwareDialog(); - } - }); - } - } - } - - public void close() { - try { - mCommunicationHandler.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private void captureFullSpeedHrInitialize(String channel, int samples, double timeGap, List args) { - timeGap = (int) (timeGap * 8) / 8; - if (timeGap < 0.5) timeGap = (int) (0.5 * 8) / 8; - if (samples > this.MAX_SAMPLES) { - Log.v(TAG, "Sample limit exceeded. 10,000 max"); - samples = this.MAX_SAMPLES; - } - this.timebase = (int) (timeGap * 8) / 8; - this.samples = samples; - int CHOSA = this.analogInputSources.get(channel).CHOSA; - - try { - mPacketHandler.sendByte(mCommandsProto.ADC); - if (args.contains("SET_LOW")) - mPacketHandler.sendByte(mCommandsProto.SET_LO_CAPTURE); - else if (args.contains("SET_HIGH")) - mPacketHandler.sendByte(mCommandsProto.SET_HI_CAPTURE); - else if (args.contains("READ_CAP")) { - mPacketHandler.sendByte(mCommandsProto.MULTIPOINT_CAPACITANCE); - } else - mPacketHandler.sendByte(mCommandsProto.CAPTURE_DMASPEED); - mPacketHandler.sendByte(CHOSA | 0x80); - mPacketHandler.sendInt(samples); - mPacketHandler.sendInt((int) timeGap * 8); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * @param channel Channel name 'CH1' / 'CH2' ... 'RES' - * @param samples Number of samples to fetch. Maximum 10000/(total specified channels) - * @param timeGap Timegap between samples in microseconds. - * @param args timestamp array ,voltage_value array - * @return Timestamp array ,voltage_value array - */ - public Map captureFullSpeedHr(String channel, int samples, double timeGap, List args) { - this.captureFullSpeedHrInitialize(channel, samples, timeGap, args); - try { - Thread.sleep((long) (1e-6 * this.samples * this.timebase + 0.1)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Map axisData = retrieveBufferData(channel, this.samples, this.timebase); - if (axisData == null) { - Log.v(TAG, "Retrieved Buffer Data as null"); - return null; - } - Map retData = new HashMap<>(); - retData.put("x", axisData.get("x")); - retData.put("y", this.analogInputSources.get(channel).cal12(axisData.get("y"))); - return retData; - } - - private Map retrieveBufferData(String channel, int samples, double timeGap) { - ArrayList listData = new ArrayList<>(); - try { - for (int i = 0; i < samples / this.dataSplitting; i++) { - mPacketHandler.sendByte(mCommandsProto.ADC); - mPacketHandler.sendByte(mCommandsProto.GET_CAPTURE_CHANNEL); - mPacketHandler.sendByte(0); - mPacketHandler.sendInt(this.dataSplitting); - mPacketHandler.sendInt(i * this.dataSplitting); - byte[] data = new byte[this.dataSplitting * 2 + 1]; - mPacketHandler.read(data, this.dataSplitting * 2 + 1); - for (int j = 0; j < data.length - 1; j++) - listData.add((int) data[j] & 0xff); - } - - if ((samples % this.dataSplitting) != 0) { - mPacketHandler.sendByte(mCommandsProto.ADC); - mPacketHandler.sendByte(mCommandsProto.GET_CAPTURE_CHANNEL); - mPacketHandler.sendByte(0); - mPacketHandler.sendInt(samples * this.dataSplitting); - mPacketHandler.sendInt(samples - samples % this.dataSplitting); - byte[] data = new byte[2 * (samples % this.dataSplitting)]; - mPacketHandler.read(data, 2 * (samples % this.dataSplitting)); - for (int j = 0; j < data.length - 1; j++) - listData.add((int) data[j] & 0xff); - } - - for (int i = 0; i < samples; i++) { - this.buffer[i] = (listData.get(i * 2) | (listData.get(i * 2 + 1) << 8)); - } - - double[] timeAxis = linSpace(0, timeGap * (samples - 1), samples); - Map retData = new HashMap<>(); - retData.put("x", timeAxis); - retData.put("y", Arrays.copyOfRange(buffer, 0, samples)); - return retData; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Instruct the ADC to start sampling. use fetchTrace to retrieve the data - * - * @param number Channels to acquire. 1/2/4 - * @param samples Total points to store per channel. Maximum 3200 total - * @param timeGap Timegap between two successive samples (in uSec) - * @param channelOneInput Map channel 1 to 'CH1' - * @param trigger Whether or not to trigger the oscilloscope based on the voltage level set - * @param CH123SA - */ - public void captureTraces(int number, int samples, double timeGap, String channelOneInput, Boolean trigger, Integer CH123SA) { - if (CH123SA == null) CH123SA = 0; - if (channelOneInput == null) channelOneInput = "CH1"; - this.timebase = timeGap; - this.timebase = (int) (this.timebase * 8) / 8; - if (!this.analogInputSources.containsKey(channelOneInput)) { - Log.e(TAG, "Invalid input channel"); - return; - } - int CHOSA = this.analogInputSources.get(channelOneInput).CHOSA; - this.aChannels.get(0).setParams(channelOneInput, samples, 0, this.timebase, 10, this.analogInputSources.get(channelOneInput), null); - try { - mPacketHandler.sendByte(mCommandsProto.ADC); - if (number == 1) { - if (timeGap < 0.5) - this.timebase = (int) (0.5 * 8) / 8; - if (samples > this.MAX_SAMPLES) - samples = this.MAX_SAMPLES; - if (trigger) { - if (timeGap < 0.75) - this.timebase = (int) (0.75 * 8) / 8; - mPacketHandler.sendByte(mCommandsProto.CAPTURE_ONE); - mPacketHandler.sendByte(CHOSA | 0x80); - } else if (timeGap > 1) { - this.aChannels.get(0).setParams(channelOneInput, samples, 0, this.timebase, 12, this.analogInputSources.get(channelOneInput), null); - mPacketHandler.sendByte(mCommandsProto.CAPTURE_DMASPEED); - mPacketHandler.sendByte(CHOSA | 0x80); - } else { - mPacketHandler.sendByte(mCommandsProto.CAPTURE_DMASPEED); - mPacketHandler.sendByte(CHOSA); - } - } else if (number == 2) { - if (timeGap < 0.875) - this.timebase = (int) (0.875 * 8) / 8; - if (samples > this.MAX_SAMPLES / 2) - samples = this.MAX_SAMPLES / 2; - this.aChannels.get(1).setParams("CH2", samples, samples, this.timebase, 10, this.analogInputSources.get("CH2"), null); - mPacketHandler.sendByte(mCommandsProto.CAPTURE_TWO); - mPacketHandler.sendByte(CHOSA | (0x80 * (trigger ? 1 : 0))); - } else { - if (timeGap < 1.75) - this.timebase = (int) (1.75 * 8) / 8; - if (samples > this.MAX_SAMPLES / 4) - samples = this.MAX_SAMPLES / 4; - int i = 1; - for (String temp : new String[]{"CH2", "CH3", "MIC"}) { - this.aChannels.get(i).setParams(temp, samples, i * samples, this.timebase, 10, this.analogInputSources.get(temp), null); - i++; - } - mPacketHandler.sendByte(mCommandsProto.CAPTURE_FOUR); - mPacketHandler.sendByte(CHOSA | (CH123SA << 4) | (0x80 * (trigger ? 1 : 0))); - } - this.samples = samples; - mPacketHandler.sendInt(samples); - mPacketHandler.sendInt((int) this.timebase * 8); - mPacketHandler.getAcknowledgement(); - this.channelsInBuffer = number; - } catch (IOException e) { - e.printStackTrace(); - } - - } - - /** - * Fetches a channel(1-4) captured by :func:captureTraces called prior to this, and returns xAxis,yAxis - * - * @param channelNumber Any of the maximum of four channels that the oscilloscope captured. 1/2/3/4 - * @return time array,voltage array - */ - public HashMap fetchTrace(int channelNumber) { - this.fetchData(channelNumber); - HashMap retData = new HashMap<>(); - retData.put("x", this.aChannels.get(channelNumber - 1).getXAxis()); - retData.put("y", this.aChannels.get(channelNumber - 1).getYAxis()); - return retData; - } - - /** - * Returns the number of samples acquired by the capture routines, and the conversion_done status - * - * @return conversion done(bool) ,samples acquired (number) - */ - public int[] oscilloscopeProgress() { - /* - * returns the number of samples acquired by the capture routines, and the conversion_done status - * - * return structure int[]{conversionDone, samples} - */ - - int conversionDone = 0; - int samples = 0; - try { - mPacketHandler.sendByte(mCommandsProto.ADC); - mPacketHandler.sendByte(mCommandsProto.GET_CAPTURE_STATUS); - conversionDone = (int) mPacketHandler.getByte() & 0xff; - samples = mPacketHandler.getInt(); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - return new int[]{conversionDone, samples}; - } - - private boolean fetchData(int channelNumber) { - int samples = this.aChannels.get(channelNumber - 1).length; - if (channelNumber > this.channelsInBuffer) { - Log.v(TAG, "Channel Unavailable"); - return false; - } - Log.v("Samples", "" + samples); - Log.v("Data Splitting", "" + this.dataSplitting); - ArrayList listData = new ArrayList<>(); - try { - for (int i = 0; i < samples / this.dataSplitting; i++) { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.RETRIEVE_BUFFER); - mPacketHandler.sendInt(this.aChannels.get(channelNumber - 1).bufferIndex + (i * this.dataSplitting)); - mPacketHandler.sendInt(this.dataSplitting); - byte[] data = new byte[this.dataSplitting * 2 + 1]; - mPacketHandler.read(data, this.dataSplitting * 2 + 1); - for (int j = 0; j < data.length - 1; j++) - listData.add((int) data[j] & 0xff); - } - - if ((samples % this.dataSplitting) != 0) { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.RETRIEVE_BUFFER); - mPacketHandler.sendInt(this.aChannels.get(channelNumber - 1).bufferIndex + samples - samples % this.dataSplitting); - mPacketHandler.sendInt(samples % this.dataSplitting); - byte[] data = new byte[2 * (samples % this.dataSplitting) + 1]; - mPacketHandler.read(data, 2 * (samples % this.dataSplitting) + 1); - for (int j = 0; j < data.length - 1; j++) - listData.add((int) data[j] & 0xff); - } - - } catch (IOException e) { - e.printStackTrace(); - return false; - } - - for (int i = 0; i < listData.size() / 2; i++) { - this.buffer[i] = (listData.get(i * 2)) | (listData.get(i * 2 + 1) << 8); - while (this.buffer[i] > 1023) this.buffer[i] -= 1023; - } - - Log.v("RAW DATA:", Arrays.toString(Arrays.copyOfRange(buffer, 0, samples))); - - this.aChannels.get(channelNumber - 1).yAxis = this.aChannels.get(channelNumber - 1).fixValue(Arrays.copyOfRange(this.buffer, 0, samples)); - return true; - } - - /** - * Configure trigger parameters for 10-bit capture commands - * The capture routines will wait till a rising edge of the input signal crosses the specified level. - * The trigger will timeout within 8mS, and capture routines will start regardless. - * These settings will not be used if the trigger option in the capture routines are set to False - * - * @param channel Channel 0,1,2,3. Corresponding to the channels being recorded by the capture routine(not the analog inputs) - * @param channelName Name of the channel. 'CH1','CH2','CH3','MIC','V+' - * @param voltage The voltage level that should trigger the capture sequence(in Volts) - * @param resolution - * @param prescalar - */ - public void configureTrigger(int channel, String channelName, double voltage, Integer resolution, Integer prescalar) { - if (resolution == null) resolution = 10; - if (prescalar == null) prescalar = 0; - try { - mPacketHandler.sendByte(mCommandsProto.ADC); - mPacketHandler.sendByte(mCommandsProto.CONFIGURE_TRIGGER); - mPacketHandler.sendByte((prescalar << 4) | (1 << channel)); - double level; - if (resolution == 12) { - level = this.analogInputSources.get(channelName).voltToCode12.value(voltage); - if (level < 0) level = 0; - else if (level > 4095) level = 4095; - } else { - level = this.analogInputSources.get(channelName).voltToCode10.value(voltage); - if (level < 0) level = 0; - else if (level > 1023) level = 1023; - } - if (level > pow(2, resolution - 1)) - level = pow(2, resolution - 1); - else if (level < 0) - level = 0; - mPacketHandler.sendInt((int) level); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Set the gain of the selected PGA - * - * @param channel 'CH1','CH2' - * @param gain (0-8) -> (1x,2x,4x,5x,8x,10x,16x,32x,1/11x) - * @param force If True, the amplifier gain will be set even if it was previously set to the same value. - * @return - */ - public double setGain(String channel, int gain, Boolean force) { - if (force == null) force = false; - if (gain < 0 || gain > 8) { - Log.v(TAG, "Invalid gain parameter. 0-7 only."); - return 0; - } - if (this.analogInputSources.get(channel).gainPGA == -1) { - Log.v(TAG, "No amplifier exists on this channel : " + channel); - return 0; - } - boolean refresh = false; - if (this.gains.get(channel) != gain) { - this.gains.put(channel, gain); - refresh = true; - } - if (refresh || force) { - analogInputSources.get(channel).setGain(gain); // giving index of gainValues - if (gain > 7) gain = 0; - try { - mPacketHandler.sendByte(mCommandsProto.ADC); - mPacketHandler.sendByte(mCommandsProto.SET_PGA_GAIN); - mPacketHandler.sendByte(analogInputSources.get(channel).gainPGA); - mPacketHandler.sendByte(gain); - mPacketHandler.getAcknowledgement(); - return this.gainValues[gain]; - } catch (IOException e) { - e.printStackTrace(); - } - } - return 0; - } - - /** - * set the gain of the selected PGA - * - * @param channel 'CH1','CH2' - * @param voltageRange Choose from [16,8,4,3,2,1.5,1,.5,160] - * @return - */ - public Double selectRange(String channel, double voltageRange) { - double[] ranges = new double[]{16, 8, 4, 3, 2, 1.5, 1, .5, 160}; - if (Arrays.asList(ArrayUtils.toObject(ranges)).contains(voltageRange)) { - return this.setGain(channel, Arrays.asList(ArrayUtils.toObject(ranges)).indexOf(voltageRange), null); - } else - Log.e(TAG, "Not a valid Range"); - return null; - } - - private int calcCHOSA(String channelName) { - channelName = channelName.toUpperCase(); - AnalogInputSource source = analogInputSources.get(channelName); - boolean found = false; - for (String temp : allAnalogChannels) { - if (temp.equals(channelName)) { - found = true; - break; - } - } - if (!found) { - Log.e(TAG, "Not a valid channel name. selecting CH1"); - return calcCHOSA("CH1"); - } - - return source.CHOSA; - } - - public double getVoltage(String channelName, Integer sample) { - this.voltmeterAutoRange(channelName); - double Voltage = this.getAverageVoltage(channelName, sample); - if (channelName.equals("CH2") || channelName.equals("CH1")) { - return 2 * Voltage; - } else { - return Voltage; - } - } - - private void voltmeterAutoRange(String channelName) { - if (this.analogInputSources.get(channelName).gainPGA != 0) { - this.setGain(channelName, 0, true); - } - } - - /** - * Return the voltage on the selected channel - * - * @param channelName : 'CH1','CH2','CH3','MIC','IN1','RES','V+' - * @param sample Samples to average - * @return Voltage on the selected channel - */ - private double getAverageVoltage(String channelName, Integer sample) { - if (sample == null) sample = 1; - PolynomialFunction poly; - double sum = 0; - poly = analogInputSources.get(channelName).calPoly12; - ArrayList vals = new ArrayList<>(); - for (int i = 0; i < sample; i++) { - vals.add(getRawAverageVoltage(channelName)); - } - for (int j = 0; j < vals.size(); j++) { - sum = sum + poly.value(vals.get(j)); - } - return sum / 2 * vals.size(); - } - - private double getRawAverageVoltage(String channelName) { - try { - int chosa = this.calcCHOSA(channelName); - mPacketHandler.sendByte(mCommandsProto.ADC); - mPacketHandler.sendByte(mCommandsProto.GET_VOLTAGE_SUMMED); - mPacketHandler.sendByte(chosa); - int vSum = mPacketHandler.getVoltageSummation(); - return vSum / 16.0; - } catch (IOException | NullPointerException e) { - e.printStackTrace(); - Log.e(TAG, "Error in getRawAverageVoltage"); - } - return 0; - } - - /** - * Fetches a section of the ADC hardware buffer - * - * @param startingPosition Starting index - * @param totalPoints Total points to fetch - */ - private void fetchBuffer(int startingPosition, int totalPoints) { - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.RETRIEVE_BUFFER); - mPacketHandler.sendInt(startingPosition); - mPacketHandler.sendInt(totalPoints); - for (int i = 0; i < totalPoints; i++) { - byte[] data = new byte[2]; - mPacketHandler.read(data, 2); - this.buffer[i] = (data[0] & 0xff) | ((data[1] << 8) & 0xff00); - } - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - Log.e(TAG, "Error in fetching buffer"); - } - } - - /** - * Clears a section of the ADC hardware buffer - * - * @param startingPosition Starting index - * @param totalPoints Total points to fetch - */ - private void clearBuffer(int startingPosition, int totalPoints) { - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.CLEAR_BUFFER); - mPacketHandler.sendInt(startingPosition); - mPacketHandler.sendInt(totalPoints); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - Log.e(TAG, "Error in clearing buffer"); - } - } - - /** - * Fill a section of the ADC hardware buffer with data - * - * @param startingPosition Starting index - * @param pointArray Total points to fetch - */ - private void fillBuffer(int startingPosition, int[] pointArray) { - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.FILL_BUFFER); - mPacketHandler.sendInt(startingPosition); - mPacketHandler.sendInt(pointArray.length); - for (int aPointArray : pointArray) { - mPacketHandler.sendInt(aPointArray); - } - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - Log.e(TAG, "Error in filling Buffer"); - } - - } - - public void setDataSplitting(int dataSplitting) { - this.dataSplitting = dataSplitting; - } - - /** - * Checks if PSLab device is found - * - * @return true is device found; false otherwise - */ - public boolean isDeviceFound() { - return mCommunicationHandler.isDeviceFound(); - } - - /** - * Checks if PSLab device is connected - * - * @return true is device is connected; false otherwise - */ - public boolean isConnected() { - return mCommunicationHandler.isConnected(); - } - - /* DIGITAL SECTION */ - - public Integer calculateDigitalChannel(String name) { - if (Arrays.asList(DigitalChannel.digitalChannelNames).contains(name)) - return Arrays.asList(DigitalChannel.digitalChannelNames).indexOf(name); - else { - Log.v(TAG, "Invalid channel " + name + " , selecting LA1 instead "); - return null; - } - } - - private Double getHighFrequencyBackup(String pin) { - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.GET_HIGH_FREQUENCY); - mPacketHandler.sendByte(this.calculateDigitalChannel(pin)); - int scale = mPacketHandler.getByte(); - long value = mPacketHandler.getLong(); - mPacketHandler.getAcknowledgement(); - return scale * value / 1.0e-1; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Retrieves the frequency of the signal connected to LA1. For frequencies > 1MHz - * Also good for lower frequencies, but avoid using it since the oscilloscope cannot be used simultaneously due to hardware limitations. - * The input frequency is fed to a 32 bit counter for a period of 100mS. - * The value of the counter at the end of 100mS is used to calculate the frequency. - * - * @param pin The input pin to measure frequency from : ['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @return frequency - */ - public Double getHighFrequency(String pin) { - /* - Retrieves the frequency of the signal connected to LA1. for frequencies > 1MHz - also good for lower frequencies, but avoid using it since - the oscilloscope cannot be used simultaneously due to hardware limitations. - The input frequency is fed to a 32 bit counter for a period of 100mS. - The value of the counter at the end of 100mS is used to calculate the frequency. - */ - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.GET_ALTERNATE_HIGH_FREQUENCY); - mPacketHandler.sendByte(this.calculateDigitalChannel(pin)); - int scale = mPacketHandler.getByte(); - long value = mPacketHandler.getLong(); - mPacketHandler.getAcknowledgement(); - return scale * value / 1.0e-1; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Frequency measurement on IDx. - * Measures time taken for 16 rising edges of input signal. - * Returns the frequency in Hertz - * - * @param channel The input to measure frequency from. ['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @return frequency - */ - public Double getFrequency(String channel) { - /* - Frequency measurement on IDx. - Measures time taken for 16 rising edges of input signal. - returns the frequency in Hertz - */ - if (channel == null) channel = "LA1"; - LinkedHashMap data; - try { - startOneChannelLA(channel, 1, channel, 3); - Thread.sleep(250); - data = getLAInitialStates(); - Thread.sleep(250); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - return fetchLAChannelFrequency(calculateDigitalChannel(channel), data); - } - - /** - * Stores a list of rising edges that occurred within the timeout period. - * - * @param channel The input to measure time between two rising edges.['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @param skipCycle Number of points to skip. eg. Pendulums pass through light barriers twice every cycle. SO 1 must be skipped - * @param timeout Number of seconds to wait for datapoints. (Maximum 60 seconds) - * @return - */ - public Double r2rTime(String channel, Integer skipCycle, Integer timeout) { - /* - Return a list of rising edges that occured within the timeout period. - */ - if (skipCycle == null) skipCycle = 0; - if (timeout == null) timeout = 5; - if (timeout > 60) timeout = 60; - this.startOneChannelLA(channel, 3, null, 0); - long startTime = System.currentTimeMillis(); - while (System.currentTimeMillis() - startTime < timeout) { - LinkedHashMap initialStates = this.getLAInitialStates(); - if (initialStates.get("A") == this.MAX_SAMPLES / 4) - initialStates.put("A", 0); - if (initialStates.get("A") >= skipCycle + 2) { - long[] data = this.fetchLongDataFromLA(initialStates.get("A"), 1); - LinkedHashMap tempMap = new LinkedHashMap<>(); - tempMap.put("LA1", initialStates.get("LA1")); - tempMap.put("LA2", initialStates.get("LA2")); - tempMap.put("LA3", initialStates.get("LA3")); - tempMap.put("LA4", initialStates.get("LA4")); - tempMap.put("RES", initialStates.get("RES")); - double[] doubleData = new double[data.length]; - for (int i = 0; i < data.length; i++) { - doubleData[i] = data[i]; - } - this.dChannels.get(0).loadData(tempMap, doubleData); - return 1e-6 * (this.dChannels.get(0).timestamps[skipCycle + 1] - this.dChannels.get(0).timestamps[0]); - } - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - return null; - } - - /** - * Stores a list of falling edges that occured within the timeout period. - * - * @param channel The input to measure time between two falling edges.['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @param skipCycle Number of points to skip. eg. Pendulums pass through light barriers twice every cycle. SO 1 must be skipped - * @param timeout Number of seconds to wait for datapoints. (Maximum 60 seconds) - * @return - */ - public Double f2fTime(String channel, Integer skipCycle, Integer timeout) { - /* - Return a list of falling edges that occured within the timeout period. - */ - if (skipCycle == null) skipCycle = 0; - if (timeout == null) timeout = 5; - if (timeout > 60) timeout = 60; - this.startOneChannelLA(channel, 2, null, 0); - long startTime = System.currentTimeMillis(); - while (System.currentTimeMillis() - startTime < timeout) { - LinkedHashMap initialStates = this.getLAInitialStates(); - if (initialStates.get("A") == this.MAX_SAMPLES / 4) - initialStates.put("A", 0); - if (initialStates.get("A") >= skipCycle + 2) { - long[] data = this.fetchLongDataFromLA(initialStates.get("A"), 1); - LinkedHashMap tempMap = new LinkedHashMap<>(); - tempMap.put("LA1", initialStates.get("LA1")); - tempMap.put("LA2", initialStates.get("LA2")); - tempMap.put("LA3", initialStates.get("LA3")); - tempMap.put("LA4", initialStates.get("LA4")); - tempMap.put("RES", initialStates.get("RES")); - double[] doubleData = new double[data.length]; - for (int i = 0; i < data.length; i++) { - doubleData[i] = data[i]; - } - this.dChannels.get(0).loadData(tempMap, doubleData); - return 1e-6 * (this.dChannels.get(0).timestamps[skipCycle + 1] - this.dChannels.get(0).timestamps[0]); - } - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - return null; - } - - /** - * Measures time intervals between two logic level changes on any two digital inputs(both can be the same) and returns the calculated time. - * For example, one can measure the time interval between the occurrence of a rising edge on LA1, and a falling edge on LA3. - * If the returned time is negative, it simply means that the event corresponding to channel2 occurred first. - * - * @param channel1 The input pin to measure first logic level change - * @param channel2 The input pin to measure second logic level change -['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @param edge1 The type of level change to detect in order to start the timer - ['rising', 'falling', 'four rising edges'] - * @param edge2 The type of level change to detect in order to stop the timer - ['rising', 'falling', 'four rising edges'] - * @param timeout Use the timeout option if you're unsure of the input signal time period. Returns -1 if timed out - * @return time - */ - public Double measureInterval(String channel1, String channel2, String edge1, String edge2, Float timeout) { - /* - Measures time intervals between two logic level changes on any two digital inputs(both can be the same) - For example, one can measure the time interval between the occurence of a rising edge on LA1, and a falling edge on LA3. - If the returned time is negative, it simply means that the event corresponding to channel2 occurred first. - Returns the calculated time - */ - - if (timeout == null) timeout = 0.1f; - try { - mPacketHandler.sendByte(mCommandsProto.TIMING); - mPacketHandler.sendByte(mCommandsProto.INTERVAL_MEASUREMENTS); - int timeoutMSB = ((int) (timeout * 64e6)) >> 16; - mPacketHandler.sendInt(timeoutMSB); - mPacketHandler.sendByte(this.calculateDigitalChannel(channel1) | (this.calculateDigitalChannel(channel2) << 4)); - int params = 0; - if ("rising".equals(edge1)) - params |= 3; - else if ("falling".equals(edge1)) - params |= 2; - else - params |= 4; - - if ("rising".equals(edge2)) - params |= 3 << 3; - else if ("falling".equals(edge2)) - params |= 2 << 3; - else - params |= 4 << 3; - - mPacketHandler.sendByte(params); - long A = mPacketHandler.getLong(); - long B = mPacketHandler.getLong(); - int tmt = mPacketHandler.getInt(); - mPacketHandler.getAcknowledgement(); - if (tmt > timeoutMSB || B == 0) return null; - - return (B - A + 20) / 64e6; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Duty cycle measurement on channel. Returns wavelength(seconds), and length of first half of pulse(high time) - * Low time = (wavelength - high time) - * - * @param channel The input pin to measure wavelength and high time.['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @param timeout Use the timeout option if you're unsure of the input signal time period. Returns 0 if timed out - * @return Wavelength, Duty cycle - */ - public double[] dutyCycle(String channel, Double timeout) { - /* - duty cycle measurement on channel - returns wavelength(seconds), and length of first half of pulse(high time) - low time = (wavelength - high time) - */ - if (channel == null) channel = "LA1"; - if (timeout == null) timeout = 1.; - Map data = this.measureMultipleDigitalEdges(channel, channel, "rising", "falling", 2, 2, timeout, null, true); - double[] retData = new double[2]; - if (data != null) { - double[] x = data.get("CHANNEL1"); - double[] y = data.get("CHANNEL2"); - if (x != null && y != null) { // Both timers registered something. did not timeout - if (y[0] > 0) { - retData[0] = y[0]; - retData[1] = x[1]; - } else { - if (y[1] > x[1]) { - retData[0] = -1; - retData[1] = -1; - return retData; - } - retData[0] = y[1]; - retData[1] = x[1]; - } - double[] params = new double[2]; - params[0] = retData[1]; - params[1] = retData[0] / retData[1]; - if (params[1] > 0.5) { - Log.v(TAG, Arrays.toString(x) + "\n" + Arrays.toString(y) + "\n" + Arrays.toString(retData)); - } - return params; - } - } - retData[0] = -1; - retData[1] = -1; - return retData; - } - - /** - * Duty cycle measurement on channel. Returns wavelength(seconds), and length of first half of pulse(high time) - * Low time = (wavelength - high time) - * - * @param channel The input pin to measure wavelength and high time.['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @param pulseType Type of pulse to detect. May be 'HIGH' or 'LOW' - * @param timeout Use the timeout option if you're unsure of the input signal time period. Returns 0 if timed out - * @return Pulse width - */ - public Double pulseTime(String channel, String pulseType, Double timeout) { - if (channel == null) channel = "LA1"; - if (pulseType == null) pulseType = "LOW"; - if (timeout == null) timeout = 0.1; - - Map data = this.measureMultipleDigitalEdges(channel, channel, "rising", "falling", 2, 2, timeout, null, true); - if (data != null) { - double[] x = data.get("CHANNEL1"); - double[] y = data.get("CHANNEL2"); - if (x != null && y != null) { // Both timers registered something. did not timeout - if (y[0] > 0) { - if ("HIGH".equals(pulseType)) - return y[0]; - else if ("LOW".equals(pulseType)) { - return x[1] - y[0]; - } - } else { - if ("HIGH".equals(pulseType)) - return y[1]; - else if ("LOW".equals(pulseType)) { - return Math.abs(y[0]); - } - } - } - } - return null; - } - - /** - * Measures a set of timestamped logic level changes(Type can be selected) from two different digital inputs. - * - * @param channel1 The input pin to measure first logic level change - * @param channel2 The input pin to measure second logic level change -['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @param edgeType1 The type of level change that should be recorded - ['rising', 'falling', 'four rising edges(default)'] - * @param edgeType2 The type of level change that should be recorded - ['rising', 'falling', 'four rising edges(default)'] - * @param points1 Number of data points to obtain for input 1 (Max 4) - * @param points2 Number of data points to obtain for input 2 (Max 4) - * @param timeout Use the timeout option if you're unsure of the input signal time period. returns -1 if timed out - * @param SQR1 Set the state of SQR1 output(LOW or HIGH) and then start the timer. eg. SQR1 = 'LOW' - * @param zero subtract the timestamp of the first point from all the others before returning. Default: True - * @return time - */ - private Map measureMultipleDigitalEdges(String channel1, String channel2, String edgeType1, String edgeType2, int points1, int points2, Double timeout, String SQR1, Boolean zero) { - - if (timeout == null) timeout = 0.1; - try { - mPacketHandler.sendByte(mCommandsProto.TIMING); - mPacketHandler.sendByte(mCommandsProto.TIMING_MEASUREMENTS); - int timeoutMSB = ((int) (timeout * 64e6)) >> 16; - mPacketHandler.sendInt(timeoutMSB); - mPacketHandler.sendByte(this.calculateDigitalChannel(channel1) | (this.calculateDigitalChannel(channel2) << 4)); - int params = 0; - if ("rising".equals(edgeType1)) - params |= 3; - else if ("falling".equals(edgeType1)) - params |= 2; - else - params |= 4; - - if ("rising".equals(edgeType2)) - params |= 3 << 3; - else if ("falling".equals(edgeType2)) - params |= 2 << 3; - else - params |= 4 << 3; - if (SQR1 != null) { - params |= (1 << 6); - if ("HIGH".equals(SQR1)) - params |= (1 << 7); - } - mPacketHandler.sendByte(params); - if (points1 > 4) points1 = 4; - if (points2 > 4) points2 = 4; - mPacketHandler.sendByte(points1 | (points2 << 4)); - - //mPacketHandler.waitForData(timeout); todo : complete waitForData in PacketHandler.java - long[] A = new long[points1]; - long[] B = new long[points2]; - for (int i = 0; i < points1; i++) - A[i] = mPacketHandler.getLong(); - for (int i = 0; i < points2; i++) - B[i] = mPacketHandler.getLong(); - int tmt = mPacketHandler.getInt(); - mPacketHandler.getAcknowledgement(); - Map retData = new HashMap<>(); - if (tmt > timeoutMSB) { - retData.put("CHANNEL1", null); - retData.put("CHANNEL2", null); - return retData; - } - if (zero == null) zero = true; - double[] A1 = new double[A.length]; - double[] B1 = new double[B.length]; - if (zero) { - for (int i = 0; i < A.length; i++) { - A[i] -= A[0]; - A1[i] = A[i] / 64e6; - } - for (int i = 0; i < B.length; i++) { - B[i] -= B[0]; - B1[i] = B[i] / 64e6; - } - } else { - for (int i = 0; i < A.length; i++) { - A1[i] = A[i] / 64e6; - } - for (int i = 0; i < B.length; i++) { - B1[i] = B[i] / 64e6; - } - } - retData.put("CHANNEL1", A1); - retData.put("CHANNEL2", B1); - return retData; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Log timestamps of rising/falling edges on one digital input - * - * @param waitingTime Total time to allow the logic analyzer to collect data. This is implemented using a simple sleep routine, so if large delays will be involved, refer to startOneChannelLA() to start the acquisition, and fetchLAChannels() to retrieve data from the hardware after adequate time. The retrieved data is stored in the array self.dchans[0].timestamps. - * @param aquireChannel LA1',...,'LA4' - * @param triggerChannel LA1',...,'LA4' - * @param aquireMode EVERY_SIXTEENTH_RISING_EDGE = 5 - * EVERY_FOURTH_RISING_EDGE = 4 - * EVERY_RISING_EDGE = 3 - * EVERY_FALLING_EDGE = 2 - * EVERY_EDGE = 1 - * DISABLED = 0 - * default = 3 - * @param triggerMode same as aquireMode. default_value : 3 - * @return - */ - public double[] captureEdgesOne(Integer waitingTime, String aquireChannel, String triggerChannel, Integer aquireMode, Integer triggerMode) { - /* - Log timestamps of rising/falling edges on one digital input - */ - if (waitingTime == null) waitingTime = 1; - if (aquireChannel == null) aquireChannel = "LA1"; - if (triggerChannel == null) triggerChannel = aquireChannel; - if (aquireMode == null) aquireMode = 3; - if (triggerMode == null) triggerMode = 3; - this.startOneChannelLA(aquireChannel, aquireMode, triggerChannel, triggerMode); - try { - Thread.sleep(waitingTime * 1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - LinkedHashMap data = this.getLAInitialStates(); - long[] temp = this.fetchLongDataFromLA(data.get("A"), 1); - double[] retData = new double[temp.length]; - for (int i = 0; i < temp.length; i++) { - retData[i] = temp[i] / 64e6; - } - return retData; - } - - /** - * Start logging timestamps of rising/falling edges on LA1 - * - * @param trigger Bool . Enable edge trigger on LA1. use keyword argument edge = 'rising' or 'falling' - * @param channel ['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @param maximumTime Total time to sample. If total time exceeds 67 seconds, a prescaler will be used in the reference clock. - * @param triggerChannels array of digital input names that can trigger the acquisition. Eg, trigger = ['LA1','LA2','LA3'] will triggger when a logic change specified by the keyword argument 'edge' occurs on either or the three specified trigger inputs. - * @param edge 'rising' or 'falling' . trigger edge type for trigger_channels. - */ - public void startOneChannelLABackup(Integer trigger, String channel, Integer maximumTime, ArrayList triggerChannels, String edge) { - /* - start logging timestamps of rising/falling edges on LA1 - */ - try { - this.clearBuffer(0, this.MAX_SAMPLES / 2); - mPacketHandler.sendByte(mCommandsProto.TIMING); - mPacketHandler.sendByte(mCommandsProto.START_ONE_CHAN_LA); - mPacketHandler.sendInt(this.MAX_SAMPLES / 4); - if (triggerChannels != null & (trigger & 1) != 0) { - if (triggerChannels.contains("LA1")) trigger |= (1 << 4); - if (triggerChannels.contains("LA2")) trigger |= (1 << 5); - if (triggerChannels.contains("LA3")) trigger |= (1 << 6); - } else { - trigger |= 1 << (this.calculateDigitalChannel(channel) + 4); - } - if ("rising".equals(edge)) trigger |= 2; - trigger |= (this.calculateDigitalChannel(channel) << 2); - - mPacketHandler.sendByte(trigger); - mPacketHandler.getAcknowledgement(); - this.digitalChannelsInBuffer = 1; - for (DigitalChannel dChan : this.dChannels) { - dChan.prescalar = 0; - dChan.dataType = "long"; - dChan.length = this.MAX_SAMPLES / 4; - dChan.maxTime = (int) (maximumTime * 1e6); - dChan.mode = DigitalChannel.EVERY_EDGE; - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Start logging timestamps of rising/falling edges on LA1. - * - * @param channel ['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @param channelMode acquisition mode default value: 1(EVERY_EDGE) - * - EVERY_SIXTEENTH_RISING_EDGE = 5 - * - EVERY_FOURTH_RISING_EDGE = 4 - * - EVERY_RISING_EDGE = 3 - * - EVERY_FALLING_EDGE = 2 - * - EVERY_EDGE = 1 - * - DISABLED = 0 - * @param triggerChannel ['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @param triggerMode 1=Falling edge, 0=Rising Edge, -1=Disable Trigger - */ - public void startOneChannelLA(String channel, Integer channelMode, String triggerChannel, Integer triggerMode) { - if (channel == null) channel = "LA1"; - if (channelMode == null) channelMode = 1; - if (triggerChannel == null) triggerChannel = "LA1"; - if (triggerMode == null) triggerMode = 3; - try { - this.clearBuffer(0, this.MAX_SAMPLES); - mPacketHandler.sendByte(mCommandsProto.TIMING); - mPacketHandler.sendByte(mCommandsProto.START_ALTERNATE_ONE_CHAN_LA); - mPacketHandler.sendInt(this.MAX_SAMPLES / 4); - int aqChannel = this.calculateDigitalChannel(channel); - int aqMode = channelMode; - int trChannel = this.calculateDigitalChannel(triggerChannel); - int trMode = triggerMode; - mPacketHandler.sendByte((aqChannel << 4) | aqMode); - mPacketHandler.sendByte((trChannel << 4) | trMode); - mPacketHandler.getAcknowledgement(); - this.digitalChannelsInBuffer = 1; - this.dChannels.get(aqChannel).prescalar = 0; - this.dChannels.get(aqChannel).dataType = "long"; - this.dChannels.get(aqChannel).length = this.MAX_SAMPLES / 4; - this.dChannels.get(aqChannel).maxTime = (int) (67 * 1e6); - this.dChannels.get(aqChannel).mode = channelMode; - this.dChannels.get(aqChannel).channelName = channel; - if (trMode == 3 || trMode == 4 || trMode == 5) - this.dChannels.get(aqChannel).initialStateOverride = 2; - else if (trMode == 2) - this.dChannels.get(0).initialStateOverride = 1; - - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Start logging timestamps of rising/falling edges on LA1,LA2 - * - * @param channels Channels to acquire data from . default ['LA1','LA2'] - * @param modes modes for each channel. Array . default value: [1,1] - * - EVERY_SIXTEENTH_RISING_EDGE = 5 - * - EVERY_FOURTH_RISING_EDGE = 4 - * - EVERY_RISING_EDGE = 3 - * - EVERY_FALLING_EDGE = 2 - * - EVERY_EDGE = 1 - * - DISABLED = 0 - * @param maximumTime Total time to sample. If total time exceeds 67 seconds, a prescaler will be used in the reference clock - * @param trigger Bool . Enable rising edge trigger on LA1 - * @param edge 'rising' or 'falling' . trigger edge type for trigger_channels. - * @param triggerChannel channel to trigger on . Any digital input. default CH1 - */ - public void startTwoChannelLA(ArrayList channels, ArrayList modes, Integer maximumTime, Integer trigger, String edge, String triggerChannel) { - if (maximumTime == null) maximumTime = 67; - if (trigger == null) trigger = 0; - if (edge == null) edge = "rising"; - if (channels == null) { - channels = new ArrayList<>(); - channels.add("LA1"); - channels.add("LA2"); - } - if (modes == null) { - modes = new ArrayList<>(); - modes.add(1); - modes.add(1); - } - int[] chans = new int[]{this.calculateDigitalChannel(channels.get(0)), this.calculateDigitalChannel(channels.get(1))}; - if (triggerChannel == null) triggerChannel = channels.get(0); - if (trigger != 0) { - trigger = 1; - if ("falling".equals(edge)) trigger |= 2; - trigger |= (this.calculateDigitalChannel(triggerChannel) << 4); - } - try { - this.clearBuffer(0, this.MAX_SAMPLES); - mPacketHandler.sendByte(mCommandsProto.TIMING); - mPacketHandler.sendByte(mCommandsProto.START_TWO_CHAN_LA); - mPacketHandler.sendInt(this.MAX_SAMPLES / 4); - mPacketHandler.sendByte(trigger); - mPacketHandler.sendByte((modes.get(1) << 4) | modes.get(0)); - mPacketHandler.sendByte((chans[1] << 4) | chans[0]); - mPacketHandler.getAcknowledgement(); - for (int i = 0; i < 2; i++) { - DigitalChannel temp = this.dChannels.get(i); - temp.prescalar = 0; - temp.length = this.MAX_SAMPLES / 4; - temp.dataType = "long"; - temp.maxTime = (int) (maximumTime * 1e6); - temp.mode = modes.get(i); - temp.channelNumber = chans[i]; - temp.channelName = channels.get(i); - } - this.digitalChannelsInBuffer = 2; - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Start logging timestamps of rising/falling edges on LA1,LA2,LA3 - * - * @param modes modes for each channel. Array. default value: [1,1,1] - * - EVERY_SIXTEENTH_RISING_EDGE = 5 - * - EVERY_FOURTH_RISING_EDGE = 4 - * - EVERY_RISING_EDGE = 3 - * - EVERY_FALLING_EDGE = 2 - * - EVERY_EDGE = 1 - * - DISABLED = 0 - * @param triggerChannel ['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - * @param triggerMode same as modes(previously documented keyword argument) - * default_value : 3 - */ - public void startThreeChannelLA(ArrayList modes, String triggerChannel, Integer triggerMode) { - if (modes == null) { - modes = new ArrayList<>(); - modes.add(1); - modes.add(1); - modes.add(1); - } - if (triggerChannel == null) { - triggerChannel = "LA1"; - } - if (triggerMode == null) { - triggerMode = 3; - } - try { - this.clearBuffer(0, this.MAX_SAMPLES); - mPacketHandler.sendByte(mCommandsProto.TIMING); - mPacketHandler.sendByte(mCommandsProto.START_THREE_CHAN_LA); - mPacketHandler.sendInt(this.MAX_SAMPLES / 4); - int trChan = this.calculateDigitalChannel(triggerChannel); - int trMode = triggerMode; - - mPacketHandler.sendInt(modes.get(0) | (modes.get(1) << 4) | (modes.get(2) << 8)); - mPacketHandler.sendByte((trChan << 4) | trMode); - mPacketHandler.getAcknowledgement(); - this.digitalChannelsInBuffer = 3; - - for (int i = 0; i < 3; i++) { - DigitalChannel temp = this.dChannels.get(i); - temp.prescalar = 0; - temp.length = this.MAX_SAMPLES / 4; - temp.dataType = "int"; - temp.maxTime = (int) (1e3); - temp.mode = modes.get(i); - temp.channelName = DigitalChannel.digitalChannelNames[i]; - if (trMode == 3 || trMode == 4 || trMode == 5) { - temp.initialStateOverride = 2; - } else if (trMode == 2) { - temp.initialStateOverride = 1; - } - } - - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Four channel Logic Analyzer. - * Start logging timestamps from a 64MHz counter to record level changes on LA1,LA2,LA3,LA4. - * triggerChannel[0] -> LA1 - * triggerChannel[1] -> LA2 - * triggerChannel[2] -> LA3 - * - * @param trigger Bool. Enable rising edge trigger on LA1. - * @param maximumTime Maximum delay expected between two logic level changes. - * If total time exceeds 1 mS, a prescaler will be used in the reference clock. - * However, this only refers to the maximum time between two successive level changes. If a delay larger - * than .26 S occurs, it will be truncated by modulo .26 S. - * If you need to record large intervals, try single channel/two channel modes which use 32 bit counters - * capable of time interval up to 67 seconds. - * @param modes modes for each channel. List with four elements\n - * default values: [1,1,1,1] - * - EVERY_SIXTEENTH_RISING_EDGE = 5 - * - EVERY_FOURTH_RISING_EDGE = 4 - * - EVERY_RISING_EDGE = 3 - * - EVERY_FALLING_EDGE = 2 - * - EVERY_EDGE = 1 - * - DISABLED = 0 - * @param edge 'rising' or 'falling'. Trigger edge type for trigger_channels. - * @param triggerChannel ['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - */ - public void startFourChannelLA(Integer trigger, Double maximumTime, ArrayList modes, String edge, ArrayList triggerChannel) { - if (trigger == null) trigger = 1; - if (maximumTime == null) maximumTime = 0.001; - if (modes == null) { - modes = new ArrayList<>(); - modes.add(1); - modes.add(1); - modes.add(1); - } - if (edge == null) edge = "0"; - this.clearBuffer(0, this.MAX_SAMPLES); - int prescale = 0; - try { - mPacketHandler.sendByte(mCommandsProto.TIMING); - mPacketHandler.sendByte(mCommandsProto.START_FOUR_CHAN_LA); - mPacketHandler.sendInt(this.MAX_SAMPLES / 4); - mPacketHandler.sendInt(modes.get(0) | (modes.get(1) << 4) | (modes.get(2) << 8) | (modes.get(3) << 12)); - mPacketHandler.sendByte(prescale); - int triggerOptions = 0; - if (triggerChannel.get(0)) triggerOptions |= 4; - if (triggerChannel.get(1)) triggerOptions |= 8; - if (triggerChannel.get(2)) triggerOptions |= 16; - if (triggerOptions == 0) - triggerOptions |= 4; // Select one trigger channel(LA1) if none selected - if ("rising".equals(edge)) triggerOptions |= 2; - trigger |= triggerOptions; - mPacketHandler.sendByte(trigger); - mPacketHandler.getAcknowledgement(); - this.digitalChannelsInBuffer = 4; - int i = 0; - for (DigitalChannel dChan : this.dChannels) { - dChan.prescalar = prescale; - dChan.dataType = "int"; - dChan.length = this.MAX_SAMPLES / 4; - dChan.maxTime = (int) (maximumTime * 1e6); - dChan.mode = modes.get(i); - dChan.channelName = DigitalChannel.digitalChannelNames[i]; - i++; - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Fetches the initial states of digital inputs that were recorded right before the Logic analyzer was started, - * and the total points each channel recorded. - * - * @return CH1 progress,CH2 progress,CH3 progress,CH4 progress,[LA1,LA2,LA3,LA4]. eg. [1,0,1,1] - */ - public LinkedHashMap getLAInitialStates() { - try { - mPacketHandler.sendByte(mCommandsProto.TIMING); - mPacketHandler.sendByte(mCommandsProto.GET_INITIAL_DIGITAL_STATES); - byte[] initialStatesBytes = new byte[13]; - mPacketHandler.read(initialStatesBytes, 13); - int initial = (initialStatesBytes[0] & 0xff) | ((initialStatesBytes[1] << 8) & 0xff00); - int A = (((initialStatesBytes[2] & 0xff) | ((initialStatesBytes[3] << 8) & 0xff00)) - initial) / 2; - int B = (((initialStatesBytes[4] & 0xff) | ((initialStatesBytes[5] << 8) & 0xff00)) - initial) / 2 - MAX_SAMPLES / 4; - int C = (((initialStatesBytes[6] & 0xff) | ((initialStatesBytes[7] << 8) & 0xff00)) - initial) / 2 - 2 * MAX_SAMPLES / 4; - int D = (((initialStatesBytes[8] & 0xff) | ((initialStatesBytes[9] << 8) & 0xff00)) - initial) / 2 - 3 * MAX_SAMPLES / 4; - int s = initialStatesBytes[10]; - int sError = initialStatesBytes[11]; - //mPacketHandler.getAcknowledgement(); - - if (A == 0) A = this.MAX_SAMPLES / 4; - if (B == 0) B = this.MAX_SAMPLES / 4; - if (C == 0) C = this.MAX_SAMPLES / 4; - if (D == 0) D = this.MAX_SAMPLES / 4; - - if (A < 0) A = 0; - if (B < 0) B = 0; - if (C < 0) C = 0; - if (D < 0) D = 0; - - LinkedHashMap retData = new LinkedHashMap<>(); - retData.put("A", A); - retData.put("B", B); - retData.put("C", C); - retData.put("D", D); - - // putting 1 -> true & 0 -> false - if ((s & 1) != 0) - retData.put("LA1", 1); - else - retData.put("LA1", 0); - - if ((s & 2) != 0) - retData.put("LA2", 1); - else - retData.put("LA2", 0); - - if ((s & 4) != 0) - retData.put("LA3", 1); - else - retData.put("LA3", 0); - - if ((s & 8) != 0) - retData.put("LA4", 1); - else - retData.put("LA4", 0); - - if ((s & 16) != 0) - retData.put("RES", 1); - else - retData.put("RES", 0); - - return retData; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Stop any running logic analyzer function. - */ - public void stopLA() { - try { - mPacketHandler.sendByte(mCommandsProto.TIMING); - mPacketHandler.sendByte(mCommandsProto.STOP_LA); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Fetches the data stored by DMA. integer address increments - * - * @param bytes number of readings(integer) to fetch - * @param channel channel number (1-4) - * @return array of integer data fetched from Logic Analyser. - */ - public int[] fetchIntDataFromLA(Integer bytes, Integer channel) { - if (channel == null) channel = 1; - try { - ArrayList l = new ArrayList<>(); - for (int i = 0; i < bytes / this.dataSplitting; i++) { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.RETRIEVE_BUFFER); - mPacketHandler.sendInt(2500 * (channel - 1) + (i * this.dataSplitting)); - mPacketHandler.sendInt(this.dataSplitting); - byte[] data = new byte[this.dataSplitting * 2 + 1]; - mPacketHandler.read(data, this.dataSplitting * 2 + 1); - for (int j = 0; j < data.length - 1; j++) - l.add((int) data[j] & 0xff); - } - - if ((bytes % this.dataSplitting) != 0) { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.RETRIEVE_BUFFER); - mPacketHandler.sendInt(bytes - bytes % this.dataSplitting); - mPacketHandler.sendInt(bytes % this.dataSplitting); - byte[] data = new byte[2 * (bytes % this.dataSplitting) + 1]; - mPacketHandler.read(data, 2 * (bytes % this.dataSplitting) + 1); - for (int j = 0; j < data.length - 1; j++) - l.add((int) data[j] & 0xff); - } - if (!l.isEmpty()) { - StringBuilder stringBuilder = new StringBuilder(); - int[] timeStamps = new int[(int) bytes + 1]; - for (int i = 0; i < (int) (bytes); i++) { - int t = (l.get(i * 2) | (l.get(i * 2 + 1) << 8)); - timeStamps[i + 1] = t; - stringBuilder.append(String.valueOf(t)); - stringBuilder.append(" "); - } - Log.v("Fetched points : ", stringBuilder.toString()); - //mPacketHandler.getAcknowledgement(); - Arrays.sort(timeStamps); - timeStamps[0] = 1; - return timeStamps; - } else { - Log.e("Error : ", "Obtained bytes = 0"); - int[] temp = new int[2501]; - Arrays.fill(temp, 0); - return temp; - } - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Fetches the data stored by DMA. long address increments. - * - * @param bytes number of readings(long integers) to fetch - * @param channel channel number (1-2) - * @return array of long integers data fetched from Logic Analyser. - */ - public long[] fetchLongDataFromLA(Integer bytes, Integer channel) { - if (channel == null) channel = 1; - try { - mPacketHandler.sendByte(mCommandsProto.TIMING); - mPacketHandler.sendByte(mCommandsProto.FETCH_LONG_DMA_DATA); - mPacketHandler.sendInt(bytes); - mPacketHandler.sendByte(channel - 1); - byte[] readData = new byte[bytes * 4]; - mPacketHandler.read(readData, bytes * 4); - mPacketHandler.getAcknowledgement(); - long[] data = new long[bytes]; - for (int i = 0; i < bytes; i++) { - data[i] = ByteBuffer.wrap(Arrays.copyOfRange(readData, 4 * i, 4 * i + 4)).order(ByteOrder.LITTLE_ENDIAN).getLong(); - } - // Trimming array data - int markerA = 0; - for (int i = 0; i < data.length; i++) { - if (data[i] != 0) { - markerA = i; - break; - } - } - int markerB = 0; - for (int i = data.length - 1; i >= 0; i--) { - if (data[i] != 0) { - markerB = i; - break; - } - } - return Arrays.copyOfRange(data, markerA, markerB + 1); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Reads and stores the channels in this.dChannels. - * - * @return true if LA channels fetched successfully. - */ - public boolean fetchLAChannels() { - LinkedHashMap data = this.getLAInitialStates(); - for (int i = 0; i < 4; i++) { - if (this.dChannels.get(i).channelNumber < this.digitalChannelsInBuffer) { - this.fetchLAChannel(i, data); - } - } - return true; - } - - /** - * @param channelNumber Channel number being used e.g. CH1, CH2, CH3, CH4. - * @param initialStates State of the digital inputs. returns dictionary with keys 'LA1','LA2','LA3','LA4','RES' - * @return true if data fetched/loaded successfully. - */ - public boolean fetchLAChannel(Integer channelNumber, LinkedHashMap initialStates) { - DigitalChannel dChan = this.dChannels.get(channelNumber); - - LinkedHashMap tempMap = new LinkedHashMap<>(); - tempMap.put("LA1", initialStates.get("LA1")); - tempMap.put("LA2", initialStates.get("LA2")); - tempMap.put("LA3", initialStates.get("LA3")); - tempMap.put("LA4", initialStates.get("LA4")); - tempMap.put("RES", initialStates.get("RES")); - - // Used LinkedHashMap above (initialStates) in which iteration is done sequentially as were inserted - int i = 0; - for (Map.Entry entry : initialStates.entrySet()) { - if (dChan.channelNumber == i) { - i = entry.getValue(); - break; - } - i++; - } - - int[] temp = this.fetchIntDataFromLA(i, dChan.channelNumber + 1); - double[] data = new double[temp.length - 1]; - if (temp[0] == 1) { - for (int j = 1; j < temp.length; j++) { - data[j - 1] = temp[j]; - } - } else { - Log.e("Error : ", "Can't load data"); - return false; - } - dChan.loadData(tempMap, data); - - dChan.generateAxes(); - return true; - } - - public double fetchLAChannelFrequency(Integer channelNumber, LinkedHashMap initialStates) { - DigitalChannel dChan = this.dChannels.get(channelNumber); - - LinkedHashMap tempMap = new LinkedHashMap<>(); - tempMap.put("LA1", initialStates.get("LA1")); - tempMap.put("LA2", initialStates.get("LA2")); - tempMap.put("LA3", initialStates.get("LA3")); - tempMap.put("LA4", initialStates.get("LA4")); - tempMap.put("RES", initialStates.get("RES")); - - // Used LinkedHashMap above (initialStates) in which iteration is done sequentially as were inserted - int i = 0; - for (Map.Entry entry : initialStates.entrySet()) { - if (dChan.channelNumber == i) { - i = entry.getValue(); - break; - } - i++; - } - - int[] temp = this.fetchIntDataFromLA(i, dChan.channelNumber + 1); - double[] data = new double[temp.length - 1]; - if (temp[0] == 1) { - for (int j = 1; j < temp.length; j++) { - data[j - 1] = temp[j]; - } - } else { - Log.e("Error : ", "Can't load data"); - return -1; - } - dChan.loadData(tempMap, data); - - dChan.generateAxes(); - int count = 0; - double[] yAxis = dChan.getYAxis(); - for (int j = 1; j < yAxis.length; j++) { - if (yAxis[i] != yAxis[i - 1]) { - count++; - } - } - if (count == this.MAX_SAMPLES / 2 - 2) { - LAChannelFrequency = 0; - } else if (count != 0 && count != this.MAX_SAMPLES / 2 - 2 && LAChannelFrequency != count) { - LAChannelFrequency = count; - } - return LAChannelFrequency; - } - - public DigitalChannel getDigitalChannel(int i) { - return dChannels.get(i); - } - - /** - * Gets the state of the digital inputs. - * - * @return dictionary with keys 'LA1','LA2','LA3','LA4'. - */ - public Map getStates() { - try { - mPacketHandler.sendByte(mCommandsProto.DIN); - mPacketHandler.sendByte(mCommandsProto.GET_STATES); - byte state = mPacketHandler.getByte(); - mPacketHandler.getAcknowledgement(); - Map states = new LinkedHashMap<>(); - states.put("LA1", ((state & 1) != 0)); - states.put("LA2", ((state & 2) != 0)); - states.put("LA3", ((state & 4) != 0)); - states.put("LA4", ((state & 8) != 0)); - return states; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Fetch the state of given input ID. - * - * @param inputID the input channel - * 'LA1' -> state of LA1 - * 'LA4' -> state of LA4 - * @return the logic level on the specified input (LA1,LA2,LA3, or LA4) - */ - public Boolean getState(String inputID) { - return this.getStates().get(inputID); - } - - /** - * set the logic level on digital outputs SQR1,SQR2,SQR3,SQR4. - * - * @param args SQR1,SQR2,SQR3,SQR4 - * states(0 or 1) - */ - public void setState(Map args) { - int data = 0; - if (args.containsKey("SQR1")) { - data |= (0x10 | args.get("SQR1")); - } - if (args.containsKey("SQR2")) { - data |= (0x20 | (args.get("SQR2") << 1)); - } - if (args.containsKey("SQR3")) { - data |= (0x40 | (args.get("SQR3") << 2)); - } - if (args.containsKey("SQR4")) { - data |= (0x80 | (args.get("SQR4") << 3)); - } - try { - mPacketHandler.sendByte(mCommandsProto.DOUT); - mPacketHandler.sendByte(mCommandsProto.SET_STATE); - mPacketHandler.sendByte(data); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - /** - * Count pulses on a digital input. Retrieve total pulses using readPulseCount. - * - * @param channel The input pin to measure rising edges on : ['LA1','LA2','LA3','LA4','RES','EXT','FRQ'] - */ - public void countPulses(String channel) { - if (channel == null) channel = "RES"; - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.START_COUNTING); - mPacketHandler.sendByte(this.calculateDigitalChannel(channel)); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Read pulses counted using a digital input. Call countPulses before using this. - * - * @return number of pulse. - */ - public int readPulseCount() { - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.FETCH_COUNT); - int count = mPacketHandler.getVoltageSummation(); - return 10 * count; - } catch (IOException e) { - e.printStackTrace(); - } - return -1; - } - - public void setCapacitorState(int state, int t) { - try { - mPacketHandler.sendByte(mCommandsProto.ADC); - mPacketHandler.sendByte(mCommandsProto.SET_CAP); - mPacketHandler.sendByte(state); - mPacketHandler.sendInt(t); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public double[] captureCapacitance(int samples, int timeGap) { - AnalyticsClass analyticsClass = new AnalyticsClass(); - this.setCapacitorState(1, 50000); - Map data = this.captureFullSpeedHr("CAP", samples, timeGap, Arrays.asList("READ_CAP")); - double[] x = data.get("x"); - double[] y = data.get("y"); - for (int i = 0; i < x.length; i++) { - x[i] = x[i] * 1e-6; - } - ArrayList fitres = analyticsClass.fitExponential(x, y); - if (fitres != null) { - // Not return extra data as in python-communication library. Not required at this point. - return fitres.get(0); - } - return null; - } - - public Double capacitanceViaRCDischarge() { - double cap = getCapacitorRange()[1]; - double time = 2 * cap * 20e3 * 1e6; // uSec - int samples = 500; - if (time > 5000 && time < 10e6) { - if (time > 50e3) samples = 250; - double RC = this.captureCapacitance(samples, (int) (time / samples))[1]; - return RC / 10e3; - } else { - Log.v(TAG, "cap out of range " + time + cap); - return null; - } - } - - /** - * Charges a capacitor connected to IN1 via a 20K resistor from a 3.3V source for a fixed interval. - * - * @param cTime range of time - * @return the capacitance calculated using the formula Vc = Vs(1-exp(-t/RC)) - */ - public double[] getCapacitorRange(int cTime) { - // returns values as a double array arr[0] = v, arr[1] = c - this.dischargeCap(30000, 1000); - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.GET_CAP_RANGE); - mPacketHandler.sendInt(cTime); - int vSum = mPacketHandler.getVoltageSummation(); - double v = vSum * 3.3 / 16 / 4095; - double c = -cTime * 1e-6 / 1e4 / Math.log(1 - v / 3.3); - return new double[]{v, c}; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Charges a capacitor connected to IN1 via a 20K resistor from a 3.3V source for a fixed interval - * - * @return the capacitance calculated using the formula Vc = Vs(1-exp(-t/RC)) - */ - public double[] getCapacitorRange() { - double[] range = new double[]{1.5, 50e-12}; - for (int i = 0; i < 4; i++) { - range = getCapacitorRange(50 * (int) (pow(10, i))); - if (range[0] > 1.5) { - if (i == 0 && range[0] > 3.28) { - range[1] = 50e-12; - } - break; - } - } - return range; - } - - public void dischargeCap(int dischargeTime, double timeout) { - Instant startTime = null; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - startTime = Instant.now(); - } - double voltage = getVoltage("CAP", 1); - double previousVoltage = voltage; - - while (voltage > CAPACITOR_DISCHARGE_VOLTAGE) { - setCapacitorState(0, dischargeTime); - voltage = getVoltage("CAP", 1); - - if (Math.abs(previousVoltage - voltage) < CAPACITOR_DISCHARGE_VOLTAGE) { - break; - } - - previousVoltage = voltage; - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - if (Duration.between(startTime, Instant.now()).toMillis() > timeout) { - break; - } - } - } - } - - /** - * Measures capacitance of component connected between CAP and ground - * - * @return Capacitance (F) - */ - public Double getCapacitance() { - double[] GOOD_VOLTS = new double[]{2.5, 3.3}; - int CT = 10; - int CR = 1; - int iterations = 0; - long startTime = System.currentTimeMillis() / 1000; - while (System.currentTimeMillis() / 1000 - startTime < 5) { - if (CT > 65000) { - Log.v(TAG, "CT too high"); - CT = (int) (CT / pow(10, 4 - CR)); - CR = 0; - } - double[] temp = getCapacitance(CR, 0, CT); - double V = temp[0]; - double C = temp[1]; - if (CT > 30000 && V < 0.1) { - Log.v(TAG, "Capacitance too high for this method"); - return null; - } else if (V > GOOD_VOLTS[0] && V < GOOD_VOLTS[1]) - return C; - else if (V < GOOD_VOLTS[0] && V > 0.01 && CT < 40000) { - if (GOOD_VOLTS[0] / V > 1.1 && iterations < 10) { - CT = (int) (CT * GOOD_VOLTS[0] / V); - iterations += 1; - Log.v(TAG, "Increased CT " + CT); - } else if (iterations == 10) - return null; - else return C; - } else if (V <= 0.1 && CR <= 3) - if (CR == 3) { - CR = 0; - } else { - CR += 1; - } - else if (CR == 0) { - Log.v(TAG, "Capacitance too high!"); - return capacitanceViaRCDischarge(); - } - } - return null; - } - - public double[] getCapacitance(int currentRange, double trim, int chargeTime) { // time in uSec - this.dischargeCap(30000, 1000); - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.GET_CAPACITANCE); - mPacketHandler.sendByte(currentRange); - if (trim < 0) - mPacketHandler.sendByte((int) (31 - Math.abs(trim) / 2) | 32); - else - mPacketHandler.sendByte((int) trim / 2); - mPacketHandler.sendInt(chargeTime); - Thread.sleep((long) (chargeTime * 1e-6 + .02)); - int VCode; - int i = 0; - do VCode = mPacketHandler.getVoltageSummation(); - while (VCode == -1 & i++ < 10); - double v = 3.3 * VCode / 4095; - double chargeCurrent = this.currents[currentRange] * (100 + trim) / 100.0; - double c = 0; - if (v != 0) { - c = (chargeCurrent * chargeTime * 1e-6 / v - this.SOCKET_CAPACITANCE); - } - return new double[]{v, c}; - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Temperature of the MCU in degrees Celsius. - * - * @return temperature : double - */ - public double getTemperature() { - // TODO: Get rid of magic numbers - int cs = 3; - double V = getCTMUVoltage(CTMU_CHANNEL, cs, 0); - if (cs == 1) { - return (646 - V * 1000) / 1.92; // current source = 1 - } else if (cs == 2) { - return (701.5 - V * 1000) / 1.74; // current source = 2 - } else { - return (760 - V * 1000) / 1.56; // current source = 3 - } - } - - /** - * Control the Charge Time Measurement Unit (CTMU). - *

get_ctmu_voltage(5,2) will activate a constant current source of 5.5uA on CAP and then measure the voltage at the output.

- *

If a diode is used to connect CAP to ground, the forward voltage drop of the diode will be returned, e.g. 0.6 V for a 4148 diode.

- *

If a resistor is connected, Ohm's law will be followed within reasonable limits.

- * - * @param channel int - *

Pin number on which to generate a current and measure output - * voltage. Refer to the PIC24EP64GP204 datasheet for channel

- * numbering. - * @param cRange {0, 1, 2, 3} - *

0 -> 550 uA - * 1 -> 550 nA - * 2 -> 5.5 uA - * 3 -> 55 uA

- * @param tgen int, optional - *

Use Time Delay mode instead of Measurement mode. The default value - * is True.

- * @return voltage : double - */ - public double getCTMUVoltage(int channel, int cRange, int tgen) { - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.GET_CTMU_VOLTAGE); - mPacketHandler.sendByte((channel) | (cRange << 5) | (tgen << 7)); - double raw_voltage = (double) mPacketHandler.getInt() / 16; // 16*voltage across the current source - mPacketHandler.getAcknowledgement(); - double max_voltage = 3.3; - double resolution = 12; - return (max_voltage * raw_voltage / (pow(2, resolution) - 1)); - } catch (IOException e) { - e.printStackTrace(); - } - return -1; - } - - public double getCTMUVoltage(int channel, int cRange) { - return getCTMUVoltage(channel, cRange, 1); - } - - public void startCTMU(int cRange, int trim, int tgen) { - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.START_CTMU); - mPacketHandler.sendByte(cRange | (tgen << 7)); - mPacketHandler.sendByte(trim); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void startCTMU(int cRange, int trim) { - startCTMU(cRange, trim, 1); - } - - public void stopCTMU() { - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.STOP_CTMU); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void resetDevice() { - /* - Reset the device. Standalone mode will be enabled if an OLED is connected to the I2C port. - */ - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.RESTORE_STANDALONE); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Reboot and stay in bootloader mode. - * - * @throws IOException - * @throws InterruptedException - */ - public void enterBootloader() throws IOException, InterruptedException { - mCommunicationHandler.close(); - mCommunicationHandler.open(460800); - mPacketHandler = new PacketHandler(50, mCommunicationHandler); - // The PSLab's RGB LED flashes some colors on boot. - int bootLightShowTime = 600; - // Wait before sending magic number to make sure UART is initialized. - Thread.sleep(bootLightShowTime / 2); - // PIC24 UART RX buffer is four bytes deep; no need to time it perfectly. - mPacketHandler.commonWrite(mCommandsProto.pack(0xDECAFBAD)); - // Wait until lightshow is done to prevent accidentally overwriting magic number. - Thread.sleep(bootLightShowTime); - } - - /** - * Set shade of a WS2812 RGB LED. - * - * @param colors ArrayList - *

List of three values between 0-255, where each value is the - * intensity of red, green and blue, respectively. When daisy - * chaining several LEDs, colors should be a list of three-value - * lists.

- * @param output {"RGB", "PGC", "SQ1"}, optional - *

Pin on which to output the pulse train setting the LED color. The - * default value, "RGB", sets the color of the built-in WS2812B - * (PSLav v6 only).

- * @param order String, optional - *

Color order of the connected LED as a three-letter string. The - * built-in LED has order "GRB", which is the default.

- */ - public void RGBLED(ArrayList> colors, String output, String order) { - HashMap pins = new HashMap<>(); - int pin; - if (CommunicationHandler.PSLAB_VERSION == 6) { - pins.put("ONBOARD", 0); - pins.put("SQR1", 1); - pins.put("SQR2", 2); - pins.put("SQR3", 3); - pins.put("SQR4", 4); - } else { - pins.put("RGB", mCommandsProto.SET_RGB1); - pins.put("PGC", mCommandsProto.SET_RGB2); - pins.put("SQ1", mCommandsProto.SET_RGB3); - } - - if (!pins.containsKey(output)) { - String outputPins = String.join(", ", pins.keySet()); - throw new IllegalArgumentException("Invalid output: " + output + ". output must be one of : " + outputPins); - } - pin = Objects.requireNonNull(pins.get(output)); - - for (ArrayList color : colors) { - if (color.size() != 3) { - throw new IllegalArgumentException("Invalid colo; each color list must have three values."); - } - } - - order = order.toUpperCase(Locale.ROOT); - char[] orderChars = order.toCharArray(); - Arrays.sort(orderChars); - if (!Arrays.equals(orderChars, new char[]{'B', 'G', 'R'})) { - throw new IllegalArgumentException("Invalid order: " + order + ". order must contain 'R', 'G', and 'B'."); - } - - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - - if (CommunicationHandler.PSLAB_VERSION == 6) { - mPacketHandler.sendByte(mCommandsProto.SET_RGB_COMMON); - } else { - mPacketHandler.sendByte(pin); - } - - mPacketHandler.sendByte(colors.size() * 3); - - for (ArrayList color : colors) { - mPacketHandler.sendByte(color.get(order.indexOf('R'))); - mPacketHandler.sendByte(color.get(order.indexOf('G'))); - mPacketHandler.sendByte(color.get(order.indexOf('B'))); - } - - if (CommunicationHandler.PSLAB_VERSION == 6) { - mPacketHandler.sendByte(pin); - } - - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void RGBLED(ArrayList colors, String output) { - RGBLED(new ArrayList<>(Collections.singletonList(colors)), output, "GRB"); - } - - /* WAVEGEN SECTION */ - - public void setWave(String channel, double frequency) { - if ("SI1".equals(channel)) - this.setSI1(frequency, null); - else if ("SI2".equals(channel)) - this.setSI2(frequency, null); - } - - public double setSine1(double frequency) { - return this.setSI1(frequency, "sine"); - } - - public double setSine2(double frequency) { - return this.setSI2(frequency, "sine"); - } - - public double setSI1(double frequency, String waveType) { - int HIGHRES, tableSize; - if (frequency < 0.1) { - Log.v(TAG, "frequency too low"); - return -1; - } else if (frequency < 1100) { - HIGHRES = 1; - tableSize = 512; - } else { - HIGHRES = 0; - tableSize = 32; - } - if (waveType != null) { - if ("sine".equals(waveType) | "tria".equals(waveType)) { - if (!(this.waveType.get("SI1").equals(waveType))) { - this.loadEquation("SI1", waveType); - } - } else { - Log.v(TAG, "Not a valid waveform. try sine or tria"); - } - } - int[] p = new int[]{1, 8, 64, 256}; - int prescalar = 0, wavelength = 0; - while (prescalar <= 3) { - wavelength = (int) (64e6 / frequency / p[prescalar] / tableSize); - frequency = 64e6 / wavelength / p[prescalar] / tableSize; - if (wavelength < 65525) break; - prescalar++; - } - if (prescalar == 4) { - Log.v(TAG, "Out of range"); - return -1; - } - try { - mPacketHandler.sendByte(mCommandsProto.WAVEGEN); - mPacketHandler.sendByte(mCommandsProto.SET_SINE1); - mPacketHandler.sendByte(HIGHRES | (prescalar << 1)); - mPacketHandler.sendInt(wavelength - 1); - mPacketHandler.getAcknowledgement(); - this.sin1Frequency = frequency; - return this.sin1Frequency; - } catch (IOException e) { - e.printStackTrace(); - } - return -1; - } - - public double setSI2(double frequency, String waveType) { - int HIGHRES; - int tableSize; - if (frequency < 0.1) { - Log.v(TAG, "frequency too low"); - return -1; - } else if (frequency < 1100) { - HIGHRES = 1; - tableSize = 512; - } else { - HIGHRES = 0; - tableSize = 32; - } - if (waveType != null) { - if ("sine".equals(waveType) | "tria".equals(waveType)) { - if (!(this.waveType.get("SI2").equals(waveType))) { - this.loadEquation("SI2", waveType); - } - } else { - Log.v(TAG, "Not a valid waveform. try sine or tria"); - } - } - int[] p = new int[]{1, 8, 64, 256}; - int prescalar = 0, wavelength = 0; - while (prescalar <= 3) { - wavelength = (int) (64e6 / frequency / p[prescalar] / tableSize); - frequency = 64e6 / wavelength / p[prescalar] / tableSize; - if (wavelength < 65525) break; - prescalar++; - } - if (prescalar == 4) { - Log.v(TAG, "Out of range"); - return -1; - } - try { - mPacketHandler.sendByte(mCommandsProto.WAVEGEN); - mPacketHandler.sendByte(mCommandsProto.SET_SINE2); - mPacketHandler.sendByte(HIGHRES | (prescalar << 1)); - mPacketHandler.sendInt(wavelength - 1); - mPacketHandler.getAcknowledgement(); - this.sin2Frequency = frequency; - return this.sin2Frequency; - } catch (IOException e) { - e.printStackTrace(); - } - return -1; - } - - public double readBackWaveform(String channel) { - if ("SI1".equals(channel)) - return this.sin1Frequency; - else if ("SI2".equals(channel)) - return this.sin2Frequency; - else if ("SQR".startsWith(channel)) - return this.squareWaveFrequency.get(channel); - return -1; - } - - public double setWaves(double frequency, double phase, double frequency2) { - // used frequency as double ( python code demanded ), maybe its taken in KHz or something ( Clarify ) - int HIGHRES, tableSize, HIGHRES2, tableSize2, wavelength = 0, wavelength2 = 0; - if (frequency2 == -1) frequency2 = frequency; - if (frequency < 0.1) { - Log.v(TAG, "frequency 1 too low"); - return -1; - } else if (frequency < 1100) { - HIGHRES = 1; - tableSize = 512; - } else { - HIGHRES = 0; - tableSize = 32; - } - if (frequency2 < 0.1) { - Log.v(TAG, "frequency 2 too low"); - return -1; - } else if (frequency2 < 1100) { - HIGHRES2 = 1; - tableSize2 = 512; - } else { - HIGHRES2 = 0; - tableSize2 = 32; - } - if (frequency < 1 || frequency2 < 1) - Log.v(TAG, "extremely low frequencies will have reduced amplitudes due to AC coupling restrictions"); - - int[] p = new int[]{1, 8, 64, 256}; - int prescalar = 0; - double retFrequency = 0; - while (prescalar <= 3) { - wavelength = (int) (64e6 / frequency / p[prescalar] / tableSize); - retFrequency = 64e6 / wavelength / p[prescalar] / tableSize; - if (wavelength < 65525) break; - prescalar++; - } - if (prescalar == 4) { - Log.v(TAG, "#1 out of range"); - return -1; - } - int prescalar2 = 0; - double retFrequency2 = 0; - while (prescalar2 <= 3) { - wavelength2 = (int) (64e6 / frequency2 / p[prescalar2] / tableSize2); - retFrequency2 = 64e6 / wavelength2 / p[prescalar2] / tableSize2; - if (wavelength2 < 65525) break; - prescalar2++; - } - if (prescalar2 == 4) { - Log.v(TAG, "#2 out of range"); - return -1; - } - - int phaseCoarse = (int) (tableSize2 * (phase) / 360.); - int phaseFine = (int) (wavelength2 * (phase - (phaseCoarse) * 360. / tableSize2) / (360. / tableSize2)); - try { - mPacketHandler.sendByte(mCommandsProto.WAVEGEN); - mPacketHandler.sendByte(mCommandsProto.SET_BOTH_WG); - mPacketHandler.sendInt(wavelength - 1); - mPacketHandler.sendInt(wavelength2 - 1); - mPacketHandler.sendInt(phaseCoarse); - mPacketHandler.sendInt(phaseFine); - mPacketHandler.sendByte((prescalar2 << 4) | (prescalar << 2) | (HIGHRES2 << 1) | (HIGHRES)); - mPacketHandler.getAcknowledgement(); - this.sin1Frequency = retFrequency; - this.sin2Frequency = retFrequency2; - return retFrequency; - } catch (IOException e) { - e.printStackTrace(); - } - return -1; - } - - public void loadEquation(String channel, String function) { - double[] span = new double[2]; - if ("sine".equals(function)) { - span[0] = 0; - span[1] = 2 * Math.PI; - waveType.put(channel, "sine"); - } else if ("tria".equals(function)) { - span[0] = 0; - span[1] = 4; - waveType.put(channel, "tria"); - } else { - waveType.put(channel, "arbit"); - } - double factor = (span[1] - span[0]) / 512; - ArrayList x = new ArrayList<>(); - ArrayList y = new ArrayList<>(); - // for now using switch, proper way is to create an interface and pass it to loadEquation and call interface methods for calculation - for (int i = 0; i < 512; i++) { - x.add(span[0] + i * factor); - switch (function) { - case "sine": - y.add(Math.sin(x.get(i))); - break; - case "tria": - y.add(Math.abs(x.get(i) % 4 - 2)); - break; - } - } - loadTable(channel, y, waveType.get(channel), -1); - } - - private void loadTable(String channel, ArrayList y, String mode, double amp) { - waveType.put(channel, mode); - ArrayList channels = new ArrayList<>(); - ArrayList points = y; - channels.add("SI1"); - channels.add("SI2"); - int num; - if (channels.contains(channel)) { - num = channels.indexOf(channel) + 1; - } else { - Log.e(TAG, "Channel does not exist. Try SI1 or SI2"); - return; - } - - if (amp == -1) amp = 0.95; - double LARGE_MAX = 511 * amp, SMALL_MAX = 63 * amp; - double min = Collections.min(y); - for (int i = 0; i < y.size(); i++) { - y.set(i, y.get(i) - min); - } - double max = Collections.max(y); - ArrayList yMod1 = new ArrayList<>(); - for (int i = 0; i < y.size(); i++) { - double temp = 1 - (y.get(i) / max); - yMod1.add((int) Math.round(LARGE_MAX - LARGE_MAX * temp)); - } - y = new ArrayList(); - - - for (int i = 0; i < points.size(); i += 16) { - y.add(points.get(i)); - } - min = Collections.min(y); - for (int i = 0; i < y.size(); i++) { - y.set(i, y.get(i) - min); - } - max = Collections.max(y); - ArrayList yMod2 = new ArrayList<>(); - for (int i = 0; i < y.size(); i++) { - double temp = 1 - (y.get(i) / max); - yMod2.add((int) Math.round(SMALL_MAX - SMALL_MAX * temp)); - } - - try { - mPacketHandler.sendByte(mCommandsProto.WAVEGEN); - switch (num) { - case 1: - mPacketHandler.sendByte(mCommandsProto.LOAD_WAVEFORM1); - break; - case 2: - mPacketHandler.sendByte(mCommandsProto.LOAD_WAVEFORM2); - break; - } - for (int a : yMod1) - mPacketHandler.sendInt(a); - - for (int a : yMod2) - mPacketHandler.sendByte(a); - - // sleep for 0.01 - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - - public double setSqr1(double frequency, double dutyCycle, boolean onlyPrepare) { - if (dutyCycle == -1) dutyCycle = 50; - if (frequency == 0 || dutyCycle == 0) return -1; - if (frequency > 10e6) { - Log.v(TAG, "Frequency is greater than 10MHz. Please use map_reference_clock for 16 & 32MHz outputs"); - return 0; - } - int[] p = new int[]{1, 8, 64, 256}; - int prescalar = 0; - int wavelength = 0; - while (prescalar <= 3) { - wavelength = (int) (64e6 / frequency / p[prescalar]); - if (wavelength < 65525) break; - prescalar++; - } - if (prescalar == 4 || wavelength == 0) { - Log.v(TAG, "Out of Range"); - return -1; - } - int highTime = (int) (wavelength * dutyCycle / 100); - if (onlyPrepare) { - Map args = new LinkedHashMap<>(); - args.put("SQR1", 0); - this.setState(args); - } - try { - mPacketHandler.sendByte(mCommandsProto.WAVEGEN); - mPacketHandler.sendByte(mCommandsProto.SET_SQR1); - mPacketHandler.sendInt(Math.round(wavelength)); - mPacketHandler.sendInt(Math.round(highTime)); - if (onlyPrepare) prescalar |= 0x4; - mPacketHandler.sendByte(prescalar); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - this.squareWaveFrequency.put("SQR1", 64e6 / wavelength / p[prescalar & 0x3]); - return this.squareWaveFrequency.get("SQR1"); - } - - public double setSqr2(double frequency, double dutyCycle) { - int[] p = new int[]{1, 8, 64, 256}; - int prescalar = 0; - int wavelength = 0; - while (prescalar <= 3) { - wavelength = (int) (64e6 / frequency / p[prescalar]); - if (wavelength < 65525) break; - prescalar++; - } - if (prescalar == 4 || wavelength == 0) { - Log.v(TAG, "Out of Range"); - return -1; - } - int highTime = (int) (wavelength * dutyCycle / 100); - try { - mPacketHandler.sendByte(mCommandsProto.WAVEGEN); - mPacketHandler.sendByte(mCommandsProto.SET_SQR2); - mPacketHandler.sendInt(Math.round(wavelength)); - mPacketHandler.sendInt(Math.round(highTime)); - mPacketHandler.sendByte(prescalar); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - this.squareWaveFrequency.put("SQR2", 64e6 / wavelength / p[prescalar & 0x3]); - return this.squareWaveFrequency.get("SQR2"); - } - - public void setSqrs(int wavelength, int phase, int highTime1, int highTime2, int prescalar) { - if (prescalar == -1) prescalar = 1; - try { - mPacketHandler.sendByte(mCommandsProto.WAVEGEN); - mPacketHandler.sendByte(mCommandsProto.SET_SQRS); - mPacketHandler.sendInt(wavelength); - mPacketHandler.sendInt(phase); - mPacketHandler.sendInt(highTime1); - mPacketHandler.sendInt(highTime2); - mPacketHandler.sendByte(prescalar); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public double sqrPWM(double frequency, double h0, double p1, double h1, double p2, double h2, double p3, double h3, boolean pulse) { - if (frequency == 0) return -1; - if (h0 == 0) { - h0 = 0.1; - } - if (h1 == 0) { - h1 = 0.1; - } - if (h2 == 0) { - h2 = 0.1; - } - if (h3 == 0) { - h3 = 0.1; - } - if (frequency > 10e6) { - Log.v(TAG, "Frequency is greater than 10MHz. Please use map_reference_clock for 16 & 32MHz outputs"); - return -1; - } - int[] p = new int[]{1, 8, 64, 256}; - int prescalar = 0, wavelength = 0; - while (prescalar <= 3) { - wavelength = (int) (64e6 / frequency / p[prescalar]); - if (wavelength < 65525) break; - prescalar++; - } - if (prescalar == 4 || wavelength == 0) { - Log.v(TAG, "Out of Range"); - return -1; - } - if (!pulse) prescalar |= (1 << 5); - int a1 = (int) (p1 % 1 * wavelength), b1 = (int) ((h1 + p1) % 1 * wavelength); - int a2 = (int) (p2 % 1 * wavelength), b2 = (int) ((h2 + p2) % 1 * wavelength); - int a3 = (int) (p3 % 1 * wavelength), b3 = (int) ((h3 + p3) % 1 * wavelength); - try { - mPacketHandler.sendByte(mCommandsProto.WAVEGEN); - mPacketHandler.sendByte(mCommandsProto.SQR4); - mPacketHandler.sendInt(wavelength - 1); - mPacketHandler.sendInt((int) (wavelength * h0) - 1); - mPacketHandler.sendInt(Math.max(0, a1 - 1)); - mPacketHandler.sendInt(Math.max(1, b1 - 1)); - mPacketHandler.sendInt(Math.max(0, a2 - 1)); - mPacketHandler.sendInt(Math.max(1, b2 - 1)); - mPacketHandler.sendInt(Math.max(0, a3 - 1)); - mPacketHandler.sendInt(Math.max(1, b3 - 1)); - mPacketHandler.sendByte(prescalar); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - for (String channel : new String[]{"SQR1", "SQR2", "SQR3", "SQR4"}) { - this.squareWaveFrequency.put(channel, 64e6 / wavelength / p[prescalar & 0x3]); - } - return (int) (64e6 / wavelength / p[prescalar & 0x3]); - } - - public void mapReferenceClock(ArrayList args, int scalar) { - try { - mPacketHandler.sendByte(mCommandsProto.WAVEGEN); - mPacketHandler.sendByte(mCommandsProto.MAP_REFERENCE); - int channel = 0; - if (args.contains("SQR1")) channel |= 1; - if (args.contains("SQR2")) channel |= 2; - if (args.contains("SQR3")) channel |= 4; - if (args.contains("SQR4")) channel |= 8; - if (args.contains("WAVEGEN")) channel |= 16; - mPacketHandler.sendByte(channel); - mPacketHandler.sendByte(scalar); - if (args.contains("WAVEGEN")) { - this.DDS_CLOCK = (int) 128e6 / (1 << scalar); - } - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /* ANALOG OUTPUTS */ - - public void setVoltage(String channel, float voltage) { - DACChannel dacChannel = dacChannels.get(channel); - int v = (int) (Math.round(dacChannel.VToCode.value(voltage))); - try { - mPacketHandler.sendByte(mCommandsProto.DAC); - mPacketHandler.sendByte(mCommandsProto.SET_POWER); - mPacketHandler.sendByte(dacChannel.channelCode); - mPacketHandler.sendInt(v); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - values.put(channel, (double) voltage); - } - - private void setCurrent(float current) { - DACChannel dacChannel = dacChannels.get("PCS"); - int v = 3300 - (int) (Math.round(dacChannel.VToCode.value(current))); - try { - mPacketHandler.sendByte(mCommandsProto.DAC); - mPacketHandler.sendByte(mCommandsProto.SET_POWER); - mPacketHandler.sendByte(dacChannel.channelCode); - mPacketHandler.sendInt(v); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - values.put("PCS", (double) current); - } - - private double getVoltage(String channel) { - return this.values.get(channel); - } - - public void setPV1(float value) { - this.setVoltage("PV1", value); - } - - public void setPV2(float value) { - this.setVoltage("PV2", value); - } - - public void setPV3(float value) { - this.setVoltage("PV3", value); - } - - public void setPCS(float value) { - this.setCurrent(value); - } - - public double getPV1() { - return this.getVoltage("PV1"); - } - - public double getPV2() { - return this.getVoltage("PV2"); - } - - public double getPV3() { - return this.getVoltage("PV3"); - } - - public double getPCS() { - return this.getVoltage("PCS"); - } - - /* READ PROGRAM AND DATA ADDRESSES */ - - public long deviceID() { - long a = readProgramAddress(0x800FF8); - long b = readProgramAddress(0x800FFA); - long c = readProgramAddress(0x800FFC); - long d = readProgramAddress(0x800FFE); - long value = d | (c << 16) | (b << 32) | (a << 48); - Log.v(TAG, "device ID : " + value); - return value; - } - - /** - * Return the value stored at the specified address in program memory. - * - * @param address int - *

Address to read from. Refer to PIC24EP64GP204 programming manual.

- * @return data : int

16-bit wide value read from program memory.

- */ - public int readProgramAddress(int address) { - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.READ_PROGRAM_ADDRESS); - mPacketHandler.sendInt(address & 0xffff); - mPacketHandler.sendInt((address >> 16) & 0xffff); - int data = mPacketHandler.getInt(); - mPacketHandler.getAcknowledgement(); - return data; - } catch (IOException e) { - e.printStackTrace(); - } - return -1; - } - - /** - * Return the value stored at the specified address in RAM. - * - * @param address int - *

Address to read from. Refer to PIC24EP64GP204 programming manual.

- * @return data : int

16-bit wide value read from RAM.

- */ - public int readDataAddress(int address) { - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.READ_DATA_ADDRESS); - mPacketHandler.sendInt(address & 0xffff); - int data = mPacketHandler.getInt(); - mPacketHandler.getAcknowledgement(); - return data; - } catch (IOException e) { - e.printStackTrace(); - } - return -1; - } - - /** - * Write a value to the specified address in RAM. - * - * @param address int - *

Address to write to. Refer to PIC24EP64GP204 programming manual.

- * @param value int - *

Value to write to RAM.

- */ - public void writeDataAddress(int address, int value) { - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.WRITE_DATA_ADDRESS); - mPacketHandler.sendInt(address & 0xffff); - mPacketHandler.sendInt(value); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Relay all data received by the device to TXD/RXD. - *

- * If a period > 0.5 seconds elapses between two transmit/receive events, - * the device resets and resumes normal mode. This timeout feature has - * been implemented in lieu of a hard reset option. - *

- *

- * Can be used to load programs into secondary microcontrollers with - * bootloaders such as ATMEGA OR ESP8266. - *

- * - * @param baudrate int - *

Baudrate of the UART bus.

- * @param persist bool, optional - *

If set to True, the device will stay in passthrough mode until the - * next power cycle. Otherwise(default scenario), the device will - * return to normal operation if no data is sent/received for a period - * greater than one second at a time.

- */ - public void enableUARTPassThrough(int baudrate, boolean persist) { - try { - mPacketHandler.sendByte(mCommandsProto.PASSTHROUGHS); - mPacketHandler.sendByte(mCommandsProto.PASS_UART); - if (persist) - mPacketHandler.sendByte(1); - else - mPacketHandler.sendByte(0); - mPacketHandler.sendInt((int) Math.round(((64e6 / baudrate) / 4) - 1)); - Log.v(TAG, "BRG2VAL: " + Math.round(((64e6 / baudrate) / 4) - 1)); - // sleep for 0.1 sec - byte[] junk = new byte[100]; - mPacketHandler.read(junk, 100); - // Log junk to see :D - } catch (IOException e) { - e.printStackTrace(); - } - } - - /* MOTOR SIGNALLING */ - - public void servo4(double angle1, double angle2, double angle3, double angle4) { - int params = (1 << 5) | 2; - try { - mPacketHandler.sendByte(mCommandsProto.WAVEGEN); - mPacketHandler.sendByte(mCommandsProto.SQR4); - mPacketHandler.sendInt(10000); - mPacketHandler.sendInt(750 + (int) (angle1 * 1900 / 180)); - mPacketHandler.sendInt(0); - mPacketHandler.sendInt(750 + (int) (angle2 * 1900 / 180)); - mPacketHandler.sendInt(0); - mPacketHandler.sendInt(750 + (int) (angle3 * 1900 / 180)); - mPacketHandler.sendInt(0); - mPacketHandler.sendInt(750 + (int) (angle4 * 1900 / 180)); - mPacketHandler.sendByte(params); - mPacketHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Read hardware debug log. - * - * @return log : String

Bytes read from the hardware debug log.

- */ - public String readLog() { - String log = ""; - try { - mPacketHandler.sendByte(mCommandsProto.COMMON); - mPacketHandler.sendByte(mCommandsProto.READ_LOG); - } catch (IOException e) { - e.printStackTrace(); - } - return mPacketHandler.readLine(); - } - - public void disconnect() throws IOException { - mCommunicationHandler.close(); - PacketHandler.version = ""; - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/communication/SensorList.java b/app/src/main/java/io/pslab/communication/SensorList.java deleted file mode 100644 index 2ff102ba5..000000000 --- a/app/src/main/java/io/pslab/communication/SensorList.java +++ /dev/null @@ -1,54 +0,0 @@ -package io.pslab.communication; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by viveksb007 on 30/3/17. - */ - -public class SensorList { - - public Map sensorList = new HashMap<>(); - - public SensorList() { - sensorList.put(0x00, new String[]{"Could be MLX90614. Try 0x5A"}); - sensorList.put(0x13, new String[]{"VCNL4000"}); - sensorList.put(0x3c, new String[]{"OLED SSD1306"}); - sensorList.put(0x3d, new String[]{"OLED SSD1306"}); - sensorList.put(0x48, new String[]{"PN532 RFID"}); - sensorList.put(0x29, new String[]{"TSL2561"}); - sensorList.put(0x39, new String[]{"TSL2561"}); - sensorList.put(0x49, new String[]{"TSL2561"}); - sensorList.put(0x1D, new String[]{"ADXL345", "MMA7455L", "LSM9DSO"}); - sensorList.put(0x53, new String[]{"ADXL345"}); - sensorList.put(0x5A, new String[]{"MLX90614 PIR temperature"}); - sensorList.put(0x1E, new String[]{"HMC5883L magnetometer", "LSM303 magnetometer"}); - sensorList.put(0x77, new String[]{"BMP180/GY-68 altimeter", "MS5607", "MS5611"}); - sensorList.put(0x68, new String[]{"MPU-6050/GY-521 accel+gyro+temp", "ITG3200", "DS1307", "DS3231"}); - sensorList.put(0x69, new String[]{"ITG3200"}); - sensorList.put(0x76, new String[]{"MS5607", "MS5611"}); - sensorList.put(0x6B, new String[]{"LSM9DSO gyro"}); - sensorList.put(0x19, new String[]{"LSM303 accel"}); - sensorList.put(0x20, new String[]{"MCP23008", "MCP23017"}); - sensorList.put(0x21, new String[]{"MCP23008", "MCP23017"}); - sensorList.put(0x22, new String[]{"MCP23008", "MCP23017"}); - sensorList.put(0x23, new String[]{"BH1750", "MCP23008", "MCP23017"}); - sensorList.put(0x24, new String[]{"MCP23008", "MCP23017"}); - sensorList.put(0x25, new String[]{"MCP23008", "MCP23017"}); - sensorList.put(0x26, new String[]{"MCP23008", "MCP23017"}); - sensorList.put(0x27, new String[]{"MCP23008", "MCP23017"}); - sensorList.put(0x40, new String[]{"SHT21(Temp/RH)"}); - sensorList.put(0x60, new String[]{"MCP4725A0 4 chan DAC (onBoard)"}); - sensorList.put(0x61, new String[]{"MCP4725A0 4 chan DAC"}); - sensorList.put(0x62, new String[]{"MCP4725A1 4 chan DAC"}); - sensorList.put(0x63, new String[]{"MCP4725A1 4 chan DAC", "Si4713"}); - sensorList.put(0x64, new String[]{"MCP4725A2 4 chan DAC"}); - sensorList.put(0x65, new String[]{"MCP4725A2 4 chan DAC"}); - sensorList.put(0x66, new String[]{"MCP4725A3 4 chan DAC"}); - sensorList.put(0x67, new String[]{"MCP4725A3 4 chan DAC"}); - sensorList.put(0x11, new String[]{"Si4713"}); - sensorList.put(0x38, new String[]{"FT6206 touch controller"}); - sensorList.put(0x41, new String[]{"STMPE610"}); - } -} diff --git a/app/src/main/java/io/pslab/communication/analogChannel/AnalogAquisitionChannel.java b/app/src/main/java/io/pslab/communication/analogChannel/AnalogAquisitionChannel.java deleted file mode 100644 index 735766477..000000000 --- a/app/src/main/java/io/pslab/communication/analogChannel/AnalogAquisitionChannel.java +++ /dev/null @@ -1,79 +0,0 @@ -package io.pslab.communication.analogChannel; - -import java.util.Arrays; - -/** - * Created by viveksb007 on 24/3/17. - */ - -public class AnalogAquisitionChannel { - - private int resolution; - private AnalogInputSource analogInputSource; - private double gain; - private String channel; - public int bufferIndex; - private double calibration_ref196; - public int length; - private double timebase; - private double[] xAxis = new double[10000]; - public double[] yAxis = new double[10000]; - - public AnalogAquisitionChannel(String channel) { - gain = 0; - this.channel = channel; - calibration_ref196 = 1.; - resolution = 10; - length = 100; - timebase = 1.; - bufferIndex = 0; - Arrays.fill(xAxis, 0); - Arrays.fill(yAxis, 0); - analogInputSource = new AnalogInputSource("CH1"); - } - - public double[] fixValue(double[] val) { - double[] calcData = new double[val.length]; - if (resolution == 12) - for (int i = 0; i < val.length; i++) - calcData[i] = calibration_ref196 * (analogInputSource.calPoly12.value(val[i])); - else - for (int i = 0; i < val.length; i++) - calcData[i] = calibration_ref196 * (analogInputSource.calPoly10.value(val[i])); - return calcData; - } - - void setYVal(int pos, int val) { - yAxis[pos] = fixValue(new double[]{val})[0]; - } - - void setXVal(int pos, int val) { - xAxis[pos] = fixValue(new double[]{val})[0]; - } - - public void setParams(String channel, int length, int bufferIndex, double timebase, int resolution, AnalogInputSource source, Double gain) { - if (gain != null) this.gain = gain; - if (source != null) this.analogInputSource = source; - if (channel != null) this.channel = channel; - if (resolution != -1) this.resolution = resolution; - if (length != -1) this.length = length; - if (bufferIndex != -1) this.bufferIndex = bufferIndex; - if (timebase != -1) this.timebase = timebase; - regenerateXAxis(); - } - - void regenerateXAxis() { - for (int i = 0; i < length; i++) { - xAxis[i] = timebase * i; - } - } - - public double[] getXAxis() { - return Arrays.copyOfRange(xAxis, 0, length); - } - - public double[] getYAxis() { - return Arrays.copyOfRange(yAxis, 0, length); - } - -} diff --git a/app/src/main/java/io/pslab/communication/analogChannel/AnalogConstants.java b/app/src/main/java/io/pslab/communication/analogChannel/AnalogConstants.java deleted file mode 100644 index 294998ca5..000000000 --- a/app/src/main/java/io/pslab/communication/analogChannel/AnalogConstants.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.pslab.communication.analogChannel; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by viveksb007 on 24/3/17. - */ - -public class AnalogConstants { - - public double[] gains = {1, 2, 4, 5, 8, 10, 16, 32, 1 / 11.}; - public String[] allAnalogChannels = {"CH1", "CH2", "CH3", "MIC", "CAP", "RES", "VOL"}; - public String[] biPolars = {"CH1", "CH2", "CH3", "MIC"}; - public Map inputRanges = new HashMap<>(); - public Map picADCMultiplex = new HashMap<>(); - - public AnalogConstants() { - - inputRanges.put("CH1", new double[]{16.5, -16.5}); - inputRanges.put("CH2", new double[]{16.5, -16.5}); - inputRanges.put("CH3", new double[]{-3.3, 3.3}); - inputRanges.put("MIC", new double[]{-3.3, 3.3}); - inputRanges.put("CAP", new double[]{0, 3.3}); - inputRanges.put("RES", new double[]{0, 3.3}); - inputRanges.put("VOL", new double[]{0, 3.3}); - - picADCMultiplex.put("CH1", 3); - picADCMultiplex.put("CH2", 0); - picADCMultiplex.put("CH3", 1); - picADCMultiplex.put("MIC", 2); - picADCMultiplex.put("AN4", 4); - picADCMultiplex.put("RES", 7); - picADCMultiplex.put("CAP", 5); - picADCMultiplex.put("VOL", 8); - - } -} - diff --git a/app/src/main/java/io/pslab/communication/analogChannel/AnalogInputSource.java b/app/src/main/java/io/pslab/communication/analogChannel/AnalogInputSource.java deleted file mode 100644 index 21cfa9283..000000000 --- a/app/src/main/java/io/pslab/communication/analogChannel/AnalogInputSource.java +++ /dev/null @@ -1,136 +0,0 @@ -package io.pslab.communication.analogChannel; - -import android.util.Log; - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; - -import java.util.ArrayList; -import java.util.List; - -public class AnalogInputSource { - - private static String TAG = "AnalogInputSource"; - - private double gainValues[], range[]; - public boolean gainEnabled = false, inverted = false, calibrationReady = false; - private double gain = 0; - public int gainPGA, CHOSA; - private int inversion = 1; - private int defaultOffsetCode = 0; - private int scaling = 1; - private String channelName; - public PolynomialFunction calPoly10; - public PolynomialFunction calPoly12; - public PolynomialFunction voltToCode10; - public PolynomialFunction voltToCode12; - private List adc_shifts = new ArrayList<>(); - private List polynomials = new ArrayList<>(); //list of maps - - public AnalogInputSource(String channelName) { - AnalogConstants analogConstants = new AnalogConstants(); - this.channelName = channelName; - range = analogConstants.inputRanges.get(channelName); - gainValues = analogConstants.gains; - this.CHOSA = analogConstants.picADCMultiplex.get(channelName); - - calPoly10 = new PolynomialFunction(new double[]{0., 3.3 / 1023, 0.}); - calPoly12 = new PolynomialFunction(new double[]{0., 3.3 / 4095, 0.}); - - if (range[1] - range[0] < 0) { - inverted = true; - inversion = -1; - } - if (channelName.equals("CH1")) { - gainEnabled = true; - gainPGA = 1; - gain = 0; - } else if (channelName.equals("CH2")) { - gainEnabled = true; - gainPGA = 2; - gain = 0; - } - gain = 0; - regenerateCalibration(); - } - - public Boolean setGain(int index) { - if (!gainEnabled) { - Log.e(channelName, "Analog gain is not available"); - return false; - } - gain = gainValues[index]; - regenerateCalibration(); - return true; - } - - boolean inRange(double val) { - double sum = voltToCode12.value(val); - return sum >= 50 && sum <= 4095; - } - - boolean conservativeInRange(double val) { - double solution = voltToCode12.value(val); - return solution >= 50 && solution <= 4000; - } - - public List loadCalibrationTable(double[] table, double slope, double intercept) { - for (double aTable : table) { - adc_shifts.add(aTable * slope - intercept); - } - return adc_shifts; - } - - public void ignoreCalibration() { - calibrationReady = false; - } - - public void loadPolynomials(ArrayList polys) { - for (int i = 0; i < polys.size(); i++) { - double[] temp = ArrayUtils.toPrimitive(polys.get(i)); - ArrayUtils.reverse(temp); - polynomials.add(new PolynomialFunction(temp)); - } - } - - public void regenerateCalibration() { - double A, B, intercept, slope; - B = range[1]; - A = range[0]; - if (gain >= 0 && gain<=8) { - gain = gainValues[(int) gain]; - B /= gain; - A /= gain; - } - slope = 2 * (B - A); - intercept = 2 * A; - if (!calibrationReady || gain == 8) { - calPoly10 = new PolynomialFunction(new double[]{intercept, slope / 1023, 0.}); - calPoly12 = new PolynomialFunction(new double[]{intercept, slope / 4095, 0.}); - }//else cases need to be worked on!!! - - voltToCode10 = new PolynomialFunction(new double[]{-1023 * intercept / slope, 1023. / slope, 0.}); - voltToCode12 = new PolynomialFunction(new double[]{-4095 * intercept / slope, 4095., 0.}); - } - - public double[] cal12(double[] RAW) { - double[] calcData = new double[RAW.length]; - for (int i = 0; i < RAW.length; i++) { - double avg_shifts = (adc_shifts.get((int) Math.floor(RAW[i])) + adc_shifts.get((int) Math.ceil(RAW[i]))) / 2; - RAW[i] -= 4095 * avg_shifts / 3.3; - calcData[i] = (polynomials.get((int) gain).value(RAW[i])); - } - return calcData; - } - - public double[] cal10(double[] RAW) { - double[] calcData = new double[RAW.length]; - for (int i = 0; i < RAW.length; i++) { - RAW[i] *= 4095 / 1023; - double avg_shifts = (adc_shifts.get((int) Math.floor(RAW[i])) + adc_shifts.get((int) Math.ceil(RAW[i]))) / 2; - RAW[i] -= 4095 * avg_shifts / 3.3; - calcData[i] = (polynomials.get((int) gain).value(RAW[i])); - } - return calcData; - } -} diff --git a/app/src/main/java/io/pslab/communication/digitalChannel/DigitalChannel.java b/app/src/main/java/io/pslab/communication/digitalChannel/DigitalChannel.java deleted file mode 100644 index c934e998f..000000000 --- a/app/src/main/java/io/pslab/communication/digitalChannel/DigitalChannel.java +++ /dev/null @@ -1,156 +0,0 @@ -package io.pslab.communication.digitalChannel; - -import java.util.Arrays; -import java.util.LinkedHashMap; - -/** - * Created by viveksb007 on 26/3/17. - */ - -public class DigitalChannel { - - public static final int EVERY_EDGE = 1; - public static final int DISABLED = 0; - private static final int EVERY_SIXTEENTH_RISING_EDGE = 5; - private static final int EVERY_FOURTH_RISING_EDGE = 4; - private static final int EVERY_RISING_EDGE = 3; - private static final int EVERY_FALLING_EDGE = 2; - public static String[] digitalChannelNames = {"LA1", "LA2", "LA3", "LA4", "RES", "EXT", "FRQ"}; - public String channelName, dataType; - public int initialStateOverride, channelNumber, length, prescalar, trigger, dlength, plotLength, maxTime, mode; - public double xAxis[], yAxis[], timestamps[]; - boolean initialState; - double gain, maxT; - - public DigitalChannel(int channelNumber) { - this.channelNumber = channelNumber; - this.channelName = digitalChannelNames[channelNumber]; - this.gain = 0; - this.xAxis = new double[20000]; - this.yAxis = new double[20000]; - this.timestamps = new double[10000]; - this.length = 100; - this.initialState = false; - this.prescalar = 0; - this.dataType = "int"; - this.trigger = 0; - this.dlength = 0; - this.plotLength = 0; - this.maxT = 0; - this.maxTime = 0; - this.initialStateOverride = 0; - this.mode = EVERY_EDGE; - } - - void setParams(String channelName, int channelNumber) { - this.channelName = channelName; - this.channelNumber = channelNumber; - } - - void setPrescalar(int prescalar) { - this.prescalar = prescalar; - } - - public void loadData(LinkedHashMap initialStates, double[] timestamps) { - if (initialStateOverride != 0) { - this.initialState = (initialStateOverride - 1) == 1; - this.initialStateOverride = 0; - } else { - final Integer s = initialStates.get(channelName); - this.initialState = s != null && s == 1; - } - System.arraycopy(timestamps, 0, this.timestamps, 0, timestamps.length); - this.dlength = timestamps.length; // - double factor; - switch (prescalar) { - case 0: - factor = 64; - break; - case 1: - factor = 8; - break; - case 2: - factor = 4; - break; - default: - factor = 1; - } - for (int i = 0; i < this.timestamps.length; i++) this.timestamps[i] /= factor; - if (dlength > 0) - this.maxT = this.timestamps[this.timestamps.length - 1]; - else - this.maxT = 0; - - } - - public void generateAxes() { - int HIGH = 1, LOW = 0, state; - if (initialState) - state = LOW; - else - state = HIGH; - - if (this.mode == DISABLED) { - xAxis[0] = 0; - yAxis[0] = 0; - this.plotLength = 1; - } else if (this.mode == EVERY_EDGE) { - xAxis[0] = 0; - yAxis[0] = state; - int i, j; - for (i = 1, j = 1; i < this.dlength; i++, j++) { - xAxis[j] = timestamps[i]; - yAxis[j] = state; - if (state == HIGH) - state = LOW; - else - state = HIGH; - j++; - xAxis[j] = timestamps[i]; - yAxis[j] = state; - } - plotLength = j; - } else if (this.mode == EVERY_FALLING_EDGE) { - xAxis[0] = 0; - yAxis[0] = HIGH; - int i, j; - for (i = 1, j = 1; i < this.dlength; i++, j++) { - xAxis[j] = timestamps[i]; - yAxis[j] = HIGH; - j++; - xAxis[j] = timestamps[i]; - yAxis[j] = LOW; - j++; - xAxis[j] = timestamps[i]; - yAxis[j] = HIGH; - } - state = HIGH; - plotLength = j; - } else if (this.mode == EVERY_RISING_EDGE || this.mode == EVERY_FOURTH_RISING_EDGE || this.mode == EVERY_SIXTEENTH_RISING_EDGE) { - xAxis[0] = 0; - yAxis[0] = LOW; - int i, j; - for (i = 1, j = 1; i < this.dlength; i++, j++) { - xAxis[j] = timestamps[i]; - yAxis[j] = LOW; - j++; - xAxis[j] = timestamps[i]; - yAxis[j] = HIGH; - j++; - xAxis[j] = timestamps[i]; - yAxis[j] = LOW; - } - state = LOW; - plotLength = j; - } - - } - - public double[] getXAxis() { - return Arrays.copyOfRange(this.xAxis, 0, plotLength); - } - - public double[] getYAxis() { - return Arrays.copyOfRange(this.yAxis, 0, plotLength); - } -} diff --git a/app/src/main/java/io/pslab/communication/peripherals/DACChannel.java b/app/src/main/java/io/pslab/communication/peripherals/DACChannel.java deleted file mode 100644 index 2a58fc2b1..000000000 --- a/app/src/main/java/io/pslab/communication/peripherals/DACChannel.java +++ /dev/null @@ -1,69 +0,0 @@ -package io.pslab.communication.peripherals; - -import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; - -import java.util.ArrayList; -import java.util.List; -/** - * Created by viveksb007 on 28/3/17. - */ - -public class DACChannel { - private String name; - int channum; - private int offset; - public double[] range; - private double slope, intercept; - public PolynomialFunction VToCode; - public int channelCode; - PolynomialFunction CodeToV; - String calibrationEnabled; - private List calibrationTable = new ArrayList<>(); - - public DACChannel(String name, double[] span, int channum, int channelCode) { - this.name = name; - this.range = span; - this.channum = channum; - this.slope = span[1] - span[0]; - this.intercept = span[0]; - this.VToCode = new PolynomialFunction(new double[]{-3300. * intercept / slope, 3300. / slope}); - this.CodeToV = new PolynomialFunction(new double[]{intercept, slope / 3300.}); - this.calibrationEnabled = "false"; - this.slope = 1; - this.offset = 0; - this.channelCode = channelCode; - } - - public void loadCalibrationTable(List table) { - calibrationEnabled = "table"; - calibrationTable = table; - } - - public void loadCalibrationTwopoint(double slope, int offset) { - calibrationEnabled = "twopoint"; - this.slope = slope; - this.offset = offset; - } - - int applyCalibration(int v) { - if (calibrationEnabled.equals("table")) { - if (v + calibrationTable.get(v) <= 0) { - return 0; - } else if (v + calibrationTable.get(v) > 0 && v + calibrationTable.get(v) < 4095) { - return ((int) (v + calibrationTable.get(v))); - } else { - return 4095; - } - } else if (calibrationEnabled.equals("twopoint")) { - if (slope * v + offset <= 0) { - return 0; - } else if (slope * v + offset > 0 && slope * v + offset < 4095) { - return ((int) (slope * v + offset)); - } else { - return 4095; - } - } else { - return v; - } - } -} diff --git a/app/src/main/java/io/pslab/communication/peripherals/I2C.java b/app/src/main/java/io/pslab/communication/peripherals/I2C.java deleted file mode 100644 index 4f5802056..000000000 --- a/app/src/main/java/io/pslab/communication/peripherals/I2C.java +++ /dev/null @@ -1,284 +0,0 @@ -package io.pslab.communication.peripherals; - -import android.os.SystemClock; -import android.util.Log; - -import io.pslab.communication.CommandsProto; -import io.pslab.communication.PacketHandler; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * Created by viveksb007 on 28/3/17. - */ - -public class I2C { - - private static final String TAG = "I2C"; - private double[] buffer; - private int frequency = 100000; - private CommandsProto commandsProto; - private PacketHandler packetHandler; - private int totalBytes, channels, samples, timeGap; - - public I2C(PacketHandler packetHandler) { - this.buffer = new double[10000]; - Arrays.fill(buffer, 0); - this.packetHandler = packetHandler; - this.commandsProto = new CommandsProto(); - } - - public void init() throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_INIT); - packetHandler.getAcknowledgement(); // can check success or failure by ack - } - - public void enableSMBus() throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_ENABLE_SMBUS); - packetHandler.getAcknowledgement(); - } - - public void pullSCLLow(int uSec) throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_PULLDOWN_SCL); - packetHandler.sendInt(uSec); - packetHandler.getAcknowledgement(); - } - - public void config(int frequency) throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_CONFIG); - int BRGVAL = (int) ((1 / frequency - 1 / 1e7) * 64e6 - 1); - if (BRGVAL > 511) { - BRGVAL = 511; - Log.v(TAG, "Frequency too low. Setting to : " + String.valueOf(1 / ((BRGVAL + 1.0) / 64e6 + 1.0 / 1e7))); - } - packetHandler.sendInt(BRGVAL); - packetHandler.getAcknowledgement(); - } - - public int start(int address, int rw) throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_START); - packetHandler.sendByte((address << 1) | rw & 0xff); - return (packetHandler.getAcknowledgement() >> 4); - } - - public void stop() throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_STOP); - packetHandler.getAcknowledgement(); - } - - public void _wait() throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_WAIT); - packetHandler.getAcknowledgement(); - } - - public int send(int data) throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_SEND); - packetHandler.sendByte(data); - return (packetHandler.getAcknowledgement() >> 4); - } - - public int restart(int address, int rw) throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_RESTART); - packetHandler.sendByte((address << 1) | rw & 0xff); - return (packetHandler.getAcknowledgement() >> 4); - } - - public ArrayList simpleRead(int address, int numBytes) throws IOException { - this.start(address, 1); - return this.read(numBytes); - } - - public ArrayList read(int length) throws IOException { - ArrayList data = new ArrayList<>(); - for (int i = 0; i < length - 1; i++) { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_READ_MORE); - data.add(packetHandler.getByte()); - packetHandler.getAcknowledgement(); - } - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_READ_END); - data.add(packetHandler.getByte()); - packetHandler.getAcknowledgement(); - return data; - } - - public byte readRepeat() throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_READ_MORE); - byte val = packetHandler.getByte(); - packetHandler.getAcknowledgement(); - return val; - } - - public byte readEnd() throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_READ_END); - byte val = packetHandler.getByte(); - packetHandler.getAcknowledgement(); - return val; - } - - public int readStatus() throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_STATUS); - int val = packetHandler.getInt(); - packetHandler.getAcknowledgement(); - return val; - } - - public ArrayList readBulk(int deviceAddress, int registerAddress, int bytesToRead) throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_READ_BULK); - packetHandler.sendByte(deviceAddress); - packetHandler.sendByte(registerAddress); - packetHandler.sendByte(bytesToRead); - byte[] data = new byte[bytesToRead + 1]; - packetHandler.read(data, bytesToRead + 1); - ArrayList intData = new ArrayList<>(); - for (byte b : data) { - intData.add((int) b); - } - return intData; - } - - public ArrayList read(int deviceAddress, int bytesToRead, int registerAddress) throws IOException { - return readBulk(deviceAddress, registerAddress, bytesToRead); - } - - public int readByte(int deviceAddress, int registerAddress) throws IOException { - return read(deviceAddress, 1, registerAddress).get(0); - } - - public int readInt(int deviceAddress, int registerAddress) throws IOException { - ArrayList data = read(deviceAddress, 2, registerAddress); - return data.get(0) << 8 | data.get(1); - } - - public long readLong(int deviceAddress, int registerAddress) throws IOException { - ArrayList data = read(deviceAddress, 4, registerAddress); - return data.get(0) << 24 | data.get(1) << 16 | data.get(2) << 8 | data.get(3); - } - - public void writeBulk(int deviceAddress, int[] data) throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_WRITE_BULK); - packetHandler.sendByte(deviceAddress); - packetHandler.sendByte(data.length); - for (int aData : data) { - packetHandler.sendByte(aData); - } - packetHandler.getAcknowledgement(); - } - - public void write(int deviceAddress, int[] data, int registerAddress) throws IOException { - int[] finalData = new int[data.length + 1]; - finalData[0] = registerAddress; - System.arraycopy(data, 0, finalData, 1, data.length); - writeBulk(deviceAddress, finalData); - } - - public void writeByte(int deviceAddress, int registerAddress, int data) throws IOException { - write(deviceAddress, new int[]{data}, registerAddress); - } - - public void writeInt(int deviceAddress, int registerAddress, int data) throws IOException { - write(deviceAddress, new int[]{data & 0xff, (data >> 8) & 0xff}, registerAddress); - } - - public void writeLong(int deviceAddress, int registerAddress, long data) throws IOException { - write(deviceAddress, new int[]{(int) (data & 0xff), (int) ((data >> 8) & 0xff), (int) ((data >> 16) & 0xff), (int) ((data >> 24) & 0xff)}, registerAddress); - } - - public ArrayList scan(Integer frequency) throws IOException { - Integer freq = frequency; - if (frequency == null) freq = 125000; - config(freq); - ArrayList addresses = new ArrayList<>(); - for (int i = 0; i < 128; i++) { - int x = start(i, 0); - if ((x & 1) == 0) { - addresses.add(i); - } - stop(); - } - return addresses; - } - - public void sendBurst(int data) throws IOException { - packetHandler.sendByte(commandsProto.I2C_HEADER); - packetHandler.sendByte(commandsProto.I2C_SEND); - packetHandler.sendByte(data); - } - - public ArrayList retreiveBuffer() throws IOException { - int totalIntSamples = totalBytes / 2; - Log.v(TAG, "Fetching samples : " + totalIntSamples + ", split : " + commandsProto.DATA_SPLITTING); - ArrayList listData = new ArrayList<>(); - for (int i = 0; i < (totalIntSamples / commandsProto.DATA_SPLITTING); i++) { - packetHandler.sendByte(commandsProto.ADC); - packetHandler.sendByte(commandsProto.GET_CAPTURE_CHANNEL); - packetHandler.sendByte(0); - packetHandler.sendInt(commandsProto.DATA_SPLITTING); - packetHandler.sendInt(i * commandsProto.DATA_SPLITTING); - int remaining = commandsProto.DATA_SPLITTING * 2 + 1; - // reading in single go, change if create communication problem - byte[] data = new byte[remaining]; - packetHandler.read(data, remaining); - for (int j = 0; j < data.length - 1; j++) - listData.add(data[j]); - } - - if ((totalIntSamples % commandsProto.DATA_SPLITTING) != 0) { - packetHandler.sendByte(commandsProto.ADC); - packetHandler.sendByte(commandsProto.GET_CAPTURE_CHANNEL); - packetHandler.sendByte(0); - packetHandler.sendInt(totalIntSamples % commandsProto.DATA_SPLITTING); - packetHandler.sendInt(totalIntSamples - totalIntSamples % commandsProto.DATA_SPLITTING); - int remaining = 2 * (totalIntSamples % commandsProto.DATA_SPLITTING) + 1; - byte[] data = new byte[remaining]; - packetHandler.read(data, remaining); - for (int j = 0; j < data.length - 1; j++) - listData.add(data[j]); - } - - Log.v(TAG, "Final Pass : length = " + listData.size()); - return listData; - } - - public Map dataProcessor(ArrayList data, Boolean inInt) { - if (inInt) { - for (int i = 0; i < (this.channels * this.samples) / 2; i++) - this.buffer[i] = (data.get(i * 2) << 8) | (data.get(i * 2 + 1)); - } else { - for (int i = 0; i < (this.channels * this.samples); i++) - this.buffer[i] = data.get(i); - } - Map retData = new LinkedHashMap<>(); - ArrayList timeBase = new ArrayList<>(); - double factor = timeGap * (this.samples - 1) / this.samples; - for (double i = 0; i < timeGap * (this.samples - 1); i += factor) timeBase.add(i); - retData.put("time", timeBase); - for (int i = 0; i < this.channels / 2; i++) { - ArrayList yValues = new ArrayList<>(); - for (int j = i; j < this.samples * this.channels / 2; j += this.channels / 2) { - yValues.add(buffer[j]); - } - retData.put("CH" + String.valueOf(i + 1), yValues); - } - return retData; - } -} diff --git a/app/src/main/java/io/pslab/communication/peripherals/MCP4728.java b/app/src/main/java/io/pslab/communication/peripherals/MCP4728.java deleted file mode 100644 index 20841c4cb..000000000 --- a/app/src/main/java/io/pslab/communication/peripherals/MCP4728.java +++ /dev/null @@ -1,81 +0,0 @@ -package io.pslab.communication.peripherals; - -import io.pslab.communication.PacketHandler; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Created by viveksb007 on 28/3/17. - */ - -public class MCP4728 { - - int defaultVDD = 3300; - int RESET = 6; - int WAKEUP = 9; - int UPDATE = 8; - int WRITEALL = 64; - int WRITEONE = 88; - int SEQWRITE = 80; - int VREFWRITE = 128; - int GAINWRITE = 192; - int POWERDOWNWRITE = 160; - int GENERALCALL = 0; - private PacketHandler packetHandler; - private double vref; - private int devid; - private I2C i2c; - private List switchedOff; - private List vRefs; - private Map channelMap = new LinkedHashMap<>(); - private int addr; - - public MCP4728(PacketHandler packetHandler, I2C i2c) { - this.packetHandler = packetHandler; - this.vref = 3.3; - this.devid = 0; - switchedOff = new ArrayList<>(Arrays.asList(0, 0, 0, 0)); - vRefs = new ArrayList<>(Arrays.asList(0, 0, 0, 0)); - this.i2c = i2c; - addr = 0x60 | devid; - channelMap.put(0, "PCS"); - channelMap.put(1, "PV3"); - channelMap.put(2, "PV2"); - channelMap.put(3, "PV1"); - - } - - public void writeAll(int v1, int v2, int v3, int v4) { - try { - i2c.start(addr, 0); - i2c.send((v1 >> 8) & 0xF); - i2c.send(v1 & 0xFF); - i2c.send((v2 >> 8) & 0xF); - i2c.send(v2 & 0xFF); - i2c.send((v3 >> 8) & 0xF); - i2c.send(v3 & 0xFF); - i2c.send((v4 >> 8) & 0xF); - i2c.send(v4 & 0xFF); - i2c.stop(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void stat() { - try { - i2c.start(addr, 0); - i2c.send(0x0); - i2c.restart(addr, 1); - i2c.read(24); - i2c.stop(); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/app/src/main/java/io/pslab/communication/peripherals/NRF24L01.java b/app/src/main/java/io/pslab/communication/peripherals/NRF24L01.java deleted file mode 100644 index 3fc4e4b1a..000000000 --- a/app/src/main/java/io/pslab/communication/peripherals/NRF24L01.java +++ /dev/null @@ -1,530 +0,0 @@ -package io.pslab.communication.peripherals; - -import android.util.Log; - -import io.pslab.communication.CommandsProto; -import io.pslab.communication.PacketHandler; -import io.pslab.communication.SensorList; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * Created by viveksb007 on 28/3/17. - */ - -public class NRF24L01 { - - private static final String TAG = "NRF24L01"; - private int R_REG = 0x00; - private int W_REG = 0x20; - private int RX_PAYLOAD = 0x61; - private int TX_PAYLOAD = 0xA0; - private int ACK_PAYLOAD = 0xA8; - private int FLUSH_TX = 0xE1; - private int FLUSH_RX = 0xE2; - private int ACTIVATE = 0x50; - private int R_STATUS = 0xFF; - - private int NRF_CONFIG = 0x00; - private int EN_AA = 0x01; - private int EN_RXADDR = 0x02; - private int SETUP_AW = 0x03; - private int SETUP_RETR = 0x04; - private int RF_CH = 0x05; - private int RF_SETUP = 0x06; - private int NRF_STATUS = 0x07; - private int OBSERVE_TX = 0x08; - private int CD = 0x09; - private int RX_ADDR_P0 = 0x0A; - private int RX_ADDR_P1 = 0x0B; - private int RX_ADDR_P2 = 0x0C; - private int RX_ADDR_P3 = 0x0D; - private int RX_ADDR_P4 = 0x0E; - private int RX_ADDR_P5 = 0x0F; - private int TX_ADDR = 0x10; - private int RX_PW_P0 = 0x11; - private int RX_PW_P1 = 0x12; - private int RX_PW_P2 = 0x13; - private int RX_PW_P3 = 0x14; - private int RX_PW_P4 = 0x15; - private int RX_PW_P5 = 0x16; - private int R_RX_PL_WID = 0x60; - private int FIFO_STATUS = 0x17; - private int DYNPD = 0x1C; - private int FEATURE = 0x1D; - private int PAYLOAD_SIZE = 0; - private int ACK_PAYLOAD_SIZE = 0; - private int READ_PAYLOAD_SIZE = 0; - - private int ADC_COMMANDS = 1; - private int READ_ADC = 0 << 4; - - private int I2C_COMMANDS = 2; - private int I2C_TRANSACTION = 0 << 4; - private int I2C_WRITE = 1 << 4; - private int I2C_SCAN = 2 << 4; - private int PULL_SCL_LOW = 3 << 4; - private int I2C_CONFIG = 4 << 4; - private int I2C_READ = 5 << 4; - - private int NRF_COMMANDS = 3; - private int NRF_READ_REGISTER = 0; - private int NRF_WRITE_REGISTER = 1 << 4; - - public int CURRENT_ADDRESS = 0xAAAA01; - private int nodePos = 0, status = 0; - private int NODELIST_MAXLENGTH = 15; - public boolean connected = false, ready = false; - - private Map sigs = new LinkedHashMap<>(); - private PacketHandler packetHandler; - private CommandsProto commandsProto; - private Map> nodeList = new LinkedHashMap<>(); - - public NRF24L01(PacketHandler packetHandler) { - this.packetHandler = packetHandler; - this.commandsProto = new CommandsProto(); - sigs.put(CURRENT_ADDRESS, 1); - if (packetHandler.isConnected()) { - connected = init(); - } - } - - private boolean init() { - try { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_SETUP); - packetHandler.getAcknowledgement(); - // add code for sleep for 15mSec - status = getStatus(); - if ((status & 0x80) != 0) { - Log.e(TAG, "Radio transceiver not installed/not found"); - return false; - } else { - ready = true; - } - selectAddress(CURRENT_ADDRESS); - - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - public void selectAddress(int address) { - try { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_WRITEADDRESS); - packetHandler.sendByte(address & 0xff); - packetHandler.sendByte((address >> 8) & 0xff); - packetHandler.sendByte((address >> 16) & 0xff); - packetHandler.getAcknowledgement(); - this.CURRENT_ADDRESS = address; - if (!sigs.containsKey(address)) { - sigs.put(address, 1); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void writeAddress(int register, int address) { - try { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_WRITEADDRESSES); - packetHandler.sendByte(register); - packetHandler.sendByte(address & 0xff); - packetHandler.sendByte((address >> 8) & 0xff); - packetHandler.sendByte((address >> 16) & 0xff); - packetHandler.getAcknowledgement(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public int getStatus() { - int val = -1; - try { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_GETSTATUS); - val = packetHandler.getByte(); - packetHandler.getAcknowledgement(); - return val; - } catch (IOException e) { - e.printStackTrace(); - } - return val; - } - - public void rxMode() throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_RXMODE); - packetHandler.getAcknowledgement(); - } - - public void txMode() throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_TXMODE); - packetHandler.getAcknowledgement(); - } - - public void powerDown() throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_POWER_DOWN); - packetHandler.getAcknowledgement(); - } - - public char rxChar() throws IOException { - int val = -1; - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_RXCHAR); - val = packetHandler.getByte(); - packetHandler.getAcknowledgement(); - return ((char) (val & 0xff)); - } - - public int txChar(char character) throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_TXCHAR); - packetHandler.sendByte(character); - return packetHandler.getAcknowledgement() >> 4; - } - - public int hasData() throws IOException { - int val = -1; - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_HASDATA); - val = packetHandler.getByte(); - packetHandler.getAcknowledgement(); - return val; - } - - public void flush() throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_FLUSH); - packetHandler.getAcknowledgement(); - } - - public void writeRegister(int address, int value) throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_WRITEREG); - packetHandler.sendByte(address); - packetHandler.sendByte(value); - packetHandler.getAcknowledgement(); - } - - public byte readRegister(int address) throws IOException { - byte val = -1; - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_READREG); - packetHandler.sendByte(address); - val = packetHandler.getByte(); - packetHandler.getAcknowledgement(); - return val; - } - - public void writeCommand(int command) throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_WRITECOMMAND); - packetHandler.sendByte(command); - packetHandler.getAcknowledgement(); - } - - public ArrayList readPayload(int numBytes) throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_READPAYLOAD); - packetHandler.sendByte(numBytes); - byte[] data = new byte[numBytes]; - packetHandler.read(data, numBytes); - packetHandler.getAcknowledgement(); - ArrayList charData = new ArrayList<>(); - for (int i = 0; i < numBytes; i++) { - charData.add((char) data[i]); - } - return charData; - } - - public int writePayload(int[] data, boolean rxMode) throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_WRITEPAYLOAD); - int numBytes = data.length | 0x80; - if (rxMode) numBytes |= 0x40; - packetHandler.sendByte(numBytes); - packetHandler.sendByte(TX_PAYLOAD); - for (int _data : data) { - packetHandler.sendByte(_data); - } - int val = packetHandler.getAcknowledgement() >> 4; - if ((val & 0x2) != 0) - Log.e(TAG, "NRF radio not found. Connect one to the add-on port"); - else if ((val & 0x1) != 0) - Log.e(TAG, "Node probably dead/out of range. It failed to acknowledge"); - return val; - } - - public void startTokenManager() throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_START_TOKEN_MANAGER); - packetHandler.getAcknowledgement(); - } - - public void stopTokenManager() throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_STOP_TOKEN_MANAGER); - packetHandler.getAcknowledgement(); - } - - public int totalTokens() throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_TOTAL_TOKENS); - int val = packetHandler.getByte(); - packetHandler.getAcknowledgement(); - return val; - } - - public ArrayList fetchReport(int num) throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_REPORTS); - packetHandler.sendByte(num); - ArrayList data = new ArrayList<>(); - for (int i = 0; i < 20; i++) { - data.add(packetHandler.getByte()); - } - packetHandler.getAcknowledgement(); - return data; - } - - public ArrayList decodeI2CList(int[] data) { - int sum = 0; - ArrayList addressList = new ArrayList<>(); - for (int _data : data) { - sum += _data; - } - if (sum == 0) return addressList; - for (int i = 0; i < data.length; i++) { - if ((data[i] ^ 255) != 0) { - for (int j = 0; j < 8; j++) { - if ((data[i] & (0x80 >> j)) == 0) { - addressList.add(8 * i + j); - } - } - } - } - return addressList; - } - - public Map> getNodeList() throws IOException { - int total = totalTokens(); - if (this.nodePos != total) { - for (int i = 0; i < this.NODELIST_MAXLENGTH; i++) { - ArrayList data = fetchReport(i); - int txrx = (data.get(0)) | (data.get(1) << 8) | (data.get(2) << 16); - if (txrx == 0) continue; - int[] tempData = new int[17]; - for (int j = 3; j < 20; j++) - tempData[j - 3] = data.get(j); - nodeList.put(txrx, decodeI2CList(tempData)); - this.nodePos = total; - } - } - Map> filteredList = new LinkedHashMap<>(); - for (Map.Entry> entry : nodeList.entrySet()) { - if (isAlive(entry.getKey()) != null) { - filteredList.put(entry.getKey(), entry.getValue()); - } - } - return filteredList; - } - - public ArrayList isAlive(int address) throws IOException { - selectAddress(address); - return transaction(new int[]{NRF_COMMANDS | NRF_READ_REGISTER, R_STATUS}, 0, 100); - } - - public ArrayList transaction(int[] data, int listen, int timeout) throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_TRANSACTION); - packetHandler.sendByte(data.length); - packetHandler.sendInt(timeout); - for (int _data : data) { - packetHandler.sendByte(_data); - } - ArrayList characterData = new ArrayList<>(); - int numBytes = packetHandler.getByte(); - byte[] readData; - if (numBytes != -1) { - readData = new byte[numBytes]; - packetHandler.read(readData, numBytes); - } else { - readData = null; - } - int val = packetHandler.getAcknowledgement() >> 4; - if ((val & 0x1) != 0) Log.e(TAG, "Node not found " + CURRENT_ADDRESS); - if ((val & 0x2) != 0) Log.e(TAG, "NRF on-board transmitter not found " + CURRENT_ADDRESS); - if ((val & 0x4) != 0 & (listen == 1)) - Log.e(TAG, "Node received command but did not reply " + CURRENT_ADDRESS); - - if ((val & 0x7) != 0) { - flush(); - sigs.put(CURRENT_ADDRESS, sigs.get(CURRENT_ADDRESS) * 50 / 51); - return null; - } - sigs.put(CURRENT_ADDRESS, (sigs.get(CURRENT_ADDRESS) * 50 + 1) / 51); - if (readData == null) return characterData; - for (int i = 0; i < numBytes; i++) { - characterData.add((char) readData[i]); - } - return characterData; - } - - public ArrayList transactionWithRetries(int[] data, int retries) throws IOException { - if (retries == -1) retries = 5; - ArrayList reply = null; - while (retries > 0) { - reply = transaction(data, 0, 200); - if (reply != null) { - break; - } - retries--; - } - return reply; - } - - public void deleteRegisteredNode(int num) throws IOException { - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_DELETE_REPORT_ROW); - packetHandler.sendByte(num); - packetHandler.getAcknowledgement(); - } - - public void deleteAllRegisteredNodes() throws IOException { - while (totalTokens() != 0) { - deleteRegisteredNode(0); - } - } - - public void initShockBurstTransmitter(int payloadSize, int myAddress, int sendAddress) throws IOException { - if (payloadSize != -1) PAYLOAD_SIZE = payloadSize; - if (myAddress != -1) myAddress = 0xAAAA01; - if (sendAddress != -1) sendAddress = 0xAAAA01; - - init(); - writeAddress(RX_ADDR_P0, myAddress); - writeAddress(TX_ADDR, sendAddress); - writeRegister(RX_PW_P0, PAYLOAD_SIZE); - rxMode(); - // Add code for sleep 0.1 sec - flush(); - } - - public void initShockBurstReceiver(int payloadSize, int[] myAddress) throws IOException { - if (payloadSize != -1) { - PAYLOAD_SIZE = payloadSize; - } - if (myAddress[0] != -1) { - myAddress[0] = 0xA523B5; - } - init(); - writeRegister(RF_SETUP, 0x26); - int enabledPipes = 0; - for (int i = 0; i < 6; i++) { - if (myAddress[i] != -1) { - enabledPipes |= (1 << i); - writeAddress(RX_ADDR_P0 + i, myAddress[i]); - } - } - if (myAddress[1] != -1) - writeAddress(RX_ADDR_P1, myAddress[1]); - - writeRegister(EN_RXADDR, enabledPipes); - writeRegister(EN_AA, enabledPipes); - writeRegister(DYNPD, enabledPipes); - writeRegister(FEATURE, 0x06); - - rxMode(); - // Add code for sleep 0.1 sec - flush(); - } - - public void triggerAll(int val) throws IOException { - txMode(); - selectAddress(0x111111); - writeRegister(EN_AA, 0x00); - writePayload(new int[]{val}, true); - writeRegister(EN_AA, 0x01); - } - - public int writeAckPayload(int[] data, int pipe) throws IOException { - if (data.length != ACK_PAYLOAD_SIZE) { - ACK_PAYLOAD_SIZE = data.length; - if (ACK_PAYLOAD_SIZE > 15) { - Log.v(TAG, "too large. Truncating"); - ACK_PAYLOAD_SIZE = 15; - data = Arrays.copyOf(data, 15); - } else { - Log.v(TAG, "Ack payload size " + ACK_PAYLOAD_SIZE); - } - } - packetHandler.sendByte(commandsProto.NRFL01); - packetHandler.sendByte(commandsProto.NRF_WRITEPAYLOAD); - packetHandler.sendByte(data.length); - packetHandler.sendByte(ACK_PAYLOAD | pipe); - for (int _data : data) { - packetHandler.sendByte(_data); - } - return packetHandler.getAcknowledgement() >> 4; - } - - public ArrayList i2CScan() throws IOException { - ArrayList addresses = new ArrayList<>(); - ArrayList temp = transaction(new int[]{I2C_COMMANDS | I2C_SCAN | 0x80}, 0, 500); - if (temp == null) return addresses; - int sum = 0; - for (int i = 0; i < temp.size(); i++) { - sum += (int) temp.get(i); - } - if (sum == 0) return addresses; - - for (int i = 0; i < 16; i++) { - if ((temp.get(i) ^ 255) != 0) { - for (int j = 0; j < 8; j++) { - if ((temp.get(i) & (0x80 >> j)) == 0) { - addresses.add(8 * i + j); - } - } - } - } - return addresses; - } - - public ArrayList guessingScan() throws IOException { - ArrayList addresses = new ArrayList<>(); - ArrayList temp = transaction(new int[]{I2C_COMMANDS | I2C_SCAN | 0x80}, 0, 500); - if (temp == null) return addresses; - int sum = 0; - for (int i = 0; i < temp.size(); i++) { - sum += (int) temp.get(i); - } - if (sum == 0) return addresses; - Log.v(TAG, "Address \t Possible Devices"); - SensorList sensorList = new SensorList(); - for (int i = 0; i < 16; i++) { - if ((temp.get(i) ^ 255) != 0) { - for (int j = 0; j < 8; j++) { - if ((temp.get(i) & (0x80 >> j)) == 0) { - int address = 8 * i + j; - addresses.add(address); - Log.v(TAG, Integer.toHexString(address) + "\t" + Arrays.toString(sensorList.sensorList.get(address))); - } - } - } - } - - return addresses; - } - -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/communication/peripherals/RadioLink.java b/app/src/main/java/io/pslab/communication/peripherals/RadioLink.java deleted file mode 100644 index 9a0d5be7d..000000000 --- a/app/src/main/java/io/pslab/communication/peripherals/RadioLink.java +++ /dev/null @@ -1,184 +0,0 @@ -package io.pslab.communication.peripherals; - -import android.util.Log; - -import io.pslab.communication.SensorList; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; - -/** - * Created by viveksb007 on 28/3/17. - */ - -public class RadioLink { - - private static final String TAG = "RadioLink"; - private int ADC_COMMANDS = 1; - private int READ_ADC = 0 << 4; - - private int I2C_COMMANDS = 2; - private int I2C_TRANSACTION = 0 << 4; - private int I2C_WRITE = 1 << 4; - private int I2C_SCAN = 2 << 4; - private int PULL_SCL_LOW = 3 << 4; - private int I2C_CONFIG = 4 << 4; - private int I2C_READ = 5 << 4; - - private int NRF_COMMANDS = 3; - private int NRF_READ_REGISTER = 0 << 4; - private int NRF_WRITE_REGISTER = 1 << 4; - - private int MISC_COMMANDS = 4; - private int WS2812B_CMD = 0 << 4; - - private NRF24L01 nrf24L01; - private int ADDRESS = 0x010101; - private int timeout = 200; - - public RadioLink(NRF24L01 nrf24L01, int address) { - this.nrf24L01 = nrf24L01; - if (address != -1) ADDRESS = address; - - } - - private void selectMe() { - if (this.nrf24L01.CURRENT_ADDRESS != this.ADDRESS) { - this.nrf24L01.selectAddress(this.ADDRESS); - } - } - - public ArrayList writeI2C(int I2CAddress, int regAddress, int[] data) throws IOException { - selectMe(); - int[] newData = new int[3 + data.length]; - newData[0] = I2C_COMMANDS | I2C_WRITE; - newData[1] = I2CAddress; - newData[2] = regAddress; - System.arraycopy(data, 0, newData, 3, data.length); - return this.nrf24L01.transaction(newData, 0, timeout); - } - - public ArrayList readI2C(int I2CAddress, int regAddress, int numBytes) throws IOException { - selectMe(); - return this.nrf24L01.transaction(new int[]{I2C_COMMANDS | I2C_TRANSACTION, I2CAddress, regAddress, numBytes}, 0, timeout); - } - - public ArrayList writeBulk(int I2CAddress, int[] data) throws IOException { - selectMe(); - int[] newData = new int[2 + data.length]; - newData[0] = I2C_COMMANDS | I2C_WRITE; - newData[1] = I2CAddress; - System.arraycopy(data, 0, newData, 2, data.length); - return this.nrf24L01.transaction(newData, 0, timeout); - } - - public ArrayList readBulk(int I2CAddress, int regAddress, int numBytes) throws IOException { - selectMe(); - return this.nrf24L01.transactionWithRetries(new int[]{I2C_COMMANDS | I2C_TRANSACTION, I2CAddress, regAddress, numBytes}, -1); - } - - public ArrayList simpleRead(int I2CAddress, int numBytes) throws IOException { - selectMe(); - return this.nrf24L01.transactionWithRetries(new int[]{I2C_COMMANDS | I2C_READ, I2CAddress, numBytes}, -1); - } - - public ArrayList readADC(int channel) throws IOException { - selectMe(); - return this.nrf24L01.transaction(new int[]{ADC_COMMANDS | READ_ADC, channel}, 0, timeout); - } - - public ArrayList i2CScan() throws IOException { - selectMe(); - Log.v(TAG, "Scanning addresses 0-127..."); - ArrayList addresses = new ArrayList<>(); - ArrayList temp = this.nrf24L01.transaction(new int[]{I2C_COMMANDS | I2C_SCAN | 0x80}, 0, 500); - if (temp == null) return addresses; - int sum = 0; - for (int i = 0; i < temp.size(); i++) { - sum += (int) temp.get(i); - } - if (sum == 0) return addresses; - Log.v(TAG, "Address \t Possible Devices"); - SensorList sensorList = new SensorList(); - for (int i = 0; i < 16; i++) { - if ((temp.get(i) ^ 255) != 0) { - for (int j = 0; j < 8; j++) { - if ((temp.get(i) & (0x80 >> j)) == 0) { - int address = 8 * i + j; - addresses.add(address); - Log.v(TAG, Integer.toHexString(address) + "\t" + Arrays.toString(sensorList.sensorList.get(address))); - } - } - } - } - return addresses; - } - - private ArrayList decodeI2CList(int[] data) { - int sum = 0; - ArrayList addressList = new ArrayList<>(); - for (int _data : data) { - sum += _data; - } - if (sum == 0) return addressList; - for (int i = 0; i < data.length; i++) { - if ((data[i] ^ 255) != 0) { - for (int j = 0; j < 8; j++) { - if ((data[i] & (0x80 >> j)) == 0) { - addressList.add(8 * i + j); - } - } - } - } - return addressList; - } - - public ArrayList pullSCLLow(int t_ms) throws IOException { - selectMe(); - ArrayList data; - data = this.nrf24L01.transaction(new int[]{I2C_COMMANDS | PULL_SCL_LOW, t_ms}, 0, timeout); - if (data != null) { - int[] tempData = new int[data.size()]; - for (int i = 0; i < data.size(); i++) { - tempData[i] = data.get(i); - } - return decodeI2CList(tempData); - } else { - return new ArrayList<>(); - } - } - - public ArrayList configI2C(int frequency) throws IOException { - selectMe(); - int brgVal = (int) 32e6 / frequency / 4 - 1; - return this.nrf24L01.transaction(new int[]{I2C_COMMANDS | I2C_CONFIG, brgVal}, 0, timeout); - } - - public ArrayList writeRegister(int register, int value) throws IOException { - selectMe(); - return this.nrf24L01.transaction(new int[]{NRF_COMMANDS | NRF_WRITE_REGISTER, register, value}, 0, timeout); - } - - public int readRegister(int register) throws IOException { - selectMe(); - ArrayList data = this.nrf24L01.transaction(new int[]{NRF_COMMANDS | NRF_READ_REGISTER, register}, 0, timeout); - if (data != null) { - return (int) data.get(0); - } else - return -1; - } - - public ArrayList WS2812B(int[][] cols) throws IOException { - selectMe(); - int[] colorArray = new int[1 + cols.length * 3]; - colorArray[0] = MISC_COMMANDS | WS2812B_CMD; - for (int i = 1, j = 1; i < cols.length; i++, j += 3) { - colorArray[j] = cols[i][1]; - colorArray[j + 1] = cols[i][0]; - colorArray[j + 2] = cols[i][2]; - } - return this.nrf24L01.transaction(colorArray, 0, timeout); - } - -} diff --git a/app/src/main/java/io/pslab/communication/peripherals/SPI.java b/app/src/main/java/io/pslab/communication/peripherals/SPI.java deleted file mode 100644 index e4836188d..000000000 --- a/app/src/main/java/io/pslab/communication/peripherals/SPI.java +++ /dev/null @@ -1,107 +0,0 @@ -package io.pslab.communication.peripherals; - -import android.util.Log; - -import io.pslab.communication.CommandsProto; -import io.pslab.communication.PacketHandler; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; - -/** - * Created by viveksb007 on 28/3/17. - */ - -public class SPI { - - private static final String TAG = "SPI"; - private PacketHandler packetHandler; - private CommandsProto commandsProto; - private int CKE = 1, CKP = 0, SMP = 1; - - public SPI(PacketHandler packetHandler) { - this.packetHandler = packetHandler; - this.commandsProto = new CommandsProto(); - } - - public void setParameters(int primaryPreScalar, int secondaryPreScalar, Integer CKE, Integer CKP, Integer SMP) throws IOException { - if (CKE != null) this.CKE = CKE; - if (CKP != null) this.CKP = CKP; - if (SMP != null) this.SMP = SMP; - - packetHandler.sendByte(commandsProto.SPI_HEADER); - packetHandler.sendByte(commandsProto.SET_SPI_PARAMETERS); - packetHandler.sendByte(secondaryPreScalar | (primaryPreScalar << 3) | (this.CKE << 5) | (this.CKP << 6) | (this.SMP << 7)); - packetHandler.getAcknowledgement(); - } - - public void start(int channel) throws IOException { - packetHandler.sendByte(commandsProto.SPI_HEADER); - packetHandler.sendByte(commandsProto.START_SPI); - packetHandler.sendByte(channel); - } - - public void setCS(String channel, int state) throws IOException { - String[] chipSelect = new String[]{"CS1", "CS2"}; - channel = channel.toUpperCase(); - if (Arrays.asList(chipSelect).contains(channel)) { - int csNum = Arrays.asList(chipSelect).indexOf(channel) + 9; - packetHandler.sendByte(commandsProto.SPI_HEADER); - if (state == 1) - packetHandler.sendByte(commandsProto.STOP_SPI); - else - packetHandler.sendByte(commandsProto.START_SPI); - packetHandler.sendByte(csNum); - } else { - Log.d(TAG, "Channel does not exist"); - } - } - - public void stop(int channel) throws IOException { - packetHandler.sendByte(commandsProto.SPI_HEADER); - packetHandler.sendByte(commandsProto.STOP_SPI); - packetHandler.sendByte(channel); - } - - public byte send8(int value) throws IOException { - packetHandler.sendByte(commandsProto.SPI_HEADER); - packetHandler.sendByte(commandsProto.SEND_SPI8); - packetHandler.sendByte(value); - byte retValue = packetHandler.getByte(); - packetHandler.getAcknowledgement(); - return retValue; - } - - public int send16(int value) throws IOException { - packetHandler.sendByte(commandsProto.SPI_HEADER); - packetHandler.sendByte(commandsProto.SEND_SPI16); - packetHandler.sendInt(value); - int retValue = packetHandler.getInt(); - packetHandler.getAcknowledgement(); - return retValue; - } - - public void send8Burst(int value) throws IOException { - packetHandler.sendByte(commandsProto.SPI_HEADER); - packetHandler.sendByte(commandsProto.SEND_SPI8_BURST); - packetHandler.sendByte(value); - } - - public void send16Burst(int value) throws IOException { - packetHandler.sendByte(commandsProto.SPI_HEADER); - packetHandler.sendByte(commandsProto.SEND_SPI16_BURST); - packetHandler.sendInt(value); - } - - public ArrayList xfer(int channel, ArrayList data) throws IOException { - start(channel); - ArrayList reply = new ArrayList<>(); - for (Byte a : data) { - reply.add(send8(a)); - } - stop(channel); - return reply; - } - -} diff --git a/app/src/main/java/io/pslab/communication/sensors/AD7718.java b/app/src/main/java/io/pslab/communication/sensors/AD7718.java deleted file mode 100644 index 58964b49e..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/AD7718.java +++ /dev/null @@ -1,322 +0,0 @@ -package io.pslab.communication.sensors; - -import android.util.Log; - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; -import io.pslab.communication.peripherals.SPI; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; - -/** - * Created by Padmal on 5/3/17. - */ - -public class AD7718 { - - private double VREF = 3.3; - - private int STATUS = 0; - private int MODE = 1; - private int ADCCON = 2; - private int FILTER = 3; - private int ADCDATA = 4; - private int ADCOFFSET = 5; - private int ADCGAIN = 6; - private int IOCON = 7; - private int TEST1 = 12; - private int TEST2 = 13; - private int ID = 15; - - // Bit definitions - private int MODE_PD = 0; - private int MODE_IDLE = 1; - private int MODE_SINGLE = 2; - private int MODE_CONT = 3; - private int MODE_INT_ZEROCAL = 4; - private int MODE_INT_FULLCAL = 5; - private int MODE_SYST_ZEROCAL = 6; - private int MODE_SYST_FULLCAL = 7; - - private int MODE_OSCPD = bitShift(1, 3); - private int MODE_CHCON = bitShift(1, 4); - private int MODE_REFSEL = bitShift(1, 5); - private int MODE_NEGBUF = bitShift(1, 6); - private int MODE_NOCHOP = bitShift(1, 7); - - private int CON_AIN1AINCOM = bitShift(0, 4); - private int CON_AIN2AINCOM = bitShift(1, 4); - private int CON_AIN3AINCOM = bitShift(2, 4); - private int CON_AIN4AINCOM = bitShift(3, 4); - private int CON_AIN5AINCOM = bitShift(4, 4); - private int CON_AIN6AINCOM = bitShift(5, 4); - private int CON_AIN7AINCOM = bitShift(6, 4); - private int CON_AIN8AINCOM = bitShift(7, 4); - private int CON_AIN1AIN2 = bitShift(8, 4); - private int CON_AIN3AIN4 = bitShift(9, 4); - private int CON_AIN5AIN6 = bitShift(10, 4); - private int CON_AIN7AIN8 = bitShift(11, 4); - private int CON_AIN2AIN2 = bitShift(12, 4); - private int CON_AINCOMAINCOM = bitShift(13, 4); - private int CON_REFINREFIN = bitShift(14, 4); - private int CON_OPEN = bitShift(15, 4); - private int CON_UNIPOLAR = bitShift(1, 3); - - private int CON_RANGE0 = 0; // +-20mV - private int CON_RANGE1 = 1; // +-40mV - private int CON_RANGE2 = 2; // +-80mV - private int CON_RANGE3 = 3; // +-160mV - private int CON_RANGE4 = 4; // +-320mV - private int CON_RANGE5 = 5; // +-640mV - private int CON_RANGE6 = 6; // +-1280mV - private int CON_RANGE7 = 7; // +-2560mV - private int gain = 1; - - private String[] CHAN_NAMES = { - "AIN1AINCOM", - "AIN2AINCOM", - "AIN3AINCOM", - "AIN4AINCOM", - "AIN5AINCOM", - "AIN6AINCOM", - "AIN7AINCOM", - "AIN8AINCOM" - }; - - private SPI spi; - private boolean caldone; - private String cs; - - private final String TAG = "AD7718"; - - private HashMap calibs = new HashMap<>(); - private HashMap caldata = new HashMap<>(); - - - public AD7718(SPI spi) throws IOException { - this.spi = spi; - this.cs = "CS1"; - // Populate Calibrations - populateCalibrationMap(); - // Set SPI Parameters - spi.setParameters(2, 1, 0, 1, 1); - writeRegister(FILTER, 20); - writeRegister(MODE, MODE_SINGLE | MODE_CHCON | MODE_REFSEL); - - for (String key : calibs.keySet()) { - double[] convertedList = new PolynomialFunction(calibs.get(key)).getCoefficients(); - ArrayUtils.reverse(convertedList); - caldata.put(key, convertedList); - } - } - - public void setCalibrationMap(HashMap calibrationMap) { - this.calibs = calibrationMap; - } - - /** - * Initiates calibration HashMap with default values - */ - private void populateCalibrationMap() { - calibs.put("AIN1AINCOM", new double[]{ - 8.220199e-05, -4.587100e-04, 1.001015e+00, -1.684517e-04}); - calibs.put("AIN2AINCOM", new double[]{ - 5.459186e-06, -1.749624e-05, 1.000268e+00, 1.907896e-04}); - calibs.put("AIN3AINCOM", new double[]{ - -3.455831e-06, 2.861689e-05, 1.000195e+00, 3.802349e-04}); - calibs.put("AIN4AINCOM", new double[]{ - 4.135213e-06, -1.973478e-05, 1.000277e+00, 2.115374e-04}); - calibs.put("AIN5AINCOM", new double[]{ - -1.250787e-07, -9.203838e-07, 1.000299e+00, -1.262684e-03}); - calibs.put("AIN6AINCOM", new double[]{ - 6.993123e-07, -1.563294e-06, 9.994211e-01, -4.596018e-03}); - calibs.put("AIN7AINCOM", new double[]{ - 3.911521e-07, -1.706405e-06, 1.002294e+00, -1.286302e-02}); - calibs.put("AIN8AINCOM", new double[]{ - 8.290843e-07, -7.129532e-07, 9.993159e-01, 3.307947e-03}); - calibs.put("AIN9AINCOM", new double[]{ - 7.652808e+00, 1.479229e+00, 2.832601e-01, 4.495232e-02}); - } - - public void start() throws IOException { - spi.setCS(cs, 0); - } - - public void stop() throws IOException { - spi.setCS(cs, 1); - } - - public int send8(int val) throws IOException { - return spi.send8(val); - } - - private int send16(int val) throws IOException { - return spi.send16(val); - } - - private int readRegister(int reg) throws IOException { - start(); - int val = send16(0x4000 | (reg << 8)); - stop(); - val &= 0x00FF; - return val; - } - - private int readData() throws IOException { - start(); - int val = send16(0x4000 | (ADCDATA << 8)); - val &= 0xFF; - val <<= 16; - val |= send16(0x0000); - stop(); - return val; - } - - private int writeRegister(int reg, int value) throws IOException { - start(); - int val = send16((reg << 8) | value); - stop(); - return val; - } - - public void internalCalibration(int chan) throws IOException, InterruptedException { - start(); - int val = send16((ADCCON << 8) | (chan << 4) | 7); // range=7 - long start_time = System.currentTimeMillis(); - caldone = false; - val = send16((MODE << 8) | 4); - while (!caldone) { - Thread.sleep(500); - caldone = (send16(0x4000 | (MODE << 8)) & 7) == 1; - Log.d(TAG, String.format("Waiting for zero scale calibration... %.2f S, %s", - (float) (System.currentTimeMillis() - start_time), - caldone) - ); - } - caldone = false; - val = send16((MODE << 8) | 5); - while (!caldone) { - Thread.sleep(500); - caldone = (send16(0x4000 | (MODE << 8)) & 7) == 1; - Log.d(TAG, String.format("Waiting for full scale calibration... %.2f S, %s", - (float) (System.currentTimeMillis() - start_time), - caldone) - ); - } - stop(); - } - - public List readCalibration() throws IOException { - start(); - int off = send16(0x4000 | (ADCOFFSET << 8)); - off &= 0xFF; - off <<= 16; - off |= send16(0x0000); - - int gn = send16(0x4000 | (ADCGAIN << 8)); - gn &= 0xFF; - gn <<= 16; - gn |= send16(0x0000); - stop(); - return Arrays.asList(new int[]{off, gn}); - } - - - private void configADC(int adccon) throws IOException { - writeRegister(ADCCON, adccon); // unipolar channels, range - gain = 2 ^ (7 - adccon & 3); - } - - public void printstat() throws IOException { - int stat = readRegister(STATUS); - String[] P = {"PLL LOCKED", "RES", "RES", "ADC ERROR", "RES", "CAL DONE", "RES", "READY"}; - String[] N = {"PLL ERROR", "RES", "RES", "ADC OKAY", "RES", "CAL LOW", "RES", "NOT READY"}; - StringBuilder sb = new StringBuilder(); - for (int a = 0; a < 8; a++) { - if ((stat & (1 << a)) == 1) { - sb.append(P[a]); - } else { - sb.append(N[a]); - } - } - Log.d(TAG, stat + ", " + sb.toString()); - } - - private float convertUniPolar(float x) { - return (float) (1.024 * VREF * x) / (gain * 2 ^ 24); - } - - public float convertBipolar(float x) { - return (float) (((x / (2 ^ 24)) - 1) * (1.024 * VREF) / (gain)); - } - - private boolean startRead(String chan) throws IOException { - List channels = Arrays.asList(CHAN_NAMES); - if (channels.contains(chan)) { - int channelID = channels.indexOf(chan); - configADC(CON_RANGE7 | CON_UNIPOLAR | channelID << 4); - writeRegister(MODE, MODE_SINGLE | MODE_CHCON | MODE_REFSEL); - return true; - } else { - Log.d(TAG, "Invalid Channel Name. try AIN1AINCOM"); - return false; - } - } - - private boolean fetchData(String chan) throws IOException, InterruptedException { - - while (true) { - int stat = readRegister(STATUS); - if ((stat & 0x80) == 1) { - float data = readData(); - data = convertUniPolar(data); - List channelList = Collections.singletonList(chan); - if ((int) channelList.get(3) > 4) { - data = (data - 3.3f / 2) * 4; - } - PolynomialFunction function = new PolynomialFunction(caldata.get(chan)); - return function.value(data) == 0; - } else { - Thread.sleep(100); - Log.d(TAG, "Increase Delay"); - } - } - } - - public boolean readVoltage(String channel) throws IOException, InterruptedException { - if (startRead(channel)) { - return false; - } - Thread.sleep(150); - return fetchData(channel); - } - - private boolean fetchRawData(String chan) throws IOException, InterruptedException { - while (true) { - int stat = readRegister(STATUS); - if ((stat & 0x80) == 1) { - float data = readData(); - return convertUniPolar(data) == 1; - } else { - Thread.sleep(100); - Log.d(TAG, "Increase Delay"); - } - } - } - - public boolean readRawVoltage(String channel) throws IOException, InterruptedException { - if (startRead(channel)) { - return false; - } - Thread.sleep(150); - return fetchRawData(channel); - } - - private int bitShift(int y, int x) { - return y << x; - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/communication/sensors/AD9833.java b/app/src/main/java/io/pslab/communication/sensors/AD9833.java deleted file mode 100644 index e1c868774..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/AD9833.java +++ /dev/null @@ -1,108 +0,0 @@ -package io.pslab.communication.sensors; - - -import android.util.Log; - -import io.pslab.communication.peripherals.SPI; - -import java.io.IOException; - - -/** - * Created by akarshan on 4/23/17. - *

- * ScienceLab instance of SPI and DDS_CLOCK are required to be passed to the AD9833 constructor. - * mapReferenceClock(new ArrayList<>(Collections.singletonList("WAVEGEN")), 4) is needed to be called prior to creation of AD9833 object. - *

- */ - -public class AD9833 { - //control bytes - private static final String TAG = "AD9833"; - private int DDS_MAX_FREQ = 0xFFFFFFF - 1; - private int DDS_B28 = 13; - private int DDS_HLB = 12; - private int DDS_FSELECT = 11; - private int DDS_PSELECT = 10; - private int DDS_RESET = 8; - private int DDS_SLEEP1 = 7; - private int DDS_SLEEP12 = 6; - private int DDS_OPBITEN = 5; - private int DDS_DIV2 = 3; - private int DDS_MODE = 1; - - private int DDS_FSYNC = 9; - - private int[] DDS_SINE = {0}; - private int DDS_TRIANGLE = (1 << DDS_MODE); - private int DDS_SQUARE = (1 << DDS_OPBITEN); - private int DDS_RESERVED = (1 << DDS_OPBITEN) | (1 << DDS_MODE); - private int DDS_CLOCK; - private int clockScaler = 4; // 8MHz - private int waveformMode; - private int activeChannel; - private int frequency; - private int cs; - private SPI spi; - - public AD9833(SPI spi, int DDS_CLOCK) throws IOException { - cs = 9; - this.spi = spi; - this.spi.setParameters(2, 2, 1, 1, 0); - this.DDS_CLOCK = DDS_CLOCK; - waveformMode = DDS_TRIANGLE; - - Log.v(TAG, "clock set to: " + DDS_CLOCK); - write(1 << DDS_RESET); - write((1 << DDS_B28) | waveformMode); //finished loading data - activeChannel = 0; - frequency = 1000; - } - - private void write(int con) throws IOException { - spi.start(cs); - spi.send16(con); - spi.stop(cs); - } - - private void setFrequency(int frequency, int register, int phase) throws IOException { - int regSel; - activeChannel = register; - this.frequency = frequency; - - int frequencySetting = (Math.round(frequency * DDS_MAX_FREQ / DDS_CLOCK)); - int modeBits = (1 << DDS_B28) | waveformMode; - if (register > 0) { - modeBits |= (1 << DDS_FSELECT); - regSel = 0x8000; - } else - regSel = 0x4000; - - write((1 << DDS_RESET) | modeBits); //Ready to load DATA - write((regSel | (frequencySetting & 0x3FFF)) & 0xFFFF); //LSB - write((regSel | ((frequencySetting >> 14) & 0x3FFF)) & 0xFFFF); //MSB - write(0xc000 | phase); //Phase - write(modeBits); //finished loading data - } - - public void setVoltage(int voltage) throws IOException { - waveformMode = DDS_TRIANGLE; - setFrequency(0, 0, voltage); //0xfff*v/.6 - } - - public void selectFrequencyRegister(int register) throws IOException { - activeChannel = register; - int modeBits = waveformMode; - if (register != 0) - modeBits |= (1 << DDS_FSELECT); - write(modeBits); - } - - public void setWaveformMode(int mode) throws IOException { - waveformMode = mode; - int modeBits = mode; - if (activeChannel != 0) - modeBits |= (1 << DDS_FSELECT); - write(modeBits); - } -} diff --git a/app/src/main/java/io/pslab/communication/sensors/ADS1115.java b/app/src/main/java/io/pslab/communication/sensors/ADS1115.java deleted file mode 100644 index e89dc1cb0..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/ADS1115.java +++ /dev/null @@ -1,236 +0,0 @@ -package io.pslab.communication.sensors; - -import io.pslab.communication.peripherals.I2C; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; - -public class ADS1115 { - private int ADDRESS = 0x48; - private I2C i2c; - - private int REG_POINTER_MASK = 0x3; - private int REG_POINTER_CONVERT = 0; - private int REG_POINTER_CONFIG = 1; - private int REG_POINTER_LOWTHRESH = 2; - private int REG_POINTER_HITHRESH = 3; - - private int REG_CONFIG_OS_MASK = 0x8000; - private int REG_CONFIG_OS_SINGLE = 0x8000; - private int REG_CONFIG_OS_BUSY = 0x0000; - private int REG_CONFIG_OS_NOTBUSY = 0x8000; - - private int REG_CONFIG_MUX_MASK = 0x7000; - private int REG_CONFIG_MUX_DIFF_0_1 = 0x0000; - private int REG_CONFIG_MUX_DIFF_0_3 = 0x1000; - private int REG_CONFIG_MUX_DIFF_1_3 = 0x2000; - private int REG_CONFIG_MUX_DIFF_2_3 = 0x3000; - private int REG_CONFIG_MUX_SINGLE_0 = 0x4000; - private int REG_CONFIG_MUX_SINGLE_1 = 0x5000; - private int REG_CONFIG_MUX_SINGLE_2 = 0x6000; - private int REG_CONFIG_MUX_SINGLE_3 = 0x7000; - - private int REG_CONFIG_PGA_MASK = 0x0E00; - private int REG_CONFIG_PGA_6_144V = 0 << 9; - private int REG_CONFIG_PGA_4_096V = 1 << 9; - private int REG_CONFIG_PGA_2_048V = 2 << 9; - private int REG_CONFIG_PGA_1_024V = 3 << 9; - private int REG_CONFIG_PGA_0_512V = 4 << 9; - private int REG_CONFIG_PGA_0_256V = 5 << 9; - - private int REG_CONFIG_MODE_MASK = 0x0100; - private int REG_CONFIG_MODE_CONTIN = 0 << 8; - private int REG_CONFIG_MODE_SINGLE = 1 << 8; - - private int REG_CONFIG_DR_MASK = 0x00E0; - private int REG_CONFIG_DR_8SPS = 0 << 5; - private int REG_CONFIG_DR_16SPS = 1 << 5; - private int REG_CONFIG_DR_32SPS = 2 << 5; - private int REG_CONFIG_DR_64SPS = 3 << 5; - private int REG_CONFIG_DR_128SPS = 4 << 5; - private int REG_CONFIG_DR_250SPS = 5 << 5; - private int REG_CONFIG_DR_475SPS = 6 << 5; - private int REG_CONFIG_DR_860SPS = 7 << 5; - - private int REG_CONFIG_CMODE_MASK = 0x0010; - private int REG_CONFIG_CMODE_TRAD = 0x0000; - private int REG_CONFIG_CMODE_WINDOW = 0x0010; - - private int REG_CONFIG_CPOL_MASK = 0x0008; - private int REG_CONFIG_CPOL_ACTVLOW = 0x0000; - private int REG_CONFIG_CPOL_ACTVHI = 0x0008; - - private int REG_CONFIG_CLAT_MASK = 0x0004; - private int REG_CONFIG_CLAT_NONLAT = 0x0000; - private int REG_CONFIG_CLAT_LATCH = 0x0004; - - private int REG_CONFIG_CQUE_MASK = 0x0003; - private int REG_CONFIG_CQUE_1CONV = 0x0000; - private int REG_CONFIG_CQUE_2CONV = 0x0001; - private int REG_CONFIG_CQUE_4CONV = 0x0002; - private int REG_CONFIG_CQUE_NONE = 0x0003; - - private HashMap gains = new HashMap(); - private HashMap gainScaling = new HashMap(); - private HashMap typeSelection = new HashMap(); - private HashMap sdrSelection = new HashMap(); - - private String channel; - private String gain; - private int rate; - - public int NUMPLOTS = 1; - public String[] PLOTNAMES = {"mV"}; - - public ADS1115(I2C i2c) throws IOException, InterruptedException { - this.i2c = i2c; - channel = "UNI_0"; - gain = "GAIN_ONE"; - rate = 128; - - setGain("GAIN_ONE"); - setChannel("UNI_0"); - setDataRate(128); - - int conversionDelay = 8; - String name = "ADS1115 16-bit ADC"; - - gains.put("GAIN_TWOTHIRDS", REG_CONFIG_PGA_6_144V); - gains.put("GAIN_ONE", REG_CONFIG_PGA_4_096V); - gains.put("GAIN_TWO", REG_CONFIG_PGA_2_048V); - gains.put("GAIN_FOUR", REG_CONFIG_PGA_1_024V); - gains.put("GAIN_EIGHT", REG_CONFIG_PGA_0_512V); - gains.put("GAIN_SIXTEEN", REG_CONFIG_PGA_0_256V); - - gainScaling.put("GAIN_TWOTHIRDS", 0.1875); - gainScaling.put("GAIN_ONE", 0.125); - gainScaling.put("GAIN_TWO", 0.0625); - gainScaling.put("GAIN_FOUR", 0.03125); - gainScaling.put("GAIN_EIGHT", 0.015625); - gainScaling.put("GAIN_SIXTEEN", 0.0078125); - - typeSelection.put("UNI_0", "0"); - typeSelection.put("UNI_1", "1"); - typeSelection.put("UNI_2", "2"); - typeSelection.put("UNI_3", "3"); - typeSelection.put("DIFF_01", "01"); - typeSelection.put("DIFF_23", "23"); - - sdrSelection.put(8, REG_CONFIG_DR_8SPS); - sdrSelection.put(16, REG_CONFIG_DR_16SPS); - sdrSelection.put(32, REG_CONFIG_DR_32SPS); - sdrSelection.put(64, REG_CONFIG_DR_64SPS); - sdrSelection.put(128, REG_CONFIG_DR_128SPS); - sdrSelection.put(250, REG_CONFIG_DR_250SPS); - sdrSelection.put(475, REG_CONFIG_DR_475SPS); - sdrSelection.put(860, REG_CONFIG_DR_860SPS); - - } - - public int readInt(int addr) throws IOException, InterruptedException { - ArrayList vals = i2c.readBulk(ADDRESS, addr, 2); - int v = (int) (1. * ((vals.get(0) << 8) | vals.get(1))); - return v; - } - - public void initTemperature() throws IOException, InterruptedException { - i2c.writeBulk(ADDRESS, new int[]{ADDRESS}); - TimeUnit.SECONDS.sleep((long) 0.005); - } - - private int readRegister(int register) throws IOException { - ArrayList vals = i2c.readBulk(ADDRESS, register, 2); - return (vals.get(0) << 8) | vals.get(1); - } - - private void writeRegister(int reg, int value) throws IOException { - i2c.writeBulk(ADDRESS, new int[]{ADDRESS, (value >> 8) & 0xFF, value & 0xFF}); - } - - public void setGain(String gain) { - /*options : 'GAIN_TWOTHIRDS','GAIN_ONE','GAIN_TWO','GAIN_FOUR','GAIN_EIGHT','GAIN_SIXTEEN'*/ - this.gain = gain; - } - - public void setChannel(String channel) { - /*options 'UNI_0','UNI_1','UNI_2','UNI_3','DIFF_01','DIFF_23'*/ - this.channel = channel; - } - - public void setDataRate(int rate) { - /*data rate options 8,16,32,64,128,250,475,860 SPS*/ - this.rate = rate; - } - - private double readADCSingleEnded(int chan) throws IOException, InterruptedException { - if (chan > 3) { - return -1; - } - //start with default values - int config = REG_CONFIG_CQUE_NONE //Disable the comparator (default val) - | REG_CONFIG_CLAT_NONLAT //Non-latching (default val) - | REG_CONFIG_CPOL_ACTVLOW //Alert/Rdy active low (default val) - | REG_CONFIG_CMODE_TRAD // Traditional comparator (default val) - | REG_CONFIG_MODE_SINGLE // Single-shot mode (default) - | sdrSelection.get(rate); //1600 samples per second (default) - - //Set PGA/voltage range - config = config | gains.get(gain); - - if (chan == 0) - config = config | REG_CONFIG_MUX_SINGLE_0; - else if (chan == 1) - config = config | REG_CONFIG_MUX_SINGLE_1; - else if (chan == 2) - config = config | REG_CONFIG_MUX_SINGLE_2; - else if (chan == 3) - config = config | REG_CONFIG_MUX_SINGLE_3; - - //Set 'start single-conversion' bit - config = config | REG_CONFIG_OS_SINGLE; - writeRegister(REG_POINTER_CONFIG, config); - TimeUnit.MILLISECONDS.sleep((long) ((1. / rate + 0.002) * 1000)); //convert to mS to S - return readRegister(REG_POINTER_CONVERT) * gainScaling.get(gain); - } - - private short readADCDifferential(String chan) throws IOException, InterruptedException { - //start with default values - int config = REG_CONFIG_CQUE_NONE //Disable the comparator (default val) - | REG_CONFIG_CLAT_NONLAT //Non-latching (default val) - | REG_CONFIG_CPOL_ACTVLOW //Alert/Rdy active low (default val) - | REG_CONFIG_CMODE_TRAD // Traditional comparator (default val) - | REG_CONFIG_MODE_SINGLE // Single-shot mode (default) - | sdrSelection.get(rate); //1600 samples per second (default) - - //Set PGA/voltage range - config = config | gains.get(gain); - - if (chan.equals("01")) - config = config | REG_CONFIG_MUX_DIFF_0_1; - else if (chan.equals("23")) - config = config | REG_CONFIG_MUX_DIFF_2_3; - - //Set 'start single-conversion' bit - config = config | REG_CONFIG_OS_SINGLE; - writeRegister(REG_POINTER_CONFIG, config); - TimeUnit.MILLISECONDS.sleep((long) ((1. / rate + 0.002) * 1000)); //convert to mS to S - - return (short) (readRegister(REG_POINTER_CONVERT) * gainScaling.get(gain)); - } - - public short getLastResults() throws IOException { - return (short) (readRegister(REG_POINTER_CONVERT) * gainScaling.get(gain)); - } - - public int getRaw() throws IOException, InterruptedException { - //return values in mV - String chan = typeSelection.get(channel); - if (channel.contains("UNI")) - return (int) readADCSingleEnded(Integer.parseInt(chan)); - else if (channel.contains("DIF")) - return readADCDifferential(chan); - return 0; - } -} diff --git a/app/src/main/java/io/pslab/communication/sensors/APDS9960.java b/app/src/main/java/io/pslab/communication/sensors/APDS9960.java deleted file mode 100644 index 867693d6b..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/APDS9960.java +++ /dev/null @@ -1,255 +0,0 @@ -package io.pslab.communication.sensors; - -import java.io.IOException; -import java.util.ArrayList; - -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; - -public class APDS9960 { - - // APDS9960 default address - private static final int APDS9960_I2C_ADDRESS = 0x39; - private final I2C i2c; - - private static final int APDS9960_ENABLE = 0x80; - private static final int APDS9960_ATIME = 0x81; - private static final int APDS9960_PILT = 0x89; - private static final int APDS9960_PERS = 0x8C; - private static final int APDS9960_CONTROL = 0x8F; - private static final int APDS9960_STATUS = 0x93; - private static final int APDS9960_CDATAL = 0x94; - private static final int APDS9960_PDATA = 0x9C; - private static final int APDS9960_GPENTH = 0xA0; - private static final int APDS9960_GEXTH = 0xA1; - private static final int APDS9960_GCONF1 = 0xA2; - private static final int APDS9960_GCONF2 = 0xA3; - private static final int APDS9960_GPULSE = 0xA6; - private static final int APDS9960_GCONF4 = 0xAB; - private static final int APDS9960_GFLVL = 0xAE; - private static final int APDS9960_GSTATUS = 0xAF; - private static final int APDS9960_AICLEAR = 0xE7; - private static final int APDS9960_GFIFO_U = 0xFC; - - private static final int BIT_MASK_ENABLE_EN = 0x01; - private static final int BIT_MASK_ENABLE_COLOR = 0x02; - private static final int BIT_MASK_ENABLE_PROX = 0x04; - private static final int BIT_MASK_ENABLE_GESTURE = 0x40; - private static final int BIT_MASK_STATUS_GINT = 0x04; - private static final int BIT_MASK_GSTATUS_GFOV = 0x02; - private static final int BIT_MASK_GCONF4_GFIFO_CLR = 0x04; - - private static final int BIT_POS_PERS_PPERS = 4; - private static final int BIT_MASK_PERS_PPERS = 0xF0; - - private static final int BIT_POS_CONTROL_AGAIN = 0; - private static final int BIT_MASK_CONTROL_AGAIN = 3; - - public APDS9960(I2C i2c, ScienceLab scienceLab) throws Exception { - this.i2c = i2c; - if (scienceLab.isConnected()) { - enableProximity(false); - enableGesture(false); - enableColor(false); - - setProximityInterruptThreshold(new int[]{0, 0, 0}); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0}, APDS9960_GPENTH); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0}, APDS9960_GEXTH); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0}, APDS9960_GCONF1); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0}, APDS9960_GCONF2); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0}, APDS9960_GCONF4); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0}, APDS9960_GPULSE); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{255}, APDS9960_ATIME); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0}, APDS9960_CONTROL); - - clearInterrupt(); - - setBit(APDS9960_GCONF4, BIT_MASK_GCONF4_GFIFO_CLR, true); - - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0}, APDS9960_ENABLE); - Thread.sleep(25); - - enable(true); - Thread.sleep(10); - - setProximityInterruptThreshold(new int[]{0, 5, 4}); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0x05}, APDS9960_GPENTH); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0x1E}, APDS9960_GEXTH); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0x82}, APDS9960_GCONF1); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0x41}, APDS9960_GCONF2); - i2c.write(APDS9960_I2C_ADDRESS, new int[]{0x85}, APDS9960_GPULSE); - setColorIntegrationTime(256); - setColorGain(1); - } - } - - private void enable(Boolean value) throws IOException { - setBit(APDS9960_ENABLE, BIT_MASK_ENABLE_EN, value); - } - - public void enableProximity(Boolean value) throws IOException { - setBit(APDS9960_ENABLE, BIT_MASK_ENABLE_PROX, value); - } - - public void enableGesture(Boolean value) throws IOException { - setBit(APDS9960_ENABLE, BIT_MASK_ENABLE_GESTURE, value); - } - - public void enableColor(Boolean value) throws IOException { - setBit(APDS9960_ENABLE, BIT_MASK_ENABLE_COLOR, value); - } - - private void setProximityInterruptThreshold(int[] settingArray) throws IOException { - if (settingArray.length != 0 && settingArray[0] >= 0 && settingArray[0] <= 255) { - i2c.write(APDS9960_I2C_ADDRESS, new int[]{settingArray[0]}, APDS9960_PILT); - } - if (settingArray.length > 1 && settingArray[0] >= 0 && settingArray[0] <= 255) { - i2c.write(APDS9960_I2C_ADDRESS, new int[]{settingArray[1]}, APDS9960_PILT); - } - int persist = 4; - if (settingArray.length > 2 && settingArray[0] >= 0 && settingArray[0] <= 15) { - persist = Math.min(settingArray[2], 15); - setBits(APDS9960_PERS, BIT_POS_PERS_PPERS, BIT_MASK_PERS_PPERS, persist); - } - } - - private void clearInterrupt() throws IOException { - i2c.write(APDS9960_I2C_ADDRESS, new int[]{}, APDS9960_AICLEAR); - } - - private void setColorIntegrationTime(int value) throws IOException { - i2c.write(APDS9960_I2C_ADDRESS, new int[]{256 - value}, APDS9960_ATIME); - } - - private void setColorGain(int value) throws IOException { - setBits(APDS9960_CONTROL, BIT_POS_CONTROL_AGAIN, BIT_MASK_CONTROL_AGAIN, value); - } - - public int getProximity() throws IOException { - ArrayList data = i2c.read(APDS9960_I2C_ADDRESS, 1, APDS9960_PDATA); - return data.get(0) & 0xFF; - } - - public int[] getColorData() throws IOException { - return new int[]{ - colorData16(APDS9960_CDATAL + 2), - colorData16(APDS9960_CDATAL + 4), - colorData16(APDS9960_CDATAL + 6), - colorData16(APDS9960_CDATAL) - }; - } - - public int getGesture() throws IOException, InterruptedException { - if (getBit(APDS9960_GSTATUS, BIT_MASK_GSTATUS_GFOV)) { - setBit(APDS9960_GCONF4, BIT_MASK_GCONF4_GFIFO_CLR, true); - int waitCycles = 0; - while (!getBit(APDS9960_STATUS, BIT_MASK_STATUS_GINT) && waitCycles <= 30) { - Thread.sleep(3); - waitCycles++; - } - } - ArrayList> frame = new ArrayList<>(); - int datasetsAvailable = i2c.read(APDS9960_I2C_ADDRESS, 1, APDS9960_GFLVL).get(0) & 0xFF; - - if (getBit(APDS9960_STATUS, BIT_MASK_STATUS_GINT) && datasetsAvailable > 0) { - while (true) { - int datasetCount = i2c.read(APDS9960_I2C_ADDRESS, 1, APDS9960_GFLVL).get(0) & 0xFF; - if (datasetCount == 0) break; - - ArrayList buffer = i2c.read(APDS9960_I2C_ADDRESS, Math.min(128, datasetCount * 4), APDS9960_GFIFO_U); - - for (int i = 0; i < datasetCount; i++) { - ArrayList bufferDataset = new ArrayList<>(4); - for (int j = 0; j < 4; j++) { - bufferDataset.add(buffer.get(i * 4 + j) & 0xFF); - } - - boolean fullySaturated = bufferDataset.stream().allMatch(val -> val == 255); - boolean fullyZero = bufferDataset.stream().allMatch(val -> val == 0); - boolean highCount = bufferDataset.stream().allMatch(val -> val >= 30); - - if (!fullySaturated && !fullyZero && highCount) { - if (frame.size() < 2) { - frame.add(bufferDataset); - } else { - frame.set(1, bufferDataset); - } - } - } - Thread.sleep(30); - } - } - - if (frame.size() < 2) { - return 0; - } - - int[] frame0 = frame.get(0).stream().mapToInt(Integer::intValue).toArray(); - int[] frame1 = frame.get(1).stream().mapToInt(Integer::intValue).toArray(); - - int frUd = calcDelta(frame0[0], frame0[1]); - int frLr = calcDelta(frame0[2], frame0[3]); - int lrUd = calcDelta(frame1[0], frame1[1]); - int lrLr = calcDelta(frame1[2], frame1[3]); - - int deltaUd = lrUd - frUd; - int deltaLr = lrLr - frLr; - - int stateUd = getState(deltaUd); - int stateLr = getState(deltaLr); - - return determineGesture(stateUd, stateLr, deltaUd, deltaLr); - } - - private int calcDelta(int a, int b) { - return ((a - b) * 100) / (a + b); - } - - private int getState(int delta) { - if (delta >= 30) return 1; - if (delta <= -30) return -1; - return 0; - } - - private int determineGesture(int stateUd, int stateLr, int deltaUd, int deltaLr) { - if (stateUd == -1 && stateLr == 0) return 1; - if (stateUd == 1 && stateLr == 0) return 2; - if (stateUd == 0 && stateLr == -1) return 3; - if (stateUd == 0 && stateLr == 1) return 4; - - boolean udDominant = Math.abs(deltaUd) > Math.abs(deltaLr); - if (stateUd == -1 && stateLr == 1) return udDominant ? 1 : 4; - if (stateUd == 1 && stateLr == -1) return udDominant ? 2 : 3; - if (stateUd == -1) return udDominant ? 1 : 3; - if (stateUd == 1) return udDominant ? 2 : 3; - - return 0; - } - - - private Boolean getBit(int register, int mask) throws IOException { - ArrayList data = i2c.read(APDS9960_I2C_ADDRESS, 1, register); - return (((data.get(0) & 0xFF) & mask) == 0) ? false : true; - } - - private void setBit(int register, int mask, Boolean value) throws IOException { - ArrayList data = i2c.read(APDS9960_I2C_ADDRESS, 1, register); - if (value) { - data.set(0, (data.get(0) & 0xFF) | mask); - } else { - data.set(0, (data.get(0) & 0xFF) & ~mask); - } - i2c.write(APDS9960_I2C_ADDRESS, data.stream().mapToInt(Integer::intValue).toArray(), register); - } - - private void setBits(int register, int pos, int mask, int value) throws IOException { - ArrayList data = i2c.read(APDS9960_I2C_ADDRESS, 1, register); - data.set(0, ((data.get(0) & 0xFF) & ~mask) | (value << pos)); - i2c.write(APDS9960_I2C_ADDRESS, data.stream().mapToInt(Integer::intValue).toArray(), register); - } - - private int colorData16(int register) throws IOException { - ArrayList data = i2c.read(APDS9960_I2C_ADDRESS, 2, register); - return ((data.get(1) & 0xFF) << 8) | ((data.get(0) & 0xFF)); - } -} diff --git a/app/src/main/java/io/pslab/communication/sensors/BH1750.java b/app/src/main/java/io/pslab/communication/sensors/BH1750.java deleted file mode 100644 index 9b1423146..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/BH1750.java +++ /dev/null @@ -1,55 +0,0 @@ -package io.pslab.communication.sensors; - -import io.pslab.communication.peripherals.I2C; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; - -public class BH1750 { - private String TAG = "BH1750"; - private int POWER_ON = 0x01; - private int RESET = 0x07; - private int RES_1000mLx = 0x10; - private int RES_500mLx = 0x11; - private int RES_4000mLx = 0x13; - private I2C i2c; - - private int[] gainChoices = {RES_500mLx, RES_1000mLx, RES_4000mLx}; - private String[] gainLiteralChoices = {"500mLx", "1000mLx", "4000mLx"}; - public int gain = 0; - public double[] scaling = {2, 1, 0.25}; - - public int NUMPLOTS = 1; - public String[] PLOTNAMES = {"Lux"}; - private int ADDRESS = 0x23; - private String name = "Luminosity"; - - - public BH1750(I2C i2c) throws IOException, InterruptedException { - this.i2c = i2c; - init(); - } - - private void init() throws IOException { - i2c.writeBulk(ADDRESS, new int[]{RES_500mLx}); - } - - public void setRange(String g) throws IOException { - int gain = Arrays.asList(gainLiteralChoices).indexOf(g); - i2c.writeBulk(ADDRESS, new int[]{gainChoices[gain]}); - } - - private ArrayList getVals(int numbytes) throws IOException { - ArrayList vals = i2c.simpleRead(ADDRESS, numbytes); - return vals; - } - - public Double getRaw() throws IOException { - ArrayList vals = getVals(2); - if (vals.size() == 3) - return (vals.get(0) << 8 | vals.get(1)) / 1.2; - else - return 0.0; - } -} diff --git a/app/src/main/java/io/pslab/communication/sensors/BMP180.java b/app/src/main/java/io/pslab/communication/sensors/BMP180.java deleted file mode 100644 index 917b181f7..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/BMP180.java +++ /dev/null @@ -1,185 +0,0 @@ -package io.pslab.communication.sensors; - -import android.util.Log; - -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; - -import static java.lang.Math.pow; - -/** - * Created by akarshan on 4/18/17. - */ - -public class BMP180 { - - private static final String TAG = "BMP180"; - // BMP180 default address - private static final int ADDRESS = 0x77; - - // Operating Modes - private static final int ULTRALOWPOWER = 0; - private static final int STANDARD = 1; - private static final int HIGHRES = 2; - private static final int ULTRAHIGHRES = 3; - - // BMP180 Registers - private static final int CAL_AC1 = 0xAA; - private static final int CAL_AC2 = 0xAC; - private static final int CAL_AC3 = 0xAE; - private static final int CAL_AC4 = 0xB0; - private static final int CAL_AC5 = 0xB2; - private static final int CAL_AC6 = 0xB4; - private static final int CAL_B1 = 0xB6; - private static final int CAL_B2 = 0xB8; - private static final int CAL_MB = 0xBA; - private static final int CAL_MC = 0xBC; - private static final int CAL_MD = 0xBE; - private static final int CONTROL = 0xF4; - private static final int TEMPDATA = 0xF6; - private static final int PRESSDATA = 0xF6; - - // BMP180 Commands - private static final int READTEMPCMD = 0x2E; - private static final int READPRESSURECMD = 0x34; - - private int mode = HIGHRES; - private int oversampling = mode; - - public int NUMPLOTS = 3; - public String[] PLOTNAMES = {"Temperature", "Pressure", "Altitude"}; - public String name = "Altimeter BMP180"; - - private I2C i2c; - private int ac1; - private int ac2; - private int ac3; - private int ac4; - private int ac5; - private int ac6; - private int b1; - private int b2; - private int mb; - private int mc; - private int md; - private double temperature; - private double pressure; - private static final double SEA_LEVEL_PRESSURE = 101325.0; - - public BMP180(I2C i2c, ScienceLab scienceLab) throws IOException, InterruptedException { - this.i2c = i2c; - if (scienceLab.isConnected()) { - ac1 = readInt16(CAL_AC1); - ac2 = readInt16(CAL_AC2); - ac3 = readInt16(CAL_AC3); - ac4 = readUInt16(CAL_AC4); - ac5 = readUInt16(CAL_AC5); - ac6 = readUInt16(CAL_AC6); - b1 = readInt16(CAL_B1); - b2 = readInt16(CAL_B2); - mb = readInt16(CAL_MB); - mc = readInt16(CAL_MC); - md = readInt16(CAL_MD); - - Log.v("calib", Arrays.toString((new double[]{ac1, ac2, ac3, ac4, ac5, ac6, b1, b2, mb, mc, md}))); - } - } - - private int readInt16(int address) throws IOException { - ArrayList data = i2c.read(ADDRESS, 2, address); - int value = ((data.get(0) & 0xFF) << 8) | (data.get(1) & 0xFF); - if ((value & 0x8000) != 0) { // Check if the sign bit is set - value |= 0xFFFF0000; // Sign-extend to 32 bits - } - return value; - } - - private int readUInt16(int address) throws IOException { - ArrayList data = i2c.read(ADDRESS, 2, address); - return ((data.get(0) & 0xFF) << 8) | (data.get(1) & 0xFF); - } - - private int readRawTemperature() throws IOException, InterruptedException { - i2c.write(ADDRESS, new int[]{READTEMPCMD}, CONTROL); - TimeUnit.MILLISECONDS.sleep(5); - int raw = readUInt16(TEMPDATA); - return raw; - } - - private Double readTemperature() throws IOException, InterruptedException { - int ut = readRawTemperature(); - // Calculations from section 3.5 of the datasheet - int x1 = ((ut - ac6) * ac5) >> 15; - int x2 = (mc << 11) / (x1 + md); - int b5 = x1 + x2; - temperature = ((b5 + 8) >> 4) / 10.0; - return temperature; - } - - public void setOversampling(int num) { - oversampling = num; - } - - private int readRawPressure() throws IOException, InterruptedException { - int[] delays = {5, 8, 14, 26}; - i2c.write(ADDRESS, new int[]{READPRESSURECMD + (mode << 6)}, CONTROL); - TimeUnit.MILLISECONDS.sleep(delays[oversampling]); - int msb = i2c.readByte(ADDRESS, PRESSDATA) & 0xFF; - int lsb = i2c.readByte(ADDRESS, PRESSDATA + 1) & 0xFF; - int xlsb = i2c.readByte(ADDRESS, PRESSDATA + 2) & 0xFF; - return ((msb << 16) + (lsb << 8) + xlsb) >> (8 - mode); - } - - private Double readPressure() throws IOException, InterruptedException { - int ut = readRawTemperature(); - int up = readRawPressure(); - // Calculations from section 3.5 of the datasheet - int x1 = ((ut - ac6) * ac5) >> 15; - int x2 = (mc << 11) / (x1 + md); - int b5 = x1 + x2; - // Pressure Calculations - int b6 = b5 - 4000; - x1 = (b2 * (b6 * b6) >> 12) >> 11; - x2 = (ac2 * b6) >> 11; - int x3 = x1 + x2; - int b3 = (((ac1 * 4 + x3) << mode) + 2) / 4; - x1 = (ac3 * b6) >> 13; - x2 = (b1 * ((b6 * b6) >> 12)) >> 16; - x3 = ((x1 + x2) + 2) >> 2; - int b4 = (ac4 * (x3 + 32768)) >> 15; - int b7 = (up - b3) * (50000 >> mode); - int p; - if (b7 < 0x80000000) { - p = (b7 * 2) / b4; - } else { - p = (b7 / b4) * 2; - } - x1 = (p >> 8) * (p >> 8); - x1 = (x1 * 3038) >> 16; - x2 = (-7357 * p) >> 16; - pressure = p + ((x1 + x2 + 3791) >> 4); - return pressure; - } - - public double altitude() { - // Calculation from section 3.6 of the datasheet - return (44330.0 * (1 - pow(pressure / SEA_LEVEL_PRESSURE, 1 / 5.255))); - } - - public double seaLevel(double pressure, double altitude) { - //given a calculated pressure and altitude, return the sealevel - return (pressure / pow(1 - (altitude / 44330.0), 5.255)); - } - - public double[] getRaw() throws IOException, InterruptedException { - temperature = readTemperature(); - pressure = readPressure(); - return (new double[]{temperature, altitude(), pressure}); - } - -} diff --git a/app/src/main/java/io/pslab/communication/sensors/CCS811.java b/app/src/main/java/io/pslab/communication/sensors/CCS811.java deleted file mode 100644 index d4887e057..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/CCS811.java +++ /dev/null @@ -1,103 +0,0 @@ -package io.pslab.communication.sensors; - -import android.util.Log; - -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; - -import java.io.IOException; -import java.util.ArrayList; - -public class CCS811 { - private static final int ADDRESS = 0x5A; - private final I2C i2c; - - // Figure 14: CCS811 Application Register Map - private static final int ALG_RESULT_DATA = 0x02; // ALG_RESULT_DATA # R 8 bytes Algorithm result. The most significant 2 bytes contain a up to ppm estimate of the equivalent CO2 (eCO2) level, and - private static final int HW_ID = 0x20; // HW_ID # R 1 byte Hardware ID. The value is 0x81 - private static final int FW_BOOT_VERSION = 0x23; // FW_Boot_Version # R 2 bytes firmware version number for the boot code. Firmware Application Version. The first 2 bytes contain - private static final int FW_APP_VERSION = 0x24; // FW_App_Version # R 2 bytes the firmware version number for the application code - private static final int MEAS_MODE = 0x01; // MEAS_MODE # R/W 1 byte Measurement mode and conditions register Algorithm result. - - // Figure 25: CCS811 Bootloader Register Map - // Address Register R/W Size Description - private static final int HW_Version = 0x21; - private static final int APP_START = 0xF4; - - // Measurement Mode - private static final int DRIVE_MODE_1SEC = 0x01; - - public CCS811(I2C i2c, ScienceLab scienceLab) throws Exception { - this.i2c = i2c; - if (scienceLab.isConnected()) { - fetchID(); - appStart(); - Thread.sleep(100); - disableInterrupt(); - setMeasMode(); - } - } - - private void setMeasMode() throws IOException { - i2c.write(ADDRESS, new int[]{1 << 2 | CCS811.DRIVE_MODE_1SEC << 4}, MEAS_MODE); - } - - private void disableInterrupt() throws IOException { - i2c.write(ADDRESS, new int[]{1 << 2 | 3 << 4}, MEAS_MODE); - } - - private void fetchID() throws IOException, InterruptedException { - int hardwareId = i2c.read(ADDRESS, 1, HW_ID).get(0) & 0xFF; - Thread.sleep(20); - int hardwareVersion = i2c.read(ADDRESS, 1, HW_Version).get(0) & 0xFF; - Thread.sleep(20); - int bootVersion = i2c.read(ADDRESS, 2, FW_BOOT_VERSION).get(0) & 0xFF; - Thread.sleep(20); - int appVersion = i2c.read(ADDRESS, 2, FW_APP_VERSION).get(0) & 0xFF; - Thread.sleep(20); - - Log.d("CCS811", "Hardware ID: " + hardwareId); - Log.d("CCS811", "Hardware Version: " + hardwareVersion); - Log.d("CCS811", "Boot Version: " + bootVersion); - Log.d("CCS811", "App Version: " + appVersion); - } - - private void appStart() throws IOException { - i2c.write(ADDRESS, new int[]{}, APP_START); - } - - private String decodeError(int error) { - String e = ""; - if ((error & (1)) > 0) { - e += ", The CCS811 received an I²C write request addressed to this station but with invalid register address ID"; - } - if ((error & (1 << 1)) > 0) { - e += ", The CCS811 received an I²C read request to a mailbox ID that is invalid"; - } - if ((error & (1 << 2)) > 0) { - e += ", The CCS811 received an I²C request to write an unsupported mode to MEAS_MODE"; - } - if ((error & (1 << 3)) > 0) { - e += ", The sensor resistance measurement has reached or exceeded the maximum range"; - } - if ((error & (1 << 4)) > 0) { - e += ", The Heater current in the CCS811 is not in range"; - } - if ((error & (1 << 5)) > 0) { - e += ", The Heater voltage is not being applied correctly"; - } - return "Error: " + e.substring(2); - } - - public int[] getRaw() throws IOException { - ArrayList data = i2c.read(ADDRESS, 8, ALG_RESULT_DATA); - int eCO2 = ((data.get(0) & 0xFF) << 8) | (data.get(1) & 0xFF); - int TVOC = ((data.get(2) & 0xFF) << 8) | (data.get(3) & 0xFF); - int errorId = data.get(5) & 0xFF; - - if (errorId > 0) { - Log.d("CCS811", decodeError(errorId)); - } - return (new int[]{eCO2, TVOC}); - } -} diff --git a/app/src/main/java/io/pslab/communication/sensors/ComplementaryFilter.java b/app/src/main/java/io/pslab/communication/sensors/ComplementaryFilter.java deleted file mode 100644 index f68a1aa38..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/ComplementaryFilter.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.pslab.communication.sensors; - -import static java.lang.Math.abs; -import static org.apache.commons.math3.util.FastMath.atan2; - -/** - * Created by akarshan on 4/23/17. - */ - -public class ComplementaryFilter { - private double dt, pitch, roll; - - public ComplementaryFilter() { - pitch = 0.; - roll = 0.; - dt = 0.001; - } - - public void addData(double[] accelerometerData, double[] gyroscopeData) { - pitch += (gyroscopeData[0]) * dt; // Angle around the X-axis - roll -= (gyroscopeData[1]) * dt; //Angle around the Y-axis - double pi = 3.14159265359; - double forceMagnitudeApprox = abs(accelerometerData[0]) + abs(accelerometerData[1]) + abs(accelerometerData[2]); - double pitchAcc = Math.atan2(accelerometerData[1], accelerometerData[2]) * 180 / pi; - pitch = pitch * 0.98 + pitchAcc * 0.02; - double rollAcc = atan2(accelerometerData[0], accelerometerData[2]) * 180 / pi; - roll = roll * 0.98 + rollAcc * 0.02; - - } - - public double[] getData() { - return new double[]{roll, pitch}; - } - -} diff --git a/app/src/main/java/io/pslab/communication/sensors/HMC5883L.java b/app/src/main/java/io/pslab/communication/sensors/HMC5883L.java deleted file mode 100644 index a8ac9886e..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/HMC5883L.java +++ /dev/null @@ -1,100 +0,0 @@ -package io.pslab.communication.sensors; - -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; - -/** - * Created by akarshan on 4/23/17. - *

- * ScienceLab instance of I2C need to be passed to the MF522 constructor. - *

- */ - -public class HMC5883L { - private int CONFA = 0x00; - private int CONFB = 0x01; - private int MODE = 0x02; - private int STATUS = 0x09; - - //--------CONFA register bits. 0x00-----------// - - private int samplesToAverage = 0; - private ArrayList samplesToAverageChoices = new ArrayList<>(Arrays.asList(1, 2, 4, 8)); - - private int dataOutputRate = 6; - private ArrayList dataOutputRateChoices = new ArrayList(Arrays.asList(0.75, 1.5, 3., 7.5, 15., 30., 75.)); - - private int measurementConf = 0; - - //--------CONFB register bits. 0x01-----------// - - private int gainValue = 7; //least sensitive - private ArrayList gainChoices = new ArrayList<>(Arrays.asList(8, 7, 6, 5, 4, 3, 2, 1)); - private ArrayList scaling = new ArrayList<>(Arrays.asList(1370., 1090., 820., 660., 440., 390., 330., 230.)); - private int ADDRESS = 0x1E; - public String name = "Magnetometer"; - public int NUMPLOTS = 3; - public String[] PLOTNAMES = {"Bx", "By", "Bz"}; - - private I2C i2c; - - public HMC5883L(I2C i2c, ScienceLab scienceLab) throws IOException { - this.i2c = i2c; - if (scienceLab.isConnected()) { - init(); - } - } - - private void init() throws IOException { - writeCONFA(); - writeCONFB(); - i2c.writeBulk(ADDRESS, new int[]{MODE, 0}); //enable continuous measurement mode - - } - - private void writeCONFB() throws IOException { - i2c.writeBulk(ADDRESS, new int[]{CONFB, gainValue << 5}); //set gain - } - - - private void writeCONFA() throws IOException { - i2c.writeBulk(ADDRESS, new int[]{CONFA, (dataOutputRate << 2) | (samplesToAverage << 5) | (measurementConf)}); - } - - public void setSamplesToAverage(int num) throws IOException { - samplesToAverage = samplesToAverageChoices.indexOf(num); - writeCONFA(); - } - - public void setDataOutputRate(double rate) throws IOException { - dataOutputRate = dataOutputRateChoices.indexOf(rate); - writeCONFA(); - } - - public void setGain(int gain) throws IOException { - gainValue = gainChoices.indexOf(gain); - writeCONFB(); - } - - public ArrayList getVals(int addr, int bytes) throws IOException { - return i2c.readBulk(ADDRESS, addr, bytes); - } - - public ArrayList getRaw() throws IOException { - ArrayList returnList = new ArrayList<>(); - ArrayList vals = getVals(0x03, 6); - if (vals.size() == 6) { - for (int a = 0; a < 3; a++) { - returnList.add((vals.get(a * 2) << 8 | vals.get(a * 2 + 1)) / scaling.get(gainValue)); - } - return returnList; - } else - return null; - } - -} - diff --git a/app/src/main/java/io/pslab/communication/sensors/KalmanFilter.java b/app/src/main/java/io/pslab/communication/sensors/KalmanFilter.java deleted file mode 100644 index 43641c1a0..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/KalmanFilter.java +++ /dev/null @@ -1,34 +0,0 @@ -package io.pslab.communication.sensors; - -/** - * Created by akarshan on 4/21/17. - */ - -public class KalmanFilter { - private double processVariance; - private double estimatedMeasurementVariance; - private double posteriEstimate; - private double posteriErrorEstimate; - private double prioriEstimate; - private double prioriErrorEstimate; - private double blendingFactor; - - public KalmanFilter(double processVariance, double estimatedMeasurementVariance) { - this.processVariance = processVariance; - this.estimatedMeasurementVariance = estimatedMeasurementVariance; - posteriEstimate = 0.0; - posteriErrorEstimate = 1.0; - } - - void inputLatestNoisyMeasurement(double measurement) { - prioriEstimate = posteriEstimate; - prioriErrorEstimate = posteriErrorEstimate + processVariance; - blendingFactor = prioriErrorEstimate / (prioriErrorEstimate + estimatedMeasurementVariance); - posteriEstimate = prioriEstimate + blendingFactor * (measurement - prioriEstimate); - posteriErrorEstimate = (1 - blendingFactor) * prioriErrorEstimate; - } - - double getLatestEstimatedMeasurement() { - return posteriEstimate; - } -} diff --git a/app/src/main/java/io/pslab/communication/sensors/MF522.java b/app/src/main/java/io/pslab/communication/sensors/MF522.java deleted file mode 100644 index c06c17496..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/MF522.java +++ /dev/null @@ -1,533 +0,0 @@ -package io.pslab.communication.sensors; - -import android.util.Log; - -import io.pslab.communication.peripherals.SPI; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; - -/** - * Created by akarshan on 4/22/17. - *

- * ScienceLab instance of SPI need to be passed to the MF522 constructor. - * refer https://github.com/fossasia/pslab-python/blob/development/PSL/SENSORS/MF522.py#L465 - * to port the code in sciencelab.java - *

- */ - -public class MF522 { - private String TAG = "MF522"; - private int CommandReg = 0x01 << 1; // starts and stops command execution - private int ComIEnReg = 0x02 << 1; // enable and disable interrupt request control bits - private int DivIEnReg = 0x03 << 1; // enable and disable interrupt request control bits - private int ComIrqReg = 0x04 << 1; // interrupt request bits - private int DivIrqReg = 0x05 << 1; // interrupt request bits - private int ErrorReg = 0x06 << 1; // error bits showing the error status of the last command executed - private int Status1Reg = 0x07 << 1; // communication status bits - private int Status2Reg = 0x08 << 1; // receiver and transmitter status bits - private int FIFODataReg = 0x09 << 1; // input and output of 64 byte FIFO buffer - private int FIFOLevelReg = 0x0A << 1; // number of bytes stored in the FIFO buffer - private int WaterLevelReg = 0x0B << 1; // level for FIFO underflow and overflow warning - private int ControlReg = 0x0C << 1; // miscellaneous control registers - private int BitFramingReg = 0x0D << 1; // adjustments for bit-oriented frames - private int CollReg = 0x0E << 1; // bit position of the first bit-collision detected on the RF sciencelab - - private int ModeReg = 0x11 << 1; // defines general modes for transmitting and receiving - private int TxModeReg = 0x12 << 1; // defines transmission data rate and framing - private int RxModeReg = 0x13 << 1; // defines reception data rate and framing - private int TxControlReg = 0x14 << 1; // controls the logical behavior of the antenna driver pins TX1 and TX2 - private int TxASKReg = 0x15 << 1; // controls the setting of the transmission modulation - private int TxSelReg = 0x16 << 1; // selects the internal sources for the antenna driver - private int RxSelReg = 0x17 << 1; // selects internal receiver settings - private int RxThresholdReg = 0x18 << 1; // selects thresholds for the bit decoder - private int DemodReg = 0x19 << 1; // defines demodulator settings - private int MfTxReg = 0x1C << 1; // controls some MIFARE communication transmit parameters - private int MfRxReg = 0x1D << 1; // controls some MIFARE communication receive parameters - private int SerialSpeedReg = 0x1F << 1; // selects the speed of the serial UART sciencelab - - private int CRCResultRegH = 0x21 << 1; // shows the MSB and LSB values of the CRC calculation - private int CRCResultRegL = 0x22 << 1; - private int ModWidthReg = 0x24 << 1; // controls the ModWidth setting? - private int RFCfgReg = 0x26 << 1; // configures the receiver gain - private int GsNReg = 0x27 << 1; // selects the conductance of the antenna driver pins TX1 and TX2 for modulation - private int CWGsPReg = 0x28 << 1; // defines the conductance of the p-driver output during periods of no modulation - private int ModGsPReg = 0x29 << 1; // defines the conductance of the p-driver output during periods of modulation - private int TModeReg = 0x2A << 1; // defines settings for the internal timer - private int TPrescalerReg = 0x2B << 1; // the lower 8 bits of the TPrescaler value. The 4 high bits are in TModeReg. - private int TReloadRegH = 0x2C << 1; // defines the 16-bit timer reload value - private int TReloadRegL = 0x2D << 1; - private int TCounterValueRegH = 0x2E << 1; // shows the 16-bit timer value - private int TCounterValueRegL = 0x2F << 1; - - private int TestSel1Reg = 0x31 << 1; // general test signal configuration - private int TestSel2Reg = 0x32 << 1; // general test signal configuration - private int TestPinEnReg = 0x33 << 1; // enables pin output driver on pins D1 to D7 - private int TestPinValueReg = 0x34 << 1; // defines the values for D1 to D7 when it is used as an I/O bus - private int TestBusReg = 0x35 << 1; // shows the status of the internal test bus - private int AutoTestReg = 0x36 << 1; // controls the digital self test - private int VersionReg = 0x37 << 1; // shows the software version - private int AnalogTestReg = 0x38 << 1; // controls the pins AUX1 and AUX2 - private int TestDAC1Reg = 0x39 << 1; // defines the test value for TestDAC1 - private int TestDAC2Reg = 0x3A << 1; // defines the test value for TestDAC2 - private int TestADCReg = 0x3B << 1; // shows the value of ADC I and Q channels - - // MFRC522 commands. Described in chapter 10 of the datasheet. - - private int PCD_Idle = 0x00; //no action, cancels current command execution - private int PCD_Mem = 0x01; //stores 25 bytes into the internal buffer - private int PCD_GenerateRandomID = 0x02; //generates a 10-byte random ID number - private int PCD_CalcCRC = 0x03; //activates the CRC coprocessor or performs a self test - private int PCD_Transmit = 0x04; // transmits data from the FIFO buffer - private int PCD_NoCmdChange = 0x07; - private int PCD_Receive = 0x08; //activates the receiver circuits - private int PCD_Transceive = 0x0C; //transmits data from FIFO buffer to antenna and automatically activates the receiver after transmission - private int PCD_MFAuthent = 0x0E; //performs the MIFARE standard authentication as a reader - private int PCD_SoftReset = 0x0F; //resets the MFRC522 - - private int RxGain_18dB = 0x00 << 4; // 000b - 18 dB, minimum - private int RxGain_23dB = 0x01 << 4; // 001b - 23 dB - private int RxGain_18dB_2 = 0x02 << 4; // 010b - 18 dB, it seems 010b is a duplicate for 000b - private int RxGain_23dB_2 = 0x03 << 4; // 011b - 23 dB, it seems 011b is a duplicate for 001b - private int RxGain_33dB = 0x04 << 4; // 100b - 33 dB, average, and typical default - private int RxGain_38dB = 0x05 << 4; // 101b - 38 dB - private int RxGain_43dB = 0x06 << 4; // 110b - 43 dB - private int RxGain_48dB = 0x07 << 4; // 111b - 48 dB, maximum - private int RxGain_min = 0x00 << 4; // 000b - 18 dB, minimum, convenience for RxGain_18dB - private int RxGain_avg = 0x04 << 4; // 100b - 33 dB, average, convenience for RxGain_33dB - private int RxGain_max = 0x07 << 4; // 111b - 48 dB, maximum, convenience for RxGain_48dB - - // The commands used by the PCD to manage communication with several PICCs (ISO 14443-3, Type A, section 6.4) - - private int PICC_CMD_REQA = 0x26; // REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection - private int PICC_CMD_WUPA = 0x52; // Wake-UP command, prepare for anticollision or selection. 7 bit frame. - private int PICC_CMD_CT = 0x88; // Cascade Tag. Not really a command, but used during anti collision. - private int PICC_CMD_SEL_CL1 = 0x93; // Anti collision/Select, Cascade Level 1 - private int PICC_CMD_SEL_CL2 = 0x95; // Anti collision/Select, Cascade Level 2 - private int PICC_CMD_SEL_CL3 = 0x97; // Anti collision/Select, Cascade Level 3 - private int PICC_CMD_HLTA = 0x50; // HaLT command, Type A. Instructs an ACTIVE PICC to go to state HALT. - - // The commands used for MIFARE Classic (from http://www.mouser.com/ds/2/302/MF1S503x-89574.pdf, Section 9) - // Use PCD_MFAuthent to authenticate access to a sector, then use these commands to read/write/modify the blocks on the sector. - // The read/write commands can also be used for MIFARE Ultralight. - - private int PICC_CMD_MF_AUTH_KEY_A = 0x60; // Perform authentication with Key A - private int PICC_CMD_MF_AUTH_KEY_B = 0x61; // Perform authentication with Key B - private int PICC_CMD_MF_READ = 0x30; // Reads one 16 byte block from the authenticated sector of the PICC. Also used for MIFARE Ultralight. - private int PICC_CMD_MF_WRITE = 0xA0; // Writes one 16 byte block to the authenticated sector of the PICC. Called "COMPATIBILITY WRITE" for MIFARE Ultralight. - private int PICC_CMD_MF_DECREMENT = 0xC0; // Decrements the contents of a block and stores the result in the internal data register. - private int PICC_CMD_MF_INCREMENT = 0xC1; // Increments the contents of a block and stores the result in the internal data register. - private int PICC_CMD_MF_RESTORE = 0xC2; // Reads the contents of a block into the internal data register. - private int PICC_CMD_MF_TRANSFER = 0xB0; // Writes the contents of the internal data register to a block. - - - private int NRSTPD = 22; - private int MAX_LEN = 16; - private int MI_OK = 0; - private int MI_NOTAGERR = 1; - private int MI_ERR = 2; - - private int PCD_CALCCRC = 0x03; - - private int PICC_REQIDL = 0x26; - private int PICC_REQALL = 0x52; - private int PICC_ANTICOLL = 0x93; - private int PICC_SElECTTAG = 0x93; - private int PICC_AUTHENT1A = 0x60; - private int PICC_AUTHENT1B = 0x61; - private int PICC_READ = 0x30; - private int PICC_WRITE = 0xA0; - private int PICC_DECREMENT = 0xC0; - private int PICC_INCREMENT = 0xC1; - private int PICC_RESTORE = 0xC2; - private int PICC_TRANSFER = 0xB0; - private int PICC_HALT = 0x50; - - // The commands used for MIFARE Ultralight (from http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf, Section 8.6) - // The PICC_CMD_MF_READ and PICC_CMD_MF_WRITE can also be used for MIFARE Ultralight. - - private int PICC_CMD_UL_WRITE = 0xA2; //Writes one 4 byte page to the PICC. - - private int MF_ACK = 0xA; // The MIFARE Classic uses a 4 bit ACK/NAK. Any other value than 0xA is NAK. - private int MF_KEY_SIZE = 6; // A Mifare Crypto1 key is 6 bytes. - private String cs; - private SPI spi; - private Boolean connected; - - public MF522(SPI spi, String cs) throws IOException, InterruptedException { - this.cs = cs; - this.spi = spi; - spi.setParameters(2, 1, 1, 0, 1); - if (!reset()) { - connected = false; - } - write(TModeReg, 0x80); - write(TPrescalerReg, 0xA9); - write(TReloadRegH, 0x03); - write(TReloadRegL, 0xE8); - - write(TxASKReg, 0x40); - write(ModeReg, 0x3D); - enableAntenna(); //Enable the antenna - } - - private void enableAntenna() throws IOException { - int val = read(TxControlReg); - if ((val & 0x03) != 0x03) - write(TxControlReg, val | 0x03); - } - - public boolean reset() throws IOException, InterruptedException { - write(CommandReg, PCD_SoftReset); - long startTime = System.currentTimeMillis(); - while ((read(CommandReg) & (1 << 4)) != 0) { - Log.v(TAG, "wait"); - TimeUnit.MILLISECONDS.sleep(100); - if (System.currentTimeMillis() - startTime > 0.5) - return false; - } - return true; - } - - private int write(int register, int val) throws IOException { - spi.setCS(cs, 0); - int ret = spi.send16(((register & 0x7F) << 8) | val); - spi.setCS(cs, 1); - return ret & 0xFF; - } - - public int read(int register) throws IOException { - spi.setCS(cs, 0); - int ret = spi.send16(((register & 0x80) << 8)); - spi.setCS(cs, 1); - return ret & 0xFF; - } - - public ArrayList readMany(int register, int total) throws IOException { - spi.setCS(cs, 0); - spi.send8(register); - ArrayList vals = new ArrayList<>(); - for (int a = 0; a < total - 1; a++) - vals.add(spi.send8(register)); - vals.add(spi.send8(0)); - spi.setCS(cs, 1); - return vals; - } - - public int getStatus() throws IOException { - return read(Status1Reg); - } - - public int getVersion() throws IOException { - int version = read(VersionReg); - if (version == 0x88) Log.v(TAG, "Cloned version: Fudan Semiconductors"); - else if (version == 0x90) Log.v(TAG, "version 1.0"); - else if (version == 0x91) Log.v(TAG, "version 1.0"); - else if (version == 0x92) Log.v(TAG, "version 2.0"); - else Log.v(TAG, "Unknown version " + version); - return version; - } - - private void setBitMask(int register, int mask) throws IOException { - int tmp = read(register); - write(register, tmp | mask); - } - - private void clearBitMask(int register, int mask) throws IOException { - int tmp = read(register); - write(register, tmp & (~mask)); - } - - private ArrayList MFRC522ToCard(int command, ArrayList sendData) throws IOException { - ArrayList returnedData = new ArrayList<>(); - int backLen = 0; - int status = MI_ERR; - int irqEn = 0x00; - int waitIRq = 0x00; - int lastBits; - int n = 0; - int i = 0; - - if (command == PCD_MFAuthent) { - irqEn = 0x12; - waitIRq = 0x10; - } - if (command == PCD_Transceive) { - irqEn = 0x77; - waitIRq = 0x30; - } - write(ComIEnReg, irqEn | 0x80); - clearBitMask(ComIrqReg, 0x80); - setBitMask(FIFOLevelReg, 0x80); - - write(CommandReg, PCD_Idle); - - for (int a = 0; a < sendData.size(); a++) - write(FIFODataReg, a); - write(CommandReg, command); - - if (command == PCD_Transceive) - setBitMask(BitFramingReg, 0x80); - - i = 2000; - while (true) { - n = read(ComIrqReg); - i = i - 1; - if (!(i != 0 && ~(n & 0x01) != 0 && ~(n & waitIRq) != 0)) //needs to be checked - break; - } - - clearBitMask(BitFramingReg, 0x80); - - if (i != 0) { - if ((read(ErrorReg) & 0x1B) == 0x00) { - status = MI_OK; - if ((n & irqEn & 0x01) != 0) - status = MI_NOTAGERR; - if (command == PCD_Transceive) { - n = read(FIFOLevelReg); - lastBits = read(ControlReg) & 0x07; - if (lastBits != 0) - backLen = (n - 1) * 8 + lastBits; - else - backLen = n * 8; - if (n == 0) - n = 1; - if (n > MAX_LEN) - n = MAX_LEN; - - i = 0; - while (i < n) { - returnedData.add(read(FIFODataReg)); - i = i + 1; - } - } - } else - status = MI_ERR; - } - return new ArrayList(Arrays.asList(status, returnedData, backLen)); - } - - public ArrayList MFRC522Request(int reqMode) throws IOException, NullPointerException { - ArrayList mfrc522ToCard; - ArrayList returnedData = new ArrayList<>(); - int backBits = 0; - int status; - ArrayList TagType = new ArrayList<>(); - - write(BitFramingReg, 0x07); - - TagType.add(reqMode); - mfrc522ToCard = MFRC522ToCard(PCD_Transceive, TagType); - status = (int) mfrc522ToCard.get(0); - returnedData = (ArrayList) mfrc522ToCard.get(1); - backBits = (int) mfrc522ToCard.get(2); - - if (status != MI_OK | backBits != 0x10) - status = MI_ERR; - - return new ArrayList(Arrays.asList(status, returnedData)); - } - - public ArrayList MFRC522Anticoll() throws IOException { - ArrayList returnedData; - int status; - int backLen; - int serNumCheck = 0; - ArrayList serNum = new ArrayList<>(); - - write(BitFramingReg, 0x00); - - serNum.add(PICC_ANTICOLL); - serNum.add(0x20); - - ArrayList mfrc522ToCard = MFRC522ToCard(PCD_Transceive, serNum); - status = (int) mfrc522ToCard.get(0); - returnedData = (ArrayList) mfrc522ToCard.get(1); - backLen = (int) mfrc522ToCard.get(2); - if (status == MI_OK) { - int i = 0; - if (returnedData.size() == 5) { - while (i < 4) { - serNumCheck = serNumCheck ^ returnedData.get(i); - i = i + 1; - } - if (serNumCheck != returnedData.get(i)) - status = MI_ERR; - } else status = MI_ERR; - } - return new ArrayList(Arrays.asList(status, returnedData)); - - } - - private ArrayList calulateCRC(ArrayList pIndata) throws IOException { - int n; - ArrayList pOutData = new ArrayList<>(); - clearBitMask(DivIrqReg, 0x04); - setBitMask(FIFOLevelReg, 0x80); - for (int a = 0; a < pIndata.size(); a++) - write(FIFODataReg, a); - write(CommandReg, PCD_CALCCRC); - for (int i = 0; i < 0xFF; i++) { - n = read(DivIrqReg); - if ((n & 0x040) != 0) - break; - } - pOutData.add(read(CRCResultRegL)); - pOutData.add(read(CRCResultRegH)); - return pOutData; - } - - public int MFRC522SelectTag(ArrayList serNum) throws IOException { - ArrayList returnedData; - ArrayList buf = new ArrayList<>(); - int status; - int backLen; - - buf.add(PICC_SElECTTAG); - buf.add(0x70); - int i = 0; - while (i < 5) { - buf.add(serNum.get(i)); - i = i + 1; - } - ArrayList pOut = calulateCRC(buf); - buf.add(pOut.get(0)); - buf.add(pOut.get(1)); - ArrayList mfrc522ToCard = MFRC522ToCard(PCD_Transceive, buf); - status = (int) mfrc522ToCard.get(0); - returnedData = (ArrayList) mfrc522ToCard.get(1); - backLen = (int) mfrc522ToCard.get(2); - if ((status == MI_OK) && (backLen == 0x18)) { - return returnedData.get(0); - } else - return 0; - } - - private int MFRC522Auth(int authMode, int blockAddress, int[] sectorkey, int[] serNum) throws IOException { - ArrayList buff = new ArrayList<>(); - ArrayList returnedData; - int status; - int backLen; - // First byte should be the authMode (A or B) - buff.add(authMode); - // Second byte is the trailerBlock (usually 7) - buff.add(blockAddress); - // Now we need to append the authKey which usually is 6 bytes of 0xFF - int i = 0; - while (i < sectorkey.length) { - buff.add(sectorkey[i]); - i = i + 1; - } - i = 0; - // Next we append the first 4 bytes of the UID - while (i < 4) { - buff.add(serNum[i]); - i = i + 1; - } - // Now we start the authentication itself - ArrayList mfrc522ToCard = MFRC522ToCard(PCD_MFAuthent, buff); - status = (int) mfrc522ToCard.get(0); - returnedData = (ArrayList) mfrc522ToCard.get(1); - backLen = (int) mfrc522ToCard.get(2); - - // Check if an error occurred - if (status != MI_OK) - Log.v(TAG, "AUTH ERROR !!"); - if ((read(Status2Reg) & 0x08) == 0) - Log.v(TAG, "AUTH ERROR(status2reg & 0x08) != 0"); - - // Return the status - return status; - } - - public void MFRC522StopCrypto1() throws IOException { - clearBitMask(Status2Reg, 0x08); - setBitMask(CommandReg, 0x10); - } - - private ArrayList MFRC522Read(int blockAddress) throws IOException { - ArrayList recvData = new ArrayList<>(); - int status; - int backLen; - ArrayList returnedData; - - recvData.add(PICC_READ); - recvData.add(blockAddress); - ArrayList pOut = calulateCRC(recvData); - recvData.add(pOut.get(0)); - recvData.add(pOut.get(1)); - ArrayList mfrc522ToCard = MFRC522ToCard(PCD_Transceive, recvData); - - status = (int) mfrc522ToCard.get(0); - returnedData = (ArrayList) mfrc522ToCard.get(1); - backLen = (int) mfrc522ToCard.get(2); - - if (status != MI_OK) { - Log.v(TAG, "Error while reading!"); - } - return returnedData; - } - - public void MFRC522Write(int blockAddress, int[] writeData) throws IOException { - ArrayList buff = new ArrayList<>(); - int status; - int backLen; - ArrayList returnedData; - - buff.add(PICC_WRITE); - buff.add(blockAddress); - ArrayList crc = calulateCRC(buff); - buff.add(crc.get(0)); - buff.add(crc.get(1)); - - ArrayList mfrc522ToCard = MFRC522ToCard(PCD_Transceive, buff); - status = (int) mfrc522ToCard.get(0); - returnedData = (ArrayList) mfrc522ToCard.get(1); - backLen = (int) mfrc522ToCard.get(2); - - if ((status != MI_OK) || (backLen != 4) || ((returnedData.get(0) & 0x0F) != 0x0A)) - status = MI_ERR; - - Log.v(TAG, backLen + " returnedData &0x0F == 0x0A " + (returnedData.get(0) & 0x0F)); - if (status == MI_OK) { - int i = 0; - ArrayList buf = new ArrayList<>(); - - while (i < 16) { - buf.add(writeData[i]); - i = i + 1; - } - - ArrayList bufCRC = calulateCRC(buf); - buf.add(bufCRC.get(0)); - buf.add(bufCRC.get(1)); - - mfrc522ToCard = MFRC522ToCard(PCD_Transceive, buff); - status = (int) mfrc522ToCard.get(0); - returnedData = (ArrayList) mfrc522ToCard.get(1); - backLen = (int) mfrc522ToCard.get(2); - if ((status != MI_OK) || (backLen != 4) || ((returnedData.get(0) & 0x0F) != 0x0A)) - Log.v(TAG, "Error while writing"); - if (status == MI_OK) - Log.v(TAG, "Data written"); - } - - } - - public void MFRC522DumpClassic1K(int key[], int uid[]) throws IOException { - int i = 0; - while (i < 64) { - int status = MFRC522Auth(PICC_AUTHENT1A, i, key, uid); - // Check if authenticated - if (status == MI_OK) - MFRC522Read(i); - else { - Log.v(TAG, "Authentication error"); - i = i + 1; - } - } - } -} diff --git a/app/src/main/java/io/pslab/communication/sensors/MLX90614.java b/app/src/main/java/io/pslab/communication/sensors/MLX90614.java deleted file mode 100644 index d95fb3348..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/MLX90614.java +++ /dev/null @@ -1,82 +0,0 @@ -package io.pslab.communication.sensors; - - -import android.util.Log; - -import io.pslab.communication.peripherals.I2C; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; - -/** - * Created by akarshan on 4/17/17. - */ - -public class MLX90614 { - private String TAG = "MLX90614"; - private int ADDRESS = 0x5A; - - public int NUMPLOTS = 1; - public String[] PLOTNAMES = {"Temp"}; - public String name = "PIR temperature"; - - private I2C i2c; - private int source, OBJADDR = 0x07, AMBADDR = 0x06; - - public MLX90614(I2C i2c) throws IOException { - this.i2c = i2c; - source = OBJADDR; - String name = "Passive IR temperature sensor"; - try { - Log.d(TAG, "switching baud to 100k"); - i2c.config((int) 100e3); - } catch (Exception e) { - Log.d(TAG, "failed to change baud rate"); - } - ArrayList readReg = new ArrayList<>(); - for (int i = 0; i < 0x20; i++) - readReg.add(i); - ArrayList selectSource = new ArrayList<>(Arrays.asList("object temperature", "ambient temperature")); - } - - public void selectSource(String source) { - if (source.equals("object temperature")) - this.source = OBJADDR; - else if (source.equals("ambient temperature")) - this.source = AMBADDR; - } - - public void readReg(int address) throws IOException { - ArrayList x = getVals(address, 2); - Log.v(TAG, Integer.toHexString(address) + " " + Integer.toHexString(x.get(0) | (x.get(1) << 8))); - } - - private ArrayList getVals(int addr, int bytes) throws IOException { - ArrayList vals = i2c.readBulk(ADDRESS, addr, bytes); - return vals; - } - - public Double getRaw() throws IOException { - ArrayList vals = getVals(source, 3); - if (vals.size() == 3) - return ((((vals.get(1) & 0x007f) << 8) + vals.get(0)) * 0.02) - 0.01 - 273.15; - else - return null; - } - - public Double getObjectTemperature() throws IOException { - source = OBJADDR; - Double val = getRaw(); - return val; - - } - - public Double getAmbientTemperature() throws IOException { - source = AMBADDR; - Double val = getRaw(); - return val; - - } - -} diff --git a/app/src/main/java/io/pslab/communication/sensors/MPU6050.java b/app/src/main/java/io/pslab/communication/sensors/MPU6050.java deleted file mode 100644 index ed286632e..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/MPU6050.java +++ /dev/null @@ -1,133 +0,0 @@ -package io.pslab.communication.sensors; - -import org.apache.commons.math3.stat.StatUtils; -import org.apache.commons.math3.util.FastMath; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; - -/** - * Created by akarshan on 4/21/17. - *

- * ScienceLab instance of I2C need to be passed to the MPU6050 constructor. - *

- */ - -public class MPU6050 { - private int GYRO_CONFIG = 0x1B; - private int ACCEL_CONFIG = 0x1C; - private double[] GYRO_SCALING = {131, 65.5, 32.8, 16.4}; - private double[] ACCEL_SCALING = {16384, 8192, 4096, 2048}; - private int AR = 3; - private int GR = 3; - private int NUMPLOTS = 7; - public String[] PLOTNAMES = {"Ax", "Ay", "Az,'Temp", "Gx", "Gy", "Gz"}; - private int ADDRESS = 0x68; - private String name = "Accel/gyro"; - private ArrayList K = new ArrayList<>(); //K is the list of KalmanFilter object - private I2C i2c; - private ArrayList setGyroRange = new ArrayList<>(Arrays.asList(250, 500, 1000, 2000)); - private ArrayList setAccelRange = new ArrayList<>(Arrays.asList(2, 4, 8, 16)); - private ArrayList kalmanFilter = new ArrayList<>(Arrays.asList(0.01, 0.1, 1.0, 10.0, 100.0, 1000.0, 10000.0, 0.0)); - - public MPU6050(I2C i2c, ScienceLab scienceLab) throws IOException { - this.i2c = i2c; - if (scienceLab.isConnected()) { - setGyroRange(2000); - setAccelerationRange(16); - powerUp(); - } - } - - public void kalmanFilter(Double opt) throws IOException, NullPointerException { - ArrayList noise = new ArrayList<>(); - double[] innerNoiseArray = new double[NUMPLOTS]; - ArrayList vals; - double standardDeviation; - if (opt == null) { //Replaced "OFF" with null. - K = null; - } - for (int a = 0; a < 500; a++) { - vals = getRaw(); - for (int b = 0; b < NUMPLOTS; b++) { - innerNoiseArray[b] = vals.get(b); - noise.set(b, innerNoiseArray); - } - } - - for (int a = 0; a < NUMPLOTS; a++) { - standardDeviation = FastMath.sqrt(StatUtils.variance(noise.get(a))); //Apachae Commons Maths used to calculate standard deviation - K.set(a, new KalmanFilter(1. / opt, Math.pow(standardDeviation, 2))); - } - - } - - private ArrayList getVals(int addr, int bytesToRead) throws IOException { - return i2c.readBulk(ADDRESS, addr, bytesToRead); - } - - private void powerUp() throws IOException { - i2c.writeBulk(ADDRESS, new int[]{0x6B, 0}); - } - - public void setGyroRange(int rs) throws IOException { - GR = setGyroRange.indexOf(rs); - i2c.writeBulk(ADDRESS, new int[]{GYRO_CONFIG, GR << 3}); - } - - public void setAccelerationRange(int rs) throws IOException { - AR = setAccelRange.indexOf(rs); - i2c.writeBulk(ADDRESS, new int[]{ACCEL_CONFIG, AR << 3}); - } - - public ArrayList getRaw() throws IOException, NullPointerException { - ArrayList vals = getVals(0x3B, 14); - ArrayList raw = new ArrayList<>(); - if (vals.size() == 14) { - int a; - for (a = 0; a < 3; a++) - raw.add(a, 1. * (vals.get(a * 2) << 8 | vals.get(a * 2 + 1)) / ACCEL_SCALING[AR]); - raw.add(a, 1. * (vals.get(6) << 8 | vals.get(7)) / 340. + 36.53); - for (a = 4; a < 7; a++) - raw.add(a, (vals.get(a * 2) << 8 | vals.get(a * 2 + 1)) / GYRO_SCALING[GR]); - if (K.isEmpty()) - return raw; - else { - for (int b = 0; b < NUMPLOTS; b++) { - K.get(b).inputLatestNoisyMeasurement(raw.get(b)); - raw.set(b, K.get(b).getLatestEstimatedMeasurement()); - } - return raw; - } - } - return null; - } - - public double[] getAcceleration() throws IOException { - ArrayList vals = getVals(0x3B, 6); - int ax = vals.get(0) << 8 | vals.get(1); - int ay = vals.get(2) << 8 | vals.get(3); - int az = vals.get(4) << 8 | vals.get(5); - return new double[]{ax / 65535., ay / 65535., az / 65535.}; - - } - - public double getTemperature() throws IOException { - ArrayList vals = getVals(0x41, 6); - int t = vals.get(0) << 8 | vals.get(1); - return t / 65535.; - } - - public double[] getGyroscope() throws IOException { - ArrayList vals = getVals(0x43, 6); - int ax = vals.get(0) << 8 | vals.get(1); - int ay = vals.get(2) << 8 | vals.get(3); - int az = vals.get(4) << 8 | vals.get(5); - return new double[]{ax / 65535., ay / 65535., az / 65535.}; - - } - -} diff --git a/app/src/main/java/io/pslab/communication/sensors/MPU925x.java b/app/src/main/java/io/pslab/communication/sensors/MPU925x.java deleted file mode 100644 index f26bd6ea9..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/MPU925x.java +++ /dev/null @@ -1,194 +0,0 @@ -package io.pslab.communication.sensors; - -import org.apache.commons.math3.stat.StatUtils; -import org.apache.commons.math3.util.FastMath; -import io.pslab.communication.peripherals.I2C; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; - -/** - * Created by akarshan on 5/7/17. - *

- * ScienceLab instance of i2c is needed to be passed to MPU95x constructor. - *

- */ - - -public class MPU925x { - private static final String TAG = "MPU925x"; - private int INT_PIN_CFG = 0x37; - private int GYRO_CONFIG = 0x1B; - private int ACCEL_CONFIG = 0x1C; - private double[] GYRO_SCALING = new double[]{131, 65.5, 32.8, 16.4}; - private int[] ACCEL_SCALING = new int[]{16384, 8192, 4096, 2048}; - private int AR = 3; - private int GR = 3; - private int NUMPLOTS = 7; - public String[] PLOTNAMES = new String[]{"Ax", "Ay", "Az", "Temp", "Gx", "Gy", "Gz"}; - private int ADDRESS = 0x68; - private int AK8963_ADDRESS = 0x0C; - private int AK8963_CNTL = 0x0A; - public String name = "Accel/gyro"; - - private I2C i2c; - private ArrayList kalman = new ArrayList<>(); - private ArrayList gyroRange = new ArrayList<>(Arrays.asList(250, 500, 1000, 2000)); - private ArrayList accelRange = new ArrayList<>(Arrays.asList(2, 4, 8, 16)); - private double[] kalmanFilter = new double[]{.01, .1, 1, 10, 100, 1000, 10000, 0}; //Replaced "OFF" with 0. - - public MPU925x(I2C i2c) throws IOException { - this.i2c = i2c; - setGyroRange(2000); - setAccelRange(16); - powerUp(); - kalman = null; - } - - public void KalmanFilter(Double opt) throws IOException, NullPointerException { - ArrayList noise = new ArrayList<>(); - double[] innerNoiseArray = new double[NUMPLOTS]; - ArrayList vals; - double standardDeviation; - if (opt == 0) { //Replaced "OFF" with 0. - kalman = null; - } - for (int a = 0; a < 500; a++) { - vals = getRaw(); - for (int b = 0; b < NUMPLOTS; b++) { - innerNoiseArray[b] = vals.get(b); - noise.set(b, innerNoiseArray); - } - } - for (int a = 0; a < NUMPLOTS; a++) { - standardDeviation = FastMath.sqrt(StatUtils.variance(noise.get(a))); - kalman.set(a, new KalmanFilter(1. / opt, Math.pow(standardDeviation, 2))); - } - } - - private ArrayList getVals(int addr, int bytestoread) throws IOException { - return i2c.readBulk(ADDRESS, addr, bytestoread); - } - - private void powerUp() throws IOException { - i2c.writeBulk(ADDRESS, new int[]{0x6B, 0}); - } - - public void setGyroRange(int rs) throws IOException { - GR = gyroRange.indexOf(rs); - i2c.writeBulk(ADDRESS, new int[]{GYRO_CONFIG, GR << 3}); - } - - public void setAccelRange(int rs) throws IOException { - AR = accelRange.indexOf(rs); - i2c.writeBulk(ADDRESS, new int[]{ACCEL_CONFIG, AR << 3}); - } - - public ArrayList getRaw() throws IOException, NullPointerException { - ArrayList vals = getVals(0x3B, 14); - ArrayList raw = new ArrayList<>(); - if (vals.size() == 14) { - for (int a = 0; a < 3; a++) - raw.set(a, 1. * (vals.get(a * 2) << 8 | vals.get(a * 2 + 1)) / ACCEL_SCALING[AR]); - for (int a = 4; a < 7; a++) - raw.set(a, (vals.get(a * 2) << 8 | vals.get(a * 2 + 1)) / GYRO_SCALING[GR]); - raw.set(3, 1. * (vals.get(6) << 8 | vals.get(7)) / 340. + 36.53); - if (kalman.isEmpty()) - return raw; - else { - for (int b = 0; b < NUMPLOTS; b++) { - kalman.get(b).inputLatestNoisyMeasurement(raw.get(b)); - raw.set(b, kalman.get(b).getLatestEstimatedMeasurement()); - } - return raw; - } - } - return null; - } - - public double[] getAcceleration() throws IOException { - //Return a list of 3 values for acceleration vector - ArrayList vals = getVals(0x3B, 6); - int ax = vals.get(0) << 8 | vals.get(1); - int ay = vals.get(2) << 8 | vals.get(3); - int az = vals.get(4) << 8 | vals.get(5); - return new double[]{ax / 65535., ay / 65535., az / 65535.}; - } - - public double getTemperature() throws IOException { - //Return temperature - ArrayList vals = getVals(0x41, 6); - int t = vals.get(0) << 8 | vals.get(1); - return t / 65535.; - } - - public double[] getGyroscope() throws IOException { - //Return a list of 3 values for angular velocity vector - ArrayList vals = getVals(0x43, 6); - int ax = vals.get(0) << 8 | vals.get(1); - int ay = vals.get(2) << 8 | vals.get(3); - int az = vals.get(4) << 8 | vals.get(5); - return new double[]{ax / 65535., ay / 65535., az / 65535.}; - - } - - public double[] getMagneticField() throws IOException { - //Return a list of 3 values for magnetic field vector - ArrayList vals = i2c.readBulk(AK8963_ADDRESS, 0X03, 7); - int ax = vals.get(0) << 8 | vals.get(1); - int ay = vals.get(2) << 8 | vals.get(3); - int az = vals.get(4) << 8 | vals.get(5); - if ((vals.get(6) & 0x08) != 0) { - return new double[]{ax / 65535., ay / 65535., az / 65535.}; - } else - return null; - } - - public String whoAmI() throws IOException { - /* - Returns the ID . - It is 71 for MPU9250 . - */ - int v = i2c.readBulk(ADDRESS, 0x75, 1).get(0); - if (v != 0x71 && v != 0x73) - return "Error " + Integer.toHexString(v); - if (v == 0x73) - return "MPU9255 " + Integer.toHexString(v); - else if (v == 0x71) - return "MPU9250 " + Integer.toHexString(v); - else - return null; - } - - public String whoAmIAK8963() throws IOException { - /* - Returns the ID fo magnetometer AK8963 if found. - It should be 0x48. - */ - initMagnetometer(); - int v = i2c.readBulk(AK8963_ADDRESS, 0, 1).get(0); - if (v == 0x48) - return "AK8963 " + Integer.toHexString(v); - else - return "AK8963 not found. returned " + Integer.toHexString(v); - } - - private void initMagnetometer() throws IOException { - /* - For MPU925x with integrated magnetometer. - It's called a 10 DoF sensor, but technically speaking , - the 3-axis Accel , 3-Axis Gyro, temperature sensor are integrated in one IC, - and the 3-axis magnetometer is implemented in a - separate IC which can be accessed via an I2C passthrough. - Therefore , in order to detect the magnetometer via an I2C scan, - the passthrough must first be enabled on IC#1 (Accel,gyro,temp) - */ - i2c.writeBulk(ADDRESS, new int[]{INT_PIN_CFG, 0x22}); //I2C passthrough - i2c.writeBulk(AK8963_ADDRESS, new int[]{AK8963_CNTL, 0}); //power down mag - i2c.writeBulk(AK8963_ADDRESS, new int[]{AK8963_CNTL, (1 << 4) | 6}); //mode (0 = 14bits, 1 = 16bits) << 4 | (2 = 8Hz, 6 = 100Hz) - } - -} - - diff --git a/app/src/main/java/io/pslab/communication/sensors/SHT21.java b/app/src/main/java/io/pslab/communication/sensors/SHT21.java deleted file mode 100644 index bd768bb40..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/SHT21.java +++ /dev/null @@ -1,115 +0,0 @@ -package io.pslab.communication.sensors; - -import android.util.Log; - -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; - -/** - * Created by akarshan on 4/16/17. - */ - -public class SHT21 { - private String TAG = "SHT21"; - private int RESET = 0XFE; - private int TEMP_ADDRESS = 0xF3; - private int HUMIDITY_ADDRESS = 0xF5; - private int selected = 0xF3; - private int ADDRESS = 0x40; - - public int NUMPLOTS = 1; - public String[] PLOTNAMES = {"Data"}; - public String name = "Humidity/Temperature"; - - public ArrayList selectParameter = new ArrayList<>(Arrays.asList("temperature", "humidity")); - private I2C i2c; - - public SHT21(I2C i2c, ScienceLab scienceLab) throws IOException, InterruptedException { - this.i2c = i2c; - if (scienceLab.isConnected()) { - init(); - } - } - - private void init() throws IOException, InterruptedException { - i2c.writeBulk(ADDRESS, new int[]{RESET}); //soft reset - TimeUnit.MILLISECONDS.sleep(100); - } - - private ArrayList rawToTemp(ArrayList vals) { - double v; - ArrayList v1 = new ArrayList<>(); - if (vals.size() != 0) { - v = (vals.get(0) << 8) | (vals.get(1) & 0xFC); - v *= 175.72; - v /= (1 << 16); - v -= 46.85; - v1.add(v); - return v1; - } else return null; - } - - private ArrayList rawToRH(ArrayList vals) { - double v; - ArrayList v1 = new ArrayList<>(); - if (vals.size() != 0) { - v = (vals.get(0) << 8) | (vals.get(1) & 0xFC); - v *= 125.; - v /= (1 << 16); - v -= 6; - v1.add(v); - return v1; - } else return null; - } - - private static int calculateChecksum(ArrayList data, int numberOfBytes) { - - //CRC - int POLYNOMIAL = 0x131, byteCtr, crc = 0; - //calculates 8-Bit checksum with given polynomial - for (byteCtr = 0; byteCtr < numberOfBytes; byteCtr++) { - crc ^= data.get(byteCtr); - for (int bit = 8; bit > 0; bit--) { - if ((crc & 0X80) != 0) - crc = (crc << 1) ^ POLYNOMIAL; - else - crc = crc << 1; - } - } - return crc; - } - - public void selectParameter(String param) { - if (param.equals("temperature")) - selected = TEMP_ADDRESS; - else if (param.equals("humidity")) - selected = HUMIDITY_ADDRESS; - } - - public ArrayList getRaw() throws IOException, InterruptedException { - ArrayList vals; - i2c.writeBulk(ADDRESS, new int[]{selected}); - if (selected == TEMP_ADDRESS) - TimeUnit.MILLISECONDS.sleep(100); - else if (selected == HUMIDITY_ADDRESS) - TimeUnit.MILLISECONDS.sleep(50); - vals = i2c.simpleRead(ADDRESS, 3); - if (vals.size() != 0) { - if (calculateChecksum(vals, 2) != vals.get(2)) - Log.v(TAG, vals.toString()); - return null; - } - if (selected == TEMP_ADDRESS) - return rawToTemp(vals); - else if (selected == HUMIDITY_ADDRESS) - return rawToRH(vals); - else - return null; - } - -} diff --git a/app/src/main/java/io/pslab/communication/sensors/SSD1306.java b/app/src/main/java/io/pslab/communication/sensors/SSD1306.java deleted file mode 100644 index fc2622da9..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/SSD1306.java +++ /dev/null @@ -1,463 +0,0 @@ -package io.pslab.communication.sensors; - -import io.pslab.communication.peripherals.I2C; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.concurrent.TimeUnit; - -import static java.lang.Math.abs; - -/** - * Created by akarshan on 4/20/17. - *

- * // functions that are needed to be handled in ScienceLab.java - * load("logo"); - * scroll("topright"); - * TimeUnit.MILLISECONDS.sleep(2800); - * scroll("stop"); - *

- * ScienceLab instance of i2c needs to be passed to SSD1306 class constructor - */ - -public class SSD1306 { - private int ADDRESS = 0x3C; - private ArrayList load = new ArrayList<>(Collections.singletonList("logo")); - private ArrayList scroll = new ArrayList<>(Arrays.asList("left", "right, ", "topright", "topleft", "bottomleft", "bottomright", "stop")); - public int NUMPLOTS = 0; - public String[] PLOTNAMES = {""}; - public String name = "OLED Display"; - - private int width = 128; - private int height = 64; - - private int rotation = 0; - private int cursorY = 0; - private int cursorX = 0; - private int textSize = 1; - private int textColor = 1; - private int textbgColor = 0; - private boolean wrap = true; - - private int SSD1306_128_64 = 1; - private int SSD1306_128_32 = 2; - private int SSD1306_96_16 = 3; - - private int DISPLAY_TYPE = SSD1306_96_16; - - private int SSD1306_LCDWIDTH = 128; - private int SSD1306_LCDHEIGHT = 64; - - private int SSD1306_SETCONTRAST = 0x81; - private int SSD1306_DISPLAYALLON_RESUME = 0xA4; - private int SSD1306_DISPLAYALLON = 0xA5; - private int SSD1306_NORMALDISPLAY = 0xA6; - private int SSD1306_INVERTDISPLAY = 0xA7; - private int SSD1306_DISPLAYOFF = 0xAE; - private int SSD1306_DISPLAYON = 0xAF; - - private int SSD1306_SETDISPLAYOFFSET = 0xD3; - private int SSD1306_SETCOMPINS = 0xDA; - - private int SSD1306_SETVCOMDETECT = 0xDB; - - private int SSD1306_SETDISPLAYCLOCKDIV = 0xD5; - private int SSD1306_SETPRECHARGE = 0xD9; - - private int SSD1306_SETMULTIPLEX = 0xA8; - - private int SSD1306_SETLOWCOLUMN = 0x00; - private int SSD1306_SETHIGHCOLUMN = 0x10; - - private int SSD1306_SETSTARTLINE = 0x40; - - private int SSD1306_MEMORYMODE = 0x20; - - private int SSD1306_COMSCANINC = 0xC0; - private int SSD1306_COMSCANDEC = 0xC8; - - private int SSD1306_SEGREMAP = 0xA0; - - private int SSD1306_CHARGEPUMP = 0x8D; - - private int SSD1306_EXTERNALVCC = 0x1; - private int SSD1306_SWITCHCAPVCC = 0x2; - - private int[] logobuff = {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 127, 63, 63, 159, 159, 223, 223, 207, 207, 207, 239, 239, 47, 47, 39, 39, 7, 7, 67, 67, 83, 131, 135, 7, 7, 15, 15, 31, 191, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 31, 15, 199, 99, 17, 25, 12, 4, 2, 3, 7, 63, 255, 255, 255, 255, 255, 255, 255, 255, 254, 252, 240, 224, 224, 224, 192, 192, 128, 128, 128, 128, 129, 128, 0, 0, 0, 0, 0, 3, 3, 7, 31, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 15, 3, 192, 120, 134, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 252, 252, 249, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 143, 0, 0, 124, 199, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 240, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 240, 128, 0, 7, 56, 96, 128, 0, 0, 0, 0, 0, 0, 0, 12, 63, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 7, 227, 243, 249, 249, 249, 249, 249, 249, 243, 255, 255, 199, 131, 49, 57, 57, 57, 121, 115, 255, 255, 255, 255, 15, 15, 159, 207, 207, 207, 143, 31, 63, 255, 255, 159, 207, 207, 207, 143, 31, 63, 255, 255, 255, 15, 15, 159, 207, 207, 207, 255, 255, 0, 0, 255, 127, 63, 159, 207, 239, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 248, 240, 224, 129, 2, 4, 8, 16, 32, 96, 64, 128, 128, 135, 30, 115, 207, 159, 255, 255, 255, 255, 127, 63, 31, 31, 31, 31, 31, 31, 31, 7, 7, 7, 127, 127, 127, 127, 127, 127, 255, 255, 255, 255, 252, 240, 227, 231, 207, 207, 207, 207, 207, 207, 231, 255, 255, 231, 207, 207, 207, 207, 207, 198, 224, 240, 255, 255, 255, 0, 0, 231, 207, 207, 207, 199, 224, 240, 255, 225, 193, 204, 204, 204, 228, 192, 192, 255, 255, 255, 192, 192, 255, 255, 255, 255, 255, 255, 192, 192, 252, 248, 243, 231, 207, 223, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 252, 248, 248, 240, 240, 224, 225, 225, 193, 193, 195, 195, 195, 195, 195, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 62, 62, 62, 62, 62, 255, 243, 3, 3, 51, 51, 51, 19, 135, 239, 255, 255, 63, 63, 159, 159, 159, 159, 63, 127, 255, 255, 255, 63, 31, 159, 159, 159, 31, 252, 252, 255, 63, 63, 159, 159, 159, 159, 63, 127, 255, 255, 255, 223, 159, 159, 159, 31, 127, 255, 255, 255, 255, 223, 31, 31, 191, 159, 159, 159, 255, 255, 127, 63, 159, 159, 159, 159, 31, 31, 255, 255, 247, 3, 7, 159, 159, 159, 31, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 252, 252, 252, 252, 252, 252, 252, 252, 224, 224, 224, 255, 255, 255, 255, 255, 255, 255, 243, 240, 240, 247, 255, 254, 252, 248, 243, 255, 255, 248, 248, 242, 242, 242, 242, 242, 250, 255, 255, 255, 241, 242, 242, 242, 242, 248, 253, 255, 255, 248, 248, 242, 242, 242, 242, 242, 250, 255, 255, 249, 240, 242, 242, 242, 240, 240, 255, 255, 255, 255, 243, 240, 240, 243, 243, 255, 255, 255, 255, 252, 248, 243, 243, 243, 243, 243, 255, 255, 255, 247, 240, 240, 247, 255, 247, 240, 240, 247, 255}; - private int[] font = {0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x5B, 0x4F, 0x5B, 0x3E, 0x3E, 0x6B, 0x4F, 0x6B, 0x3E, - 0x1C, 0x3E, 0x7C, 0x3E, 0x1C, 0x18, 0x3C, 0x7E, 0x3C, 0x18, 0x1C, 0x57, 0x7D, 0x57, 0x1C, - 0x1C, 0x5E, 0x7F, 0x5E, 0x1C, 0x00, 0x18, 0x3C, 0x18, 0x00, 0xFF, 0xE7, 0xC3, 0xE7, 0xFF, - 0x00, 0x18, 0x24, 0x18, 0x00, 0xFF, 0xE7, 0xDB, 0xE7, 0xFF, 0x30, 0x48, 0x3A, 0x06, 0x0E, - 0x26, 0x29, 0x79, 0x29, 0x26, 0x40, 0x7F, 0x05, 0x05, 0x07, 0x40, 0x7F, 0x05, 0x25, 0x3F, - 0x5A, 0x3C, 0xE7, 0x3C, 0x5A, 0x7F, 0x3E, 0x1C, 0x1C, 0x08, 0x08, 0x1C, 0x1C, 0x3E, 0x7F, - 0x14, 0x22, 0x7F, 0x22, 0x14, 0x5F, 0x5F, 0x00, 0x5F, 0x5F, 0x06, 0x09, 0x7F, 0x01, 0x7F, - 0x00, 0x66, 0x89, 0x95, 0x6A, 0x60, 0x60, 0x60, 0x60, 0x60, 0x94, 0xA2, 0xFF, 0xA2, 0x94, - 0x08, 0x04, 0x7E, 0x04, 0x08, 0x10, 0x20, 0x7E, 0x20, 0x10, 0x08, 0x08, 0x2A, 0x1C, 0x08, - 0x08, 0x1C, 0x2A, 0x08, 0x08, 0x1E, 0x10, 0x10, 0x10, 0x10, 0x0C, 0x1E, 0x0C, 0x1E, 0x0C, - 0x30, 0x38, 0x3E, 0x38, 0x30, 0x06, 0x0E, 0x3E, 0x0E, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x5F, 0x00, 0x00, 0x00, 0x07, 0x00, 0x07, 0x00, 0x14, 0x7F, 0x14, 0x7F, 0x14, - 0x24, 0x2A, 0x7F, 0x2A, 0x12, 0x23, 0x13, 0x08, 0x64, 0x62, 0x36, 0x49, 0x56, 0x20, 0x50, - 0x00, 0x08, 0x07, 0x03, 0x00, 0x00, 0x1C, 0x22, 0x41, 0x00, 0x00, 0x41, 0x22, 0x1C, 0x00, - 0x2A, 0x1C, 0x7F, 0x1C, 0x2A, 0x08, 0x08, 0x3E, 0x08, 0x08, 0x00, 0x80, 0x70, 0x30, 0x00, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x60, 0x60, 0x00, 0x20, 0x10, 0x08, 0x04, 0x02, - 0x3E, 0x51, 0x49, 0x45, 0x3E, 0x00, 0x42, 0x7F, 0x40, 0x00, 0x72, 0x49, 0x49, 0x49, 0x46, - 0x21, 0x41, 0x49, 0x4D, 0x33, 0x18, 0x14, 0x12, 0x7F, 0x10, 0x27, 0x45, 0x45, 0x45, 0x39, - 0x3C, 0x4A, 0x49, 0x49, 0x31, 0x41, 0x21, 0x11, 0x09, 0x07, 0x36, 0x49, 0x49, 0x49, 0x36, - 0x46, 0x49, 0x49, 0x29, 0x1E, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x40, 0x34, 0x00, 0x00, - 0x00, 0x08, 0x14, 0x22, 0x41, 0x14, 0x14, 0x14, 0x14, 0x14, 0x00, 0x41, 0x22, 0x14, 0x08, - 0x02, 0x01, 0x59, 0x09, 0x06, 0x3E, 0x41, 0x5D, 0x59, 0x4E, 0x7C, 0x12, 0x11, 0x12, 0x7C, - 0x7F, 0x49, 0x49, 0x49, 0x36, 0x3E, 0x41, 0x41, 0x41, 0x22, 0x7F, 0x41, 0x41, 0x41, 0x3E, - 0x7F, 0x49, 0x49, 0x49, 0x41, 0x7F, 0x09, 0x09, 0x09, 0x01, 0x3E, 0x41, 0x41, 0x51, 0x73, - 0x7F, 0x08, 0x08, 0x08, 0x7F, 0x00, 0x41, 0x7F, 0x41, 0x00, 0x20, 0x40, 0x41, 0x3F, 0x01, - 0x7F, 0x08, 0x14, 0x22, 0x41, 0x7F, 0x40, 0x40, 0x40, 0x40, 0x7F, 0x02, 0x1C, 0x02, 0x7F, - 0x7F, 0x04, 0x08, 0x10, 0x7F, 0x3E, 0x41, 0x41, 0x41, 0x3E, 0x7F, 0x09, 0x09, 0x09, 0x06, - 0x3E, 0x41, 0x51, 0x21, 0x5E, 0x7F, 0x09, 0x19, 0x29, 0x46, 0x26, 0x49, 0x49, 0x49, 0x32, - 0x03, 0x01, 0x7F, 0x01, 0x03, 0x3F, 0x40, 0x40, 0x40, 0x3F, 0x1F, 0x20, 0x40, 0x20, 0x1F, - 0x3F, 0x40, 0x38, 0x40, 0x3F, 0x63, 0x14, 0x08, 0x14, 0x63, 0x03, 0x04, 0x78, 0x04, 0x03, - 0x61, 0x59, 0x49, 0x4D, 0x43, 0x00, 0x7F, 0x41, 0x41, 0x41, 0x02, 0x04, 0x08, 0x10, 0x20, - 0x00, 0x41, 0x41, 0x41, 0x7F, 0x04, 0x02, 0x01, 0x02, 0x04, 0x40, 0x40, 0x40, 0x40, 0x40, - 0x00, 0x03, 0x07, 0x08, 0x00, 0x20, 0x54, 0x54, 0x78, 0x40, 0x7F, 0x28, 0x44, 0x44, 0x38, - 0x38, 0x44, 0x44, 0x44, 0x28, 0x38, 0x44, 0x44, 0x28, 0x7F, 0x38, 0x54, 0x54, 0x54, 0x18, - 0x00, 0x08, 0x7E, 0x09, 0x02, 0x18, 0xA4, 0xA4, 0x9C, 0x78, 0x7F, 0x08, 0x04, 0x04, 0x78, - 0x00, 0x44, 0x7D, 0x40, 0x00, 0x20, 0x40, 0x40, 0x3D, 0x00, 0x7F, 0x10, 0x28, 0x44, 0x00, - 0x00, 0x41, 0x7F, 0x40, 0x00, 0x7C, 0x04, 0x78, 0x04, 0x78, 0x7C, 0x08, 0x04, 0x04, 0x78, - 0x38, 0x44, 0x44, 0x44, 0x38, 0xFC, 0x18, 0x24, 0x24, 0x18, 0x18, 0x24, 0x24, 0x18, 0xFC, - 0x7C, 0x08, 0x04, 0x04, 0x08, 0x48, 0x54, 0x54, 0x54, 0x24, 0x04, 0x04, 0x3F, 0x44, 0x24, - 0x3C, 0x40, 0x40, 0x20, 0x7C, 0x1C, 0x20, 0x40, 0x20, 0x1C, 0x3C, 0x40, 0x30, 0x40, 0x3C, - 0x44, 0x28, 0x10, 0x28, 0x44, 0x4C, 0x90, 0x90, 0x90, 0x7C, 0x44, 0x64, 0x54, 0x4C, 0x44, - 0x00, 0x08, 0x36, 0x41, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x41, 0x36, 0x08, 0x00, - 0x02, 0x01, 0x02, 0x04, 0x02, 0x3C, 0x26, 0x23, 0x26, 0x3C, 0x1E, 0xA1, 0xA1, 0x61, 0x12, - 0x3A, 0x40, 0x40, 0x20, 0x7A, 0x38, 0x54, 0x54, 0x55, 0x59, 0x21, 0x55, 0x55, 0x79, 0x41, - 0x21, 0x54, 0x54, 0x78, 0x41, 0x21, 0x55, 0x54, 0x78, 0x40, 0x20, 0x54, 0x55, 0x79, 0x40, - 0x0C, 0x1E, 0x52, 0x72, 0x12, 0x39, 0x55, 0x55, 0x55, 0x59, 0x39, 0x54, 0x54, 0x54, 0x59, - 0x39, 0x55, 0x54, 0x54, 0x58, 0x00, 0x00, 0x45, 0x7C, 0x41, 0x00, 0x02, 0x45, 0x7D, 0x42, - 0x00, 0x01, 0x45, 0x7C, 0x40, 0xF0, 0x29, 0x24, 0x29, 0xF0, 0xF0, 0x28, 0x25, 0x28, 0xF0, - 0x7C, 0x54, 0x55, 0x45, 0x00, 0x20, 0x54, 0x54, 0x7C, 0x54, 0x7C, 0x0A, 0x09, 0x7F, 0x49, - 0x32, 0x49, 0x49, 0x49, 0x32, 0x32, 0x48, 0x48, 0x48, 0x32, 0x32, 0x4A, 0x48, 0x48, 0x30, - 0x3A, 0x41, 0x41, 0x21, 0x7A, 0x3A, 0x42, 0x40, 0x20, 0x78, 0x00, 0x9D, 0xA0, 0xA0, 0x7D, - 0x39, 0x44, 0x44, 0x44, 0x39, 0x3D, 0x40, 0x40, 0x40, 0x3D, 0x3C, 0x24, 0xFF, 0x24, 0x24, - 0x48, 0x7E, 0x49, 0x43, 0x66, 0x2B, 0x2F, 0xFC, 0x2F, 0x2B, 0xFF, 0x09, 0x29, 0xF6, 0x20, - 0xC0, 0x88, 0x7E, 0x09, 0x03, 0x20, 0x54, 0x54, 0x79, 0x41, 0x00, 0x00, 0x44, 0x7D, 0x41, - 0x30, 0x48, 0x48, 0x4A, 0x32, 0x38, 0x40, 0x40, 0x22, 0x7A, 0x00, 0x7A, 0x0A, 0x0A, 0x72, - 0x7D, 0x0D, 0x19, 0x31, 0x7D, 0x26, 0x29, 0x29, 0x2F, 0x28, 0x26, 0x29, 0x29, 0x29, 0x26, - 0x30, 0x48, 0x4D, 0x40, 0x20, 0x38, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x38, - 0x2F, 0x10, 0xC8, 0xAC, 0xBA, 0x2F, 0x10, 0x28, 0x34, 0xFA, 0x00, 0x00, 0x7B, 0x00, 0x00, - 0x08, 0x14, 0x2A, 0x14, 0x22, 0x22, 0x14, 0x2A, 0x14, 0x08, 0xAA, 0x00, 0x55, 0x00, 0xAA, - 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x10, 0x10, 0x10, 0xFF, 0x00, - 0x14, 0x14, 0x14, 0xFF, 0x00, 0x10, 0x10, 0xFF, 0x00, 0xFF, 0x10, 0x10, 0xF0, 0x10, 0xF0, - 0x14, 0x14, 0x14, 0xFC, 0x00, 0x14, 0x14, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF, - 0x14, 0x14, 0xF4, 0x04, 0xFC, 0x14, 0x14, 0x17, 0x10, 0x1F, 0x10, 0x10, 0x1F, 0x10, 0x1F, - 0x14, 0x14, 0x14, 0x1F, 0x00, 0x10, 0x10, 0x10, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x10, - 0x10, 0x10, 0x10, 0x1F, 0x10, 0x10, 0x10, 0x10, 0xF0, 0x10, 0x00, 0x00, 0x00, 0xFF, 0x10, - 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0xFF, 0x10, 0x00, 0x00, 0x00, 0xFF, 0x14, - 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x1F, 0x10, 0x17, 0x00, 0x00, 0xFC, 0x04, 0xF4, - 0x14, 0x14, 0x17, 0x10, 0x17, 0x14, 0x14, 0xF4, 0x04, 0xF4, 0x00, 0x00, 0xFF, 0x00, 0xF7, - 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0xF7, 0x00, 0xF7, 0x14, 0x14, 0x14, 0x17, 0x14, - 0x10, 0x10, 0x1F, 0x10, 0x1F, 0x14, 0x14, 0x14, 0xF4, 0x14, 0x10, 0x10, 0xF0, 0x10, 0xF0, - 0x00, 0x00, 0x1F, 0x10, 0x1F, 0x00, 0x00, 0x00, 0x1F, 0x14, 0x00, 0x00, 0x00, 0xFC, 0x14, - 0x00, 0x00, 0xF0, 0x10, 0xF0, 0x10, 0x10, 0xFF, 0x10, 0xFF, 0x14, 0x14, 0x14, 0xFF, 0x14, - 0x10, 0x10, 0x10, 0x1F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x10, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, - 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x38, 0x44, 0x44, 0x38, 0x44, 0x7C, 0x2A, 0x2A, 0x3E, 0x14, - 0x7E, 0x02, 0x02, 0x06, 0x06, 0x02, 0x7E, 0x02, 0x7E, 0x02, 0x63, 0x55, 0x49, 0x41, 0x63, - 0x38, 0x44, 0x44, 0x3C, 0x04, 0x40, 0x7E, 0x20, 0x1E, 0x20, 0x06, 0x02, 0x7E, 0x02, 0x02, - 0x99, 0xA5, 0xE7, 0xA5, 0x99, 0x1C, 0x2A, 0x49, 0x2A, 0x1C, 0x4C, 0x72, 0x01, 0x72, 0x4C, - 0x30, 0x4A, 0x4D, 0x4D, 0x30, 0x30, 0x48, 0x78, 0x48, 0x30, 0xBC, 0x62, 0x5A, 0x46, 0x3D, - 0x3E, 0x49, 0x49, 0x49, 0x00, 0x7E, 0x01, 0x01, 0x01, 0x7E, 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, - 0x44, 0x44, 0x5F, 0x44, 0x44, 0x40, 0x51, 0x4A, 0x44, 0x40, 0x40, 0x44, 0x4A, 0x51, 0x40, - 0x00, 0x00, 0xFF, 0x01, 0x03, 0xE0, 0x80, 0xFF, 0x00, 0x00, 0x08, 0x08, 0x6B, 0x6B, 0x08, - 0x36, 0x12, 0x36, 0x24, 0x36, 0x06, 0x0F, 0x09, 0x0F, 0x06, 0x00, 0x00, 0x18, 0x18, 0x00, - 0x00, 0x00, 0x10, 0x10, 0x00, 0x30, 0x40, 0xFF, 0x01, 0x01, 0x00, 0x1F, 0x01, 0x01, 0x1E, - 0x00, 0x19, 0x1D, 0x17, 0x12, 0x00, 0x3C, 0x3C, 0x3C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00}; //ascii fonts - - private int[] buff; - private I2C i2c; - - public SSD1306(I2C i2c) throws IOException, InterruptedException { - - this.i2c = i2c; - - buff = new int[1024]; - Arrays.fill(buff, 0); - SSD1306_command(SSD1306_DISPLAYOFF); //0xAE - SSD1306_command(SSD1306_SETDISPLAYCLOCKDIV); // 0xD5 - SSD1306_command(0x80); // the suggested ratio 0x80 - SSD1306_command(SSD1306_SETMULTIPLEX); // 0xA8 - SSD1306_command(0x3F); - SSD1306_command(SSD1306_SETDISPLAYOFFSET); // 0xD3 - SSD1306_command(0x0); // no offset - SSD1306_command(SSD1306_SETSTARTLINE | 0x0); // line //0 - SSD1306_command(SSD1306_CHARGEPUMP); // 0x8D - SSD1306_command(0x14); //vccstate = SSD1306_SWITCHCAPVCC; - SSD1306_command(SSD1306_MEMORYMODE); // 0x20 - SSD1306_command(0x00); // 0x0 act like ks0108 - SSD1306_command(SSD1306_SEGREMAP | 0x1); - SSD1306_command(SSD1306_COMSCANDEC); - SSD1306_command(SSD1306_SETCOMPINS); // 0xDA - SSD1306_command(0x12); - SSD1306_command(SSD1306_SETCONTRAST); // 0x81 - SSD1306_command(0xFF); // vccstate = SSD1306_SWITCHCAPVCC; - SSD1306_command(SSD1306_SETPRECHARGE); // 0xd9 - SSD1306_command(0xF1); // vccstate = SSD1306_SWITCHCAPVCC; - SSD1306_command(SSD1306_SETVCOMDETECT); // 0xDB - SSD1306_command(0x40); - SSD1306_command(SSD1306_DISPLAYALLON_RESUME); // 0xA4 - SSD1306_command(SSD1306_NORMALDISPLAY); // 0xA6 - SSD1306_command(SSD1306_DISPLAYON); //--turn on oled panel - - } - - public void load(String arg) throws IOException { - scroll("stop"); - if (arg.equals("logo")) { - clearDisplay(); - System.arraycopy(logobuff, 0, buff, 0, 1024); - displayOLED(); - } - } - - private void SSD1306_command(int cmd) throws IOException { - i2c.writeBulk(ADDRESS, new int[]{0x00, cmd}); - } - - public void SSD1306_data(int data) throws IOException { - i2c.writeBulk(ADDRESS, new int[]{0x40, data}); - } - - private void clearDisplay() { - setCursor(0, 0); - for (int a = 0; a < SSD1306_LCDWIDTH * SSD1306_LCDHEIGHT / 8; a++) - buff[a] = 0; - } - - private void displayOLED() throws IOException { - SSD1306_command(SSD1306_SETLOWCOLUMN | 0x00); - SSD1306_command(SSD1306_SETHIGHCOLUMN | 0x00); - SSD1306_command(SSD1306_SETSTARTLINE | 0x00); - int a = 0; - while (a < SSD1306_LCDWIDTH * SSD1306_LCDHEIGHT / 8) { - i2c.writeBulk(ADDRESS, merge(new int[]{0x40}, Arrays.copyOfRange(buff, a, a + 16))); - a += 16; - } - } - - private int[] merge(int[] arr1, int[] arr2) { - int[] mergedIntegerArray = new int[arr1.length + arr2.length]; - System.arraycopy(arr1, 0, mergedIntegerArray, 0, arr1.length); - System.arraycopy(arr2, 0, mergedIntegerArray, arr1.length, arr2.length); - return mergedIntegerArray; - } - - public void setContrast(int contrast) throws IOException { - SSD1306_command(SSD1306_SETCONTRAST); - SSD1306_command(contrast); - } - - private void drawPixel(int x, int y, int color) { - if (color == 1) - buff[(x + (y / 8) * SSD1306_LCDWIDTH)] |= (1 << (y % 8)); - else - buff[x + (y / 8) * SSD1306_LCDWIDTH] &= ~(1 << (y % 8)); - } - - public void drawCircle(int x0, int y0, int r, int color) { - int f = 1 - r; - int ddF_x = 1; - int ddF_y = -2 * r; - int x = 0; - int y = r; - drawPixel(x0, y0 + r, color); - drawPixel(x0, y0 - r, color); - drawPixel(x0 + r, y0, color); - drawPixel(x0 - r, y0, color); - while (x < y) { - if (f >= 0) { - y -= 1; - ddF_y += 2; - f += ddF_y; - } - x += 1; - ddF_x += 2; - f += ddF_x; - drawPixel(x0 + x, y0 + y, color); - drawPixel(x0 - x, y0 + y, color); - drawPixel(x0 + x, y0 - y, color); - drawPixel(x0 - x, y0 - y, color); - drawPixel(x0 + y, y0 + x, color); - drawPixel(x0 - y, y0 + x, color); - drawPixel(x0 + y, y0 - x, color); - drawPixel(x0 - y, y0 - x, color); - } - } - - private void drawLine(int x0, int y0, int x1, int y1, int color) { - boolean steep = abs(y1 - y0) > abs(x1 - x0); - int tmp, ystep, dx, dy, err; - if (steep) { - tmp = y0; - y0 = x0; - x0 = tmp; - tmp = y1; - y1 = x1; - x1 = tmp; - } - if (x0 > x1) { - tmp = x1; - x1 = x0; - x0 = tmp; - tmp = y1; - y1 = y0; - y0 = tmp; - } - dx = x1 - x0; - dy = abs(y1 - y0); - err = dx / 2; - - if (y0 < y1) - ystep = 1; - else - ystep = -1; - - while (x0 <= x1) { - if (steep) - drawPixel(y0, x0, color); - else - drawPixel(x0, y0, color); - err -= dy; - if (err < 0) { - y0 += ystep; - err += dx; - } - x0 += 1; - } - } - - public void drawRect(int x, int y, int w, int h, int color) { - drawFastHLine(x, y, w, color); - drawFastHLine(x, y + h - 1, w, color); - drawFastVLine(x, y, h, color); - drawFastVLine(x + w + 1, y, h, color); - } - - private void drawFastVLine(int x, int y, int h, int color) { - drawLine(x, y, x, y + h - 1, color); - } - - private void drawFastHLine(int x, int y, int w, int color) { - drawLine(x, y, x + w - 1, y, color); - } - - private void fillRect(int x, int y, int w, int h, int color) { - for (int i = x; i < x + w; i++) - drawFastVLine(i, y, h, color); - } - - public void writeString(String string) { - for (int i = 0; i < string.length(); i++) { - writeChar((int) string.charAt(i)); - } - } - - private void writeChar(int c) { - if (c == '\n') { - cursorY += textSize * 8; - cursorX = 0; - } else if (c == '\r') { - } else { - drawChar(cursorX, cursorY, c, textColor, textbgColor, textSize); - cursorX += textSize * 6; - if (wrap & (cursorX > (width - textSize * 6))) { - cursorY += textSize * 8; - cursorX = 0; - } - } - } - - private void drawChar(int x, int y, int c, int color, int bg, int size) { - int line; - if ((x >= width) | (y >= height) | ((x + 5 * size - 1) < 0) | ((y + 8 * size - 1) < 0)) - return; - for (int i = 0; i < 6; i++) { - if (i == 5) - line = 0x0; - else - line = font[c * 5 + i]; - for (int j = 0; j < 8; j++) { - if ((line & 0x1) > 0) { - if (size == 1) - drawPixel(x + i, y + j, color); - else - fillRect(x + (i * size), y + (j * size), size, size, color); - } else if (bg != color) { - if (size == 1) - drawPixel(x + i, y + j, bg); - else - fillRect(x + i * size, y + j * size, size, size, bg); - } - line >>= 1; - } - } - } - - private void setCursor(int x, int y) { - cursorX = x; - cursorY = y; - } - - public void setTextSize(int size) { - if (size > 0) - textSize = size; - else - textSize = 1; - } - - public void setTextColor(int color, int backgroundcolor) { - textColor = color; - textbgColor = backgroundcolor; - } - - public void setTextWrap(boolean w) { - wrap = w; - } - - public void scroll(String arg) throws IOException { - if (arg.equals("left")) - SSD1306_command(0x27); //up-0x29 ,2A left-0x27 right0x26 - if (arg.equals("right")) - SSD1306_command(0x26); //up-0x29 ,2A left-0x27 right0x26 - if (arg.equals("topright") | arg.equals("bottomright")) - SSD1306_command(0x29); //up-0x29 ,2A left-0x27 right0x26 - if (arg.equals("topleft") | arg.equals("bottomleft")) - SSD1306_command(0x2A); //up-0x29 ,2A left-0x27 right0x26 - if (new ArrayList(Arrays.asList("left", "right", "topright", "topleft", "bottomleft", "bottomright")).contains(arg)) { - SSD1306_command(0x00); //dummy - SSD1306_command(0x0); //start page - SSD1306_command(0x7); //time interval 0b100 - 3 frames - SSD1306_command(0xf); //end page - if (arg.equals("topleft") | arg.equals("topright")) - SSD1306_command(0x02); //dummy 00 . xx for horizontal scroll (speed) - else if (arg.equals("bottomleft") | arg.equals("bottomright")) - SSD1306_command(0xfe); //dummy 00 . xx for horizontal scroll (speed) - else if (arg.equals("left") | arg.equals("right")) { - SSD1306_command(0x02); //dummy 00 . xx for horizontal scroll (speed) - SSD1306_command(0xff); - } - } - SSD1306_command(0x2F); - if (arg.equals("stop")) - SSD1306_command(0x2E); - } - - public void pulseIt() throws InterruptedException, IOException { - for (int a = 0; a < 2; a++) { - SSD1306_command(0xD6); - SSD1306_command(0x01); - TimeUnit.MILLISECONDS.sleep(100); - SSD1306_command(0xD6); - SSD1306_command(0x00); - TimeUnit.MILLISECONDS.sleep(100); - } - } -} diff --git a/app/src/main/java/io/pslab/communication/sensors/Sx1276.java b/app/src/main/java/io/pslab/communication/sensors/Sx1276.java deleted file mode 100644 index 093c4b1cb..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/Sx1276.java +++ /dev/null @@ -1,453 +0,0 @@ -package io.pslab.communication.sensors; - -import android.util.Log; - -import io.pslab.communication.peripherals.SPI; - -import java.io.IOException; -import java.util.ArrayList; - -/** - * Created by Padmal on 6/12/17. - */ - -public class Sx1276 { - - private String name = "SX1276"; - // Registers - private int REG_FIFO = 0x00; - private int REG_OP_MODE = 0x01; - private int REG_FRF_MSB = 0x06; - private int REG_FRF_MID = 0x07; - private int REG_FRF_LSB = 0x08; - private int REG_PA_CONFIG = 0x09; - private int REG_LNA = 0x0c; - private int REG_FIFO_ADDR_PTR = 0x0d; - private int REG_FIFO_TX_BASE_ADDR = 0x0e; - private int REG_FIFO_RX_BASE_ADDR = 0x0f; - private int REG_FIFO_RX_CURRENT_ADDR = 0x10; - private int REG_IRQ_FLAGS = 0x12; - private int REG_RX_NB_BYTES = 0x13; - private int REG_PKT_RSSI_VALUE = 0x1a; - private int REG_PKT_SNR_VALUE = 0x1b; - private int REG_MODEM_CONFIG_1 = 0x1d; - private int REG_MODEM_CONFIG_2 = 0x1e; - private int REG_PREAMBLE_MSB = 0x20; - private int REG_PREAMBLE_LSB = 0x21; - private int REG_PAYLOAD_LENGTH = 0x22; - private int REG_MODEM_CONFIG_3 = 0x26; - private int REG_RSSI_WIDEBAND = 0x2c; - private int REG_DETECTION_OPTIMIZE = 0x31; - private int REG_DETECTION_THRESHOLD = 0x37; - private int REG_SYNC_WORD = 0x39; - private int REG_DIO_MAPPING_1 = 0x40; - private int REG_VERSION = 0x42; - private int REG_PA_DAC = 0x4D; - // Modes - private int MODE_LONG_RANGE_MODE = 0x80; - private int MODE_SLEEP = 0x00; - private int MODE_STDBY = 0x01; - private int MODE_TX = 0x03; - private int MODE_RX_CONTINUOUS = 0x05; - private int MODE_RX_SINGLE = 0x06; - // PA config - private int PA_BOOST = 0x80; - // IRQ masks - private int IRQ_TX_DONE_MASK = 0x08; - private int IRQ_PAYLOAD_CRC_ERROR_MASK = 0x20; - private int IRQ_RX_DONE_MASK = 0x40; - - private int MAX_PKT_LENGTH = 255; - private int PA_OUTPUT_RFO_PIN = 0; - private int PA_OUTPUT_PA_BOOST_PIN = 1; - private int onReceive = 0; - private int frequency = 10; - private int packetIndex = 0; - private int packetLength = 0; - private int version = 0; - private int implicitHeaderMode = 0; - - private SPI spi; - private ArrayList bytes = new ArrayList<>(); - - public Sx1276(SPI spi, int frequency, int power, boolean boost, double bw, int sf, int cf) throws IOException { - initiateSX1276(spi, frequency); - // Output Power 17dbm - setTxPower(power, boost ? PA_OUTPUT_PA_BOOST_PIN : PA_OUTPUT_RFO_PIN); - idle(); - // Set bandwidth - setSignalBandwidth(bw); - setSpreadingFactor(sf); - setCodingRate4(cf); - } - - public Sx1276(SPI spi, int frequency) throws IOException { - - initiateSX1276(spi, frequency); - // Output Power 17dbm - setTxPower(17, PA_OUTPUT_RFO_PIN); - idle(); - // Set bandwidth - setSignalBandwidth(125e3); - setSpreadingFactor(12); - setCodingRate4(5); - } - - private void initiateSX1276(SPI spi, int frequency) throws IOException { - - this.spi = spi; - this.spi.setParameters(2, 6, 1, 0, 1); - this.frequency = frequency; - this.name = "SX1276"; - - reset(); - - this.version = SPIRead(REG_VERSION, 1).get(0); - if (version != 0x12) { - Log.d(name, "Version error " + version); - } - sleep(); - setFrequency(frequency); - // Set base address - setupBytesArray(0); - SPIWrite(REG_FIFO_TX_BASE_ADDR, bytes); - SPIWrite(REG_FIFO_RX_BASE_ADDR, bytes); - // Set LNA boost - setupBytesArray(SPIRead(REG_LNA, 1).get(0) | 0x03); - SPIWrite(REG_LNA, bytes); - // Set auto ADC - setupBytesArray(0x04); - SPIWrite(REG_MODEM_CONFIG_3, bytes); - } - - private void reset() { - /**/ - } - - private ArrayList SPIRead(int adr, int total_bytes) throws IOException { - // CS1 => 9 - ArrayList data = new ArrayList<>(); - data.add((byte) adr); - for (int i = 0; i < total_bytes; i++) { - data.add((byte) 0); - } - data.remove(0); - return spi.xfer(9, data); - } - - private void beginPacket(boolean implicitHeader) throws IOException { - idle(); - if (implicitHeader) { - implicitHeaderMode(); - } else { - explicitHeaderMode(); - } - // reset FIFO & payload length - bytes.clear(); - bytes.add((byte) 0); - SPIWrite(REG_FIFO_ADDR_PTR, bytes); - SPIWrite(REG_PAYLOAD_LENGTH, bytes); - } - - private void endPacket() throws InterruptedException, IOException { - // put in TX mode - bytes.clear(); - bytes.add((byte) (MODE_LONG_RANGE_MODE | MODE_TX)); - SPIWrite(REG_OP_MODE, bytes); - - while (true) { // Wait for TX done - if ((SPIRead(REG_IRQ_FLAGS, 1).get(0) & IRQ_TX_DONE_MASK) == 1) { - break; - } else { - Thread.sleep(100); - } - } - setupBytesArray(IRQ_TX_DONE_MASK); - SPIWrite(REG_IRQ_FLAGS, bytes); - } - - private int parsePacket(int size) throws IOException { - packetLength = 0; - int irqFlags = SPIRead(REG_IRQ_FLAGS, 1).get(0); - if (size > 0) { - implicitHeaderMode(); - setupBytesArray(size & 0xFF); - SPIWrite(REG_PAYLOAD_LENGTH, bytes); - } else { - explicitHeaderMode(); - } - setupBytesArray(irqFlags); - SPIWrite(REG_IRQ_FLAGS, bytes); - - if (((irqFlags & IRQ_RX_DONE_MASK) == 1) && ((irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0)) { - packetIndex = 0; - if (implicitHeaderMode == 1) { - packetLength = SPIRead(REG_PAYLOAD_LENGTH, 1).get(0); - } else { - packetLength = SPIRead(REG_RX_NB_BYTES, 1).get(0); - } - SPIWrite(REG_FIFO_ADDR_PTR, SPIRead(REG_FIFO_RX_CURRENT_ADDR, 1)); - idle(); - } else if (SPIRead(REG_OP_MODE, 1).get(0) != (MODE_LONG_RANGE_MODE | MODE_RX_SINGLE)) { - setupBytesArray(0); - SPIWrite(REG_FIFO_ADDR_PTR, bytes); - setupBytesArray(MODE_LONG_RANGE_MODE | MODE_RX_SINGLE); - SPIWrite(REG_OP_MODE, bytes); - } - return packetLength; - } - - private int packetRssi() throws IOException { - return SPIRead(REG_PKT_RSSI_VALUE, 1).get(0) - ((frequency < 868e6) ? 164 : 157); - } - - private double packetSnr() throws IOException { - return SPIRead(REG_PKT_SNR_VALUE, 1).get(0) * 0.25; - } - - public int write(ArrayList byteArray) throws IOException { - int size = byteArray.size(); - int currentLength = SPIRead(REG_PAYLOAD_LENGTH, 1).get(0); - if ((currentLength + size) > MAX_PKT_LENGTH) { - size = MAX_PKT_LENGTH - currentLength; - } - SPIWrite(REG_FIFO, (ArrayList) byteArray.subList(0, size)); - setupBytesArray(currentLength + size); - SPIWrite(REG_PAYLOAD_LENGTH, bytes); - return size; - } - - public boolean available() throws IOException { - return (SPIRead(REG_RX_NB_BYTES, 1).get(0) - packetIndex) == 1; - } - - public int checkRx() throws IOException { - byte irqFlags = SPIRead(REG_IRQ_FLAGS, 1).get(0); - if (((irqFlags & IRQ_RX_DONE_MASK) == 1) && ((irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0)) { - return 1; - } else { - return 0; - } - } - - public byte read() throws IOException { - if (available()) { - packetIndex++; - return SPIRead(REG_FIFO, 1).get(0); - } else return -1; - } - - public ArrayList readAll() throws IOException { - ArrayList p = new ArrayList<>(); - while (available()) { - p.add(read()); - } - return p; - } - - public byte peek() throws IOException { - if (available()) { - ArrayList currentAddress = SPIRead(REG_FIFO_ADDR_PTR, 1); - byte val = SPIRead(REG_FIFO, 1).get(0); - SPIWrite(REG_FIFO_ADDR_PTR, currentAddress); - return val; - } else { - return -1; - } - } - - public void flush() { - /**/ - } - - public void receive(int size) throws IOException { - if (size > 0) { - implicitHeaderMode(); - setupBytesArray(size & 0xFF); - SPIWrite(REG_PAYLOAD_LENGTH, bytes); - } else { - explicitHeaderMode(); - setupBytesArray(MODE_LONG_RANGE_MODE | MODE_RX_SINGLE); - SPIWrite(REG_OP_MODE, bytes); - } - } - - private void idle() throws IOException { - setupBytesArray(MODE_LONG_RANGE_MODE | MODE_STDBY); - SPIWrite(REG_OP_MODE, bytes); - } - - private void sleep() throws IOException { - setupBytesArray(MODE_LONG_RANGE_MODE | MODE_SLEEP); - SPIWrite(REG_OP_MODE, bytes); - } - - private void setTxPower(int level, int pin) throws IOException { - if (pin == PA_OUTPUT_RFO_PIN) { - if (level < 0) { - level = 0; - } else if (level > 14) { - level = 14; - } - setupBytesArray(0x70 | level); - SPIWrite(REG_PA_CONFIG, bytes); - } else { - if (level < 2) { - level = 2; - } else if (level > 17) { - level = 17; - } - if (level == 17) { - Log.d(name, "max power output"); - setupBytesArray(0x87); - SPIWrite(REG_PA_DAC, bytes); - } else { - setupBytesArray(0x84); - SPIWrite(REG_PA_DAC, bytes); - } - setupBytesArray(PA_BOOST | 0x70 | (level - 2)); - SPIWrite(REG_PA_CONFIG, bytes); - } - Log.d(name, "Power " + SPIRead(REG_PA_CONFIG, 1).get(0)); - } - - private void setFrequency(int frq) throws IOException { - this.frequency = frq; - int frf = (frq << 19) / 32000000; - Log.d(name, "frf = " + frf); - Log.d(name, "freq = " + ((frf >> 16) & 0xFF) + " " + ((frf >> 8) & 0xFF) + " " + (frf & 0xFF)); - setupBytesArray((frf >> 16) & 0xFF); - SPIWrite(REG_FRF_MSB, bytes); - setupBytesArray((frf >> 8) & 0xFF); - SPIWrite(REG_FRF_MID, bytes); - setupBytesArray(frf & 0xFF); - SPIWrite(REG_FRF_LSB, bytes); - } - - private void setSpreadingFactor(int spreadingFactor) throws IOException { - if (spreadingFactor < 6) { - spreadingFactor = 6; - } else if (spreadingFactor > 12) { - spreadingFactor = 12; - } - - if (spreadingFactor == 6) { - setupBytesArray(0xc5); - SPIWrite(REG_DETECTION_OPTIMIZE, bytes); - setupBytesArray(0x0c); - SPIWrite(REG_DETECTION_THRESHOLD, bytes); - } else { - setupBytesArray(0xc3); - SPIWrite(REG_DETECTION_OPTIMIZE, bytes); - setupBytesArray(0x0a); - SPIWrite(REG_DETECTION_THRESHOLD, bytes); - } - setupBytesArray((SPIRead(REG_MODEM_CONFIG_2, 1).get(0) & 0x0F) | ((spreadingFactor << 4) & 0xF0)); - SPIWrite(REG_MODEM_CONFIG_2, bytes); - } - - private void setSignalBandwidth(double sbw) throws IOException { - int bw = 9; - int num = 0; - double[] referenceList = {7.8e3, 10.4e3, 15.6e3, 20.8e3, 31.25e3, 41.7e3, 62.5e3, 125e3, 250e3}; - for (double item : referenceList) { - if (sbw <= item) { - bw = num; - break; - } - num++; - } - Log.d(name, "Bandwidth " + bw); - setupBytesArray((SPIRead(REG_MODEM_CONFIG_1, 1).get(0) & 0x0F) | (bw << 4)); - SPIWrite(REG_MODEM_CONFIG_1, bytes); - } - - private void setCodingRate4(int denominator) throws IOException { - if (denominator < 5) { - denominator = 5; - } else if (denominator > 8) { - denominator = 8; - } - setupBytesArray((SPIRead(REG_MODEM_CONFIG_1, 1).get(0) & 0xF1) | ((denominator - 4) << 4)); - SPIWrite(REG_MODEM_CONFIG_1, bytes); - } - - public void setPreambleLength(int length) throws IOException { - setupBytesArray((length >> 8) & 0xFF); - SPIWrite(REG_PREAMBLE_MSB, bytes); - setupBytesArray(length & 0xFF); - SPIWrite(REG_PREAMBLE_LSB, bytes); - } - - public void setSyncWord(ArrayList Word) throws IOException { - SPIWrite(REG_SYNC_WORD, Word); - } - - public void crc() throws IOException { - setupBytesArray(SPIRead(REG_MODEM_CONFIG_2, 1).get(0) | 0x04); - SPIWrite(REG_MODEM_CONFIG_2, bytes); - } - - public void noCrc() throws IOException { - setupBytesArray(SPIRead(REG_MODEM_CONFIG_2, 1).get(0) & 0xFB); - SPIWrite(REG_MODEM_CONFIG_2, bytes); - } - - public byte random() throws IOException { - return (SPIRead(REG_RSSI_WIDEBAND, 1).get(0)); - } - - private void explicitHeaderMode() throws IOException { - implicitHeaderMode = 0; - setupBytesArray(SPIRead(REG_MODEM_CONFIG_1, 1).get(0) & 0xFE); - SPIWrite(REG_MODEM_CONFIG_1, bytes); - } - - private void implicitHeaderMode() throws IOException { - implicitHeaderMode = 1; - setupBytesArray(SPIRead(REG_MODEM_CONFIG_1, 1).get(0) | 0x01); - SPIWrite(REG_MODEM_CONFIG_1, bytes); - } - - public void handleDio0Rise() throws IOException { - byte irqFlags = SPIRead(REG_IRQ_FLAGS, 1).get(0); - setupBytesArray(irqFlags); - SPIWrite(REG_IRQ_FLAGS, bytes); - - if ((irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) { - packetIndex = 0; - if (implicitHeaderMode == 0) { - packetLength = SPIRead(REG_PAYLOAD_LENGTH, 1).get(0); - } else { - packetLength = SPIRead(REG_RX_NB_BYTES, 1).get(0); - } - - SPIWrite(REG_FIFO_ADDR_PTR, SPIRead(REG_FIFO_RX_CURRENT_ADDR, 1)); - if (onReceive == 1) { - Log.d(name, "Packet Length " + packetLength); - } - } - - setupBytesArray(0); - SPIWrite(REG_FIFO_ADDR_PTR, bytes); - } - - private ArrayList SPIWrite(int adr, ArrayList byteArray) throws IOException { - // CS1 => 9 - ArrayList data = new ArrayList<>(); - data.add((byte) (0x80 | adr)); - data.addAll(byteArray); - ArrayList XFER = spi.xfer(9, data); - XFER.remove(0); - return XFER; - } - - public ArrayList getRaw() throws IOException { - return SPIRead(0x02, 1); - } - - private void setupBytesArray(int data) { - bytes.clear(); - bytes.add((byte) data); - } -} diff --git a/app/src/main/java/io/pslab/communication/sensors/TSL2561.java b/app/src/main/java/io/pslab/communication/sensors/TSL2561.java deleted file mode 100644 index 53c44ef50..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/TSL2561.java +++ /dev/null @@ -1,124 +0,0 @@ -package io.pslab.communication.sensors; - -import android.util.Log; - -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; - -/** - * Created by akarshan on 4/15/17. - */ - -public class TSL2561 { - private String TAG = "TSL2561"; - private int VISIBLE = 2; // channel 0 - channel 1 - private int INFRARED = 1; // channel 1 - private int FULLSPECTRUM = 0; // channel 0 - - private int READBIT = 0x01; - private int COMMAND_BIT = 0x80; // Must be 1 - - private int CONTROL_POWERON = 0x03; - private int CONTROL_POWEROFF = 0x00; - - private int REGISTER_CONTROL = 0x00; - private int REGISTER_TIMING = 0x01; - private int REGISTER_ID = 0x0A; - - private int INTEGRATIONTIME_13MS = 0x00; // 13.7ms - private int INTEGRATIONTIME_101MS = 0x01; // 101ms - private int INTEGRATIONTIME_402MS = 0x02; // 402ms - - private int GAIN_1X = 0x00; // No gain - private int GAIN_16X = 0x10; // 16x gain - private int GAIN_OX; - - private int ADDRESS = 0x39; // addr normal - private int timing = INTEGRATIONTIME_13MS; - private int gain = GAIN_16X; - - public String name = "TSL2561 Luminosity"; - public int NUMPLOTS = 3; - public String[] PLOTNAMES = {"Full", "IR", "Visible"}; - - private I2C i2c; - private int full, infra; - private ArrayList infraList, fullList; - private ArrayList setGain = new ArrayList(Arrays.asList("1x", "16x")); - private ArrayList setTiming = new ArrayList(Arrays.asList(0, 1, 2)); - - public TSL2561(I2C i2c, ScienceLab scienceLab) throws IOException, InterruptedException { - this.i2c = i2c; - // set timing 101ms & 16x gain - if (scienceLab.isConnected()) { - enable(); - _wait(); - i2c.writeBulk(ADDRESS, new int[]{0x80 | 0x01, 0x01 | 0x10}); - //full scale luminosity - infraList = i2c.readBulk(ADDRESS, 0x80 | 0x20 | 0x0E, 2); - fullList = i2c.readBulk(ADDRESS, 0x80 | 0x20 | 0x0C, 2); - full = (fullList.get(1) << 8) | fullList.get(0); - infra = (infraList.get(1) << 8) | infraList.get(0); - - Log.v(TAG, "Full - " + Integer.toString(full)); - Log.v(TAG, "Infrared - " + Integer.toString(infra)); - Log.v(TAG, "Visible -" + Integer.toString(full - infra)); - } - } - - public int getID() throws IOException { - ArrayList _ID_ = i2c.readBulk(ADDRESS, REGISTER_ID, 1); - int ID = Integer.parseInt(Character.getNumericValue(_ID_.get(0)) + "", 16); - Log.d("ID", Integer.toString(ID)); - return ID; - } - - public int[] getRaw() throws IOException { - fullList = i2c.readBulk(ADDRESS, 0x80 | 0x20 | 0x0E, 2); - infraList = i2c.readBulk(ADDRESS, 0x80 | 0x20 | 0x0C, 2); - if (!infraList.isEmpty()) { - full = (fullList.get(0) << 8) | fullList.get(0); - infra = (infraList.get(0) << 8) | infraList.get(0); - return (new int[]{full, infra, full - infra}); - } else - return null; - } - - public void setGain(String _gain_) throws IOException { - if (_gain_.equals("1x")) - gain = GAIN_1X; - - else if (_gain_.equals("16x")) - gain = GAIN_16X; - else - gain = GAIN_OX; - i2c.writeBulk(ADDRESS, new int[]{COMMAND_BIT | REGISTER_TIMING, gain | timing}); - } - - public void setTiming(int timing) throws IOException { - Log.v(TAG, new int[]{13, 101, 404}[timing] + "mS"); - this.timing = timing; - i2c.writeBulk(ADDRESS, new int[]{COMMAND_BIT | REGISTER_TIMING, gain | timing}); - } - - private void enable() throws IOException { - i2c.writeBulk(ADDRESS, new int[]{COMMAND_BIT | REGISTER_CONTROL, CONTROL_POWERON}); - } - - public void disable() throws IOException { - i2c.writeBulk(ADDRESS, new int[]{COMMAND_BIT | REGISTER_CONTROL, CONTROL_POWEROFF}); - } - - private void _wait() throws InterruptedException { - if (timing == INTEGRATIONTIME_13MS) TimeUnit.MILLISECONDS.sleep(14); - if (timing == INTEGRATIONTIME_101MS) TimeUnit.MILLISECONDS.sleep(102); - if (timing == INTEGRATIONTIME_402MS) TimeUnit.MILLISECONDS.sleep(403); - - } - -} diff --git a/app/src/main/java/io/pslab/communication/sensors/VL53L0X.java b/app/src/main/java/io/pslab/communication/sensors/VL53L0X.java deleted file mode 100644 index 166c6157d..000000000 --- a/app/src/main/java/io/pslab/communication/sensors/VL53L0X.java +++ /dev/null @@ -1,313 +0,0 @@ -package io.pslab.communication.sensors; - -import android.util.Log; - -import java.io.IOException; -import java.util.ArrayList; - -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; - -public class VL53L0X { - - // VL53L0X default address - private static final int ADDRESS = 0x29; - private final I2C i2c; - - // Configuration constants, taken from https://github.com/adafruit/Adafruit_CircuitPython_VL53L0X.git - private static final int SYSRANGE_START = 0x00; - private static final int SYSTEM_SEQUENCE_CONFIG = 0x01; - private static final int SYSTEM_INTERRUPT_CONFIG_GPIO = 0x0A; - private static final int GPIO_HV_MUX_ACTIVE_HIGH = 0x84; - private static final int SYSTEM_INTERRUPT_CLEAR = 0x0B; - private static final int RESULT_INTERRUPT_STATUS = 0x13; - private static final int RESULT_RANGE_STATUS = 0x14; - private static final int MSRC_CONFIG_CONTROL = 0x60; - private static final int GLOBAL_CONFIG_SPAD_ENABLES_REF_0 = 0xB0; - private static final int GLOBAL_CONFIG_REF_EN_START_SELECT = 0xB6; - private static final int DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD = 0x4E; - private static final int DYNAMIC_SPAD_REF_EN_START_OFFSET = 0x4F; - private static final int DISABLE_SIGNAL_RATE_MSRC = 0x2; - private static final int DISABLE_SIGNAL_RATE_PRE_RANGE = 0x10; - - private static final int[][] SPAD_CONFIG = { - {0xFF, 0x01}, - {DYNAMIC_SPAD_REF_EN_START_OFFSET, 0x00}, - {DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, 0x2C}, - {0xFF, 0x00}, - {GLOBAL_CONFIG_REF_EN_START_SELECT, 0xB4} - }; - - private static final int[][] TUNING_CONFIG = { - {0xFF, 0x01}, - {0x00, 0x00}, - {0xFF, 0x00}, - {0x09, 0x00}, - {0x10, 0x00}, - {0x11, 0x00}, - {0x24, 0x01}, - {0x25, 0xFF}, - {0x75, 0x00}, - {0xFF, 0x01}, - {0x4E, 0x2C}, - {0x48, 0x00}, - {0x30, 0x20}, - {0xFF, 0x00}, - {0x30, 0x09}, - {0x54, 0x00}, - {0x31, 0x04}, - {0x32, 0x03}, - {0x40, 0x83}, - {0x46, 0x25}, - {0x60, 0x00}, - {0x27, 0x00}, - {0x50, 0x06}, - {0x51, 0x00}, - {0x52, 0x96}, - {0x56, 0x08}, - {0x57, 0x30}, - {0x61, 0x00}, - {0x62, 0x00}, - {0x64, 0x00}, - {0x65, 0x00}, - {0x66, 0xA0}, - {0xFF, 0x01}, - {0x22, 0x32}, - {0x47, 0x14}, - {0x49, 0xFF}, - {0x4A, 0x00}, - {0xFF, 0x00}, - {0x7A, 0x0A}, - {0x7B, 0x00}, - {0x78, 0x21}, - {0xFF, 0x01}, - {0x23, 0x34}, - {0x42, 0x00}, - {0x44, 0xFF}, - {0x45, 0x26}, - {0x46, 0x05}, - {0x40, 0x40}, - {0x0E, 0x06}, - {0x20, 0x1A}, - {0x43, 0x40}, - {0xFF, 0x00}, - {0x34, 0x03}, - {0x35, 0x44}, - {0xFF, 0x01}, - {0x31, 0x04}, - {0x4B, 0x09}, - {0x4C, 0x05}, - {0x4D, 0x04}, - {0xFF, 0x00}, - {0x44, 0x00}, - {0x45, 0x20}, - {0x47, 0x08}, - {0x48, 0x28}, - {0x67, 0x00}, - {0x70, 0x04}, - {0x71, 0x01}, - {0x72, 0xFE}, - {0x76, 0x00}, - {0x77, 0x00}, - {0xFF, 0x01}, - {0x0D, 0x01}, - {0xFF, 0x00}, - {0x80, 0x01}, - {0x01, 0xF8}, - {0xFF, 0x01}, - {0x8E, 0x01}, - {0x00, 0x01}, - {0xFF, 0x00}, - {0x80, 0x00} - }; - - private static final int MAYBE_TIMER_REG = 0x83; - private static final int[][] SPAD_1 = { - {0x80, 0x01}, - {0xFF, 0x01}, - {0x00, 0x00}, - {0xFF, 0x06} - }; - private static final int[][] SPAD_2 = { - {0xFF, 0x07}, - {0x81, 0x01}, - {0x80, 0x01}, - {0x94, 0x6B}, - {MAYBE_TIMER_REG, 0x00} - }; - private static final int[][] SPAD_3 = { - {0x81, 0x00}, - {0xFF, 0x06} - }; - private static final int[][] SPAD_4 = { - {0xFF, 0x01}, - {0x00, 0x01}, - {0xFF, 0x00}, - {0x80, 0x00} - }; - - private static final int IO_TIMEOUT = 10; - private int stopByte; - - public VL53L0X(I2C i2c, ScienceLab scienceLab) throws Exception { - this.i2c = i2c; - if (scienceLab.isConnected()) { - for (int[] regValPair : new int[][]{ - {0x88, 0x00}, - {0x80, 0x01}, - {0xFF, 0x01}, - {0x00, 0x00} - }) { - i2c.write(ADDRESS, new int[]{regValPair[1]}, regValPair[0]); - } - stopByte = i2c.readByte(ADDRESS, 0x91); - - for (int[] regValPair : new int[][]{ - {0x00, 0x01}, - {0xFF, 0x00}, - {0x80, 0x00} - }) { - i2c.write(ADDRESS, new int[]{regValPair[1]}, regValPair[0]); - } - int configControl = i2c.readByte(ADDRESS, MSRC_CONFIG_CONTROL) | (DISABLE_SIGNAL_RATE_MSRC | DISABLE_SIGNAL_RATE_PRE_RANGE); - - i2c.write(ADDRESS, new int[]{configControl}, MSRC_CONFIG_CONTROL); - - i2c.write(ADDRESS, new int[]{0xFF}, SYSTEM_SEQUENCE_CONFIG); - - spadConfig(); - - for (int[] regValPair : TUNING_CONFIG) { - i2c.write(ADDRESS, new int[]{regValPair[1]}, regValPair[0]); - } - - i2c.write(ADDRESS, new int[]{0x04}, SYSTEM_INTERRUPT_CONFIG_GPIO); - int gpioHvMuxActiveHigh = i2c.readByte(ADDRESS, GPIO_HV_MUX_ACTIVE_HIGH); - i2c.write(ADDRESS, new int[]{gpioHvMuxActiveHigh & ~0x10}, GPIO_HV_MUX_ACTIVE_HIGH); - i2c.write(ADDRESS, new int[]{0x01}, SYSTEM_INTERRUPT_CLEAR); - i2c.write(ADDRESS, new int[]{0xE8}, SYSTEM_SEQUENCE_CONFIG); - - i2c.write(ADDRESS, new int[]{0x01}, SYSTEM_SEQUENCE_CONFIG); - performSingleRefCalibration(0x40); - i2c.write(ADDRESS, new int[]{0x01}, SYSTEM_SEQUENCE_CONFIG); - i2c.write(ADDRESS, new int[]{0x02}, SYSTEM_SEQUENCE_CONFIG); - performSingleRefCalibration(0x00); - - i2c.write(ADDRESS, new int[]{0xE8}, SYSTEM_SEQUENCE_CONFIG); - } - } - - private int[] getSpadInfo() throws Exception { - for (int[] regValPair : SPAD_1) { - i2c.write(ADDRESS, new int[]{regValPair[1]}, regValPair[0]); - } - - int uu = i2c.readByte(ADDRESS, MAYBE_TIMER_REG) | 0x04; - i2c.write(ADDRESS, new int[]{uu}, MAYBE_TIMER_REG); - - for (int[] regValPair : SPAD_2) { - i2c.write(ADDRESS, new int[]{regValPair[1]}, regValPair[0]); - } - - long start = System.currentTimeMillis(); - - while (i2c.readByte(ADDRESS, MAYBE_TIMER_REG) == 0x00) { - if (IO_TIMEOUT > 0 && (System.currentTimeMillis() - start) / 1000.0 >= IO_TIMEOUT) { - Log.e("VL53L0X", "Timeout waiting for VL53L0X!"); - } - } - - i2c.write(ADDRESS, new int[]{0x01}, MAYBE_TIMER_REG); - - int tmp = i2c.readByte(ADDRESS, 0X92); - int count = tmp & 0x7F; - boolean isAperture = ((tmp >> 7) & 0x01) == 1; - - for (int[] regValPair : SPAD_3) { - i2c.write(ADDRESS, new int[]{regValPair[1]}, regValPair[0]); - } - - int vv = i2c.readByte(ADDRESS, MAYBE_TIMER_REG) & ~0x04; - i2c.write(ADDRESS, new int[]{vv}, MAYBE_TIMER_REG); - - for (int[] regValPair : SPAD_4) { - i2c.write(ADDRESS, new int[]{regValPair[1]}, regValPair[0]); - } - return new int[]{count, isAperture ? 1 : 0}; - } - - private void spadConfig() throws Exception { - int[] spadInfo = getSpadInfo(); - int spadCount = spadInfo[0]; - int spadIsAperture = spadInfo[1]; - - i2c.write(ADDRESS, new int[]{0}, GLOBAL_CONFIG_SPAD_ENABLES_REF_0); - ArrayList spadMap = i2c.read(ADDRESS, 6, GLOBAL_CONFIG_SPAD_ENABLES_REF_0); - - for (int[] regValPair : SPAD_CONFIG) { - i2c.write(ADDRESS, new int[]{regValPair[1]}, regValPair[0]); - } - - int firstSpadToEnable = (spadIsAperture == 1) ? 12 : 0; - int spadsEnabled = 0; - - for (int i = 0; i < 48; i++) { - int index = i / 8; - if (i < firstSpadToEnable || spadsEnabled == spadCount) { - spadMap.set(index, spadMap.get(index) & ~(1 << (i % 8))); - } else if (((spadMap.get(index) >> (i % 8)) & 0x1) > 0) { - spadsEnabled++; - } - } - - i2c.write(ADDRESS, spadMap.stream().mapToInt(Integer::intValue).toArray(), GLOBAL_CONFIG_SPAD_ENABLES_REF_0); - } - - private void performSingleRefCalibration(int vhvInitByte) throws Exception { - i2c.write(ADDRESS, new int[]{0x01 | vhvInitByte & 0xFF}, SYSRANGE_START); - long start = System.currentTimeMillis(); - - while ((i2c.readByte(ADDRESS, RESULT_INTERRUPT_STATUS) & 0x07) == 0) { - if (IO_TIMEOUT > 0 && (System.currentTimeMillis() - start) / 1000.0 >= IO_TIMEOUT) { - Log.e("VL53L0X", "Timeout waiting for VL53L0X!"); - } - } - i2c.write(ADDRESS, new int[]{0x01}, SYSTEM_INTERRUPT_CLEAR); - i2c.write(ADDRESS, new int[]{0x00}, SYSRANGE_START); - } - - public int getRaw() throws Exception { - for (int[] regValPair : new int[][]{ - {0x80, 0x01}, - {0xFF, 0x01}, - {0x00, 0x00}, - {0x91, stopByte}, - {0x00, 0x01}, - {0xFF, 0x00}, - {0x80, 0x00}, - {SYSRANGE_START, 0x01} - }) { - i2c.write(ADDRESS, new int[]{regValPair[1]}, regValPair[0]); - } - - long start = System.currentTimeMillis(); - - while ((i2c.readByte(ADDRESS, SYSRANGE_START) & 0x01) > 0) { - if (IO_TIMEOUT > 0 && (System.currentTimeMillis() - start) / 1000.0 >= IO_TIMEOUT) { - Log.e("VL53L0X", "Timeout waiting for VL53L0X!"); - } - } - - start = System.currentTimeMillis(); - - while ((i2c.readByte(ADDRESS, RESULT_INTERRUPT_STATUS) & 0x07) == 0) { - if (IO_TIMEOUT > 0 && (System.currentTimeMillis() - start) / 1000.0 >= IO_TIMEOUT) { - Log.e("VL53L0X", "Timeout waiting for VL53L0X!"); - } - } - - ArrayList data = i2c.read(ADDRESS, 2, RESULT_RANGE_STATUS + 10); - i2c.write(ADDRESS, new int[]{0x01}, SYSTEM_INTERRUPT_CLEAR); - return ((data.get(0) & 0xFF) << 8) | (data.get(1) & 0xFF); - } -} diff --git a/app/src/main/java/io/pslab/filters/BandstopFilter.java b/app/src/main/java/io/pslab/filters/BandstopFilter.java deleted file mode 100644 index d8d7116f0..000000000 --- a/app/src/main/java/io/pslab/filters/BandstopFilter.java +++ /dev/null @@ -1,205 +0,0 @@ -package io.pslab.filters; - -import android.util.Log; - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; -import org.apache.commons.math3.complex.Complex; - - -import java.util.ArrayList; -import java.util.Arrays; - -import static java.lang.Math.cos; -import static java.lang.Math.sin; -import static java.lang.Math.sqrt; -import static java.lang.Math.tan; - -/** - * Created by akarshan on 5/29/17. - */ - -public class BandstopFilter { - private String TAG = "BandStopFilter"; - private double[] a; - private double[] b; - - public BandstopFilter(int order, double[] wn){ - int k = 1; - double z[] = new double[]{}; - Complex p[] = buttap(order); - double[] warped = new double[wn.length]; - double fs = 2.0; - for(int i = 0; i < wn.length; i++) - warped[i] = 2 * fs * tan(Math.PI * wn[i] / fs); - double bw = warped[1] - warped[0]; - double wo = sqrt(warped[0] * warped[1]); - - ArrayList zpklp2bsObjectArray = zpklp2bs(z, p, k, wo, bw); - Complex[] z2 = (Complex[]) zpklp2bsObjectArray.get(0); - p = (Complex[]) zpklp2bsObjectArray.get(1); - k = (int) zpklp2bsObjectArray.get(2); - - ArrayList zpkBilinearObjectArray = zpkBilinear(z2, p, k, fs); - z2 = (Complex[])zpkBilinearObjectArray.get(0); - p = (Complex[])zpkBilinearObjectArray.get(1); - double k2 = (double)zpkBilinearObjectArray.get(2); - - ArrayList zpk2tfArray = zpk2tf(z2, p, k2); - a = zpk2tfArray.get(0); - b = zpk2tfArray.get(1); - } - - private Complex[] buttap(int order){ - /* - Return (z,p,k) for analog prototype of Nth-order Butterworth filter. - The filter will have an angular (e.g. rad/s) cutoff frequency of 1. - */ - ArrayList m = new ArrayList(); - Complex p[]; - if (Math.abs(order) != order) - Log.v(TAG, "Filter order must be a nonnegative integer"); - for(int i = -order + 1; i < order; i = i + 2) - m.add(i); - p = new Complex[m.size()]; - for(int i = 0; i < m.size(); i++) - p[i] = new Complex(-cos(m.get(i) * Math.PI / (2 * order)), -sin(m.get(i) * Math.PI / (2 * order))); - - return p; - } - - private ArrayList zpklp2bs(double[] z, Complex[] p, int k, double wo, double bw){ - int degree = relativeDegree(z, p); - double[] zhp = new double[z.length]; - Complex[] php = new Complex[p.length]; - Complex[] zbs = new Complex[degree * 2]; - Complex[] pbs = new Complex[p.length * 2]; - double zProd = 1; - double pProd = 1; - int kbs; - - // Invert to a highpass filter with desired bandwidth - for(int i = 0; i < z.length; i++) - zhp[i] = (bw / 2) / z[i]; - - Complex numerator = new Complex((bw/2)); - for(int i = 0; i < p.length; i++) - php[i] = numerator.divide(p[i]); - - // Duplicate poles and zeros and shift from baseband to +wo and -wo - int l = 0; - for(int i = 0; i < degree; i++) - zbs[i] = new Complex(0, wo); - for(int i = 0; i < degree; i++) - zbs[degree + i] = new Complex(0, -wo); - for(int i = 0; i < p.length; i++) - pbs[i] = php[i].add((php[i].pow(2).subtract(Math.pow(wo, 2))).sqrt()); - for(int i = 0; i < p.length; i++) - pbs[i + p.length] = php[i].subtract((php[i].pow(2).subtract(Math.pow(wo, 2))).sqrt()); - - // Cancel out gain change caused by inversion - Complex temp = new Complex(1,0); - for (Complex aP : p) temp = temp.multiply(aP.negate()); - - pProd = temp.getReal(); - kbs = (int) (k / pProd); - return new ArrayList(Arrays.asList(zbs, pbs, kbs)); - } - - private ArrayList zpkBilinear(Complex[] z, Complex[] p, int k, double fs){ - //Return a digital filter from an analog one using a bilinear transform. - Complex[] zz = new Complex[z.length]; - Complex[] pz = new Complex[p.length]; - double kz; - relativeDegree(z, p); - double fs2 = 2 * fs; - Complex complexFs2 = new Complex(fs2); - for(int i = 0; i < z.length; i++){ - zz[i] = (complexFs2.add(z[i])).divide(complexFs2.subtract(z[i])); - } - for(int i = 0; i < p.length; i++){ - pz[i] = (complexFs2.add(p[i])).divide(complexFs2.subtract(p[i])); - } - - //rearranging pz - ArrayList pz2 = new ArrayList(); - for (Complex aPz : pz) { - if (!pz2.contains(aPz) && !pz2.contains(aPz.conjugate())) { - pz2.add(aPz); - } - } - - for(int i = 0; i < pz.length / 2; i++) - pz2.add(pz2.get(i).conjugate()); - - Complex [] pzRearranged = pz2.toArray(new Complex[pz.length]); - - Complex temp = new Complex(1,0); - for (Complex aZ : z) temp = temp.multiply(complexFs2.subtract(aZ)); - - - Complex temp2 = new Complex(1,0); - for (Complex aP : p) temp2 = temp2.multiply(complexFs2.subtract(aP)); - - kz = (k * (temp.divide(temp2)).getReal()); - return new ArrayList(Arrays.asList(zz, pzRearranged, kz)); - } - - private ArrayList zpk2tf(Complex[] z, Complex[] p, double k){ - //Return polynomial transfer function representation from zeros and poles - double[] zCoefficients = rootsToPolynomial(z); - double[] bCoefficients = new double[zCoefficients.length]; - - for(int i = 0; i < zCoefficients.length; i++) - bCoefficients[i] = zCoefficients[i] * k; - - double[] aCoefficients = rootsToPolynomial(p); - ArrayUtils.reverse(aCoefficients); - return new ArrayList(Arrays.asList(aCoefficients,bCoefficients)); - } - - private int relativeDegree(double[] z,Complex[] p){ - int degree = p.length - z.length; - if(degree < 0) { - Log.v(TAG, "Improper transfer function."); - return -1; - } - else - return degree; - } - - private int relativeDegree(Complex[] z,Complex[] p){ - int degree = p.length - z.length; - if(degree < 0) { - Log.v(TAG, "Improper transfer function."); - return -1; - } - else - return degree; - } - - private double[] rootsToPolynomial(Complex[] x){ - /* - Returns a double array of coefficients of the polynomial, - assuming the each complex root has it's conjugate in the same array. - */ - PolynomialFunction[] polynomialFunctionArray = new PolynomialFunction[x.length/2]; - PolynomialFunction product = new PolynomialFunction(new double[]{1}); - for(int i = 0; i < x.length / 2; i++){ - PolynomialFunction complexRoot = new PolynomialFunction(new double[]{-x[i].getReal(), 1}); - complexRoot = complexRoot.multiply(complexRoot); - complexRoot = complexRoot.subtract(new PolynomialFunction(new double[]{-1 * x[i].getImaginary() * x[i].getImaginary()})); - System.out.println((complexRoot)); - polynomialFunctionArray[i] = complexRoot; - } - - for (PolynomialFunction aPolynomialFunctionArray : polynomialFunctionArray) - product = aPolynomialFunctionArray.multiply(product); - - return product.getCoefficients(); - } - - public ArrayList abGetter(){ - return new ArrayList(Arrays.asList(b, a)); - } -} diff --git a/app/src/main/java/io/pslab/filters/Lfilter.java b/app/src/main/java/io/pslab/filters/Lfilter.java deleted file mode 100644 index 74f850086..000000000 --- a/app/src/main/java/io/pslab/filters/Lfilter.java +++ /dev/null @@ -1,64 +0,0 @@ -package io.pslab.filters; - -import android.util.Log; - -/** - * Created by akarshan on 6/1/17. - */ - -public class Lfilter { - String TAG = "Lfilter"; - public double[] filter(double[] b, double[] a, double[] x) { - double[] filter = null; - double[] a1 = getRealArrayScalarDiv(a,a[0]); - double[] b1 = getRealArrayScalarDiv(b,a[0]); - int sx = x.length; - filter = new double[sx]; - filter[0] = b1[0]*x[0]; - for (int i = 1; i < sx; i++) { - filter[i] = 0.0; - for (int j = 0; j <= i; j++) { - int k = i-j; - if (j > 0) { - if ((k < b1.length) && (j < x.length)) { - filter[i] += b1[k]*x[j]; - } - if ((k < filter.length) && (j < a1.length)) { - filter[i] -= a1[j]*filter[k]; - } - } else { - if ((k < b1.length) && (j < x.length)) { - filter[i] += (b1[k]*x[j]); - } - } - } - } - return filter; - } - - private double[] getRealArrayScalarDiv(double[] dDividend, double dDivisor) { - if (dDividend == null) - Log.v(TAG, "The array must be defined or different to null"); - if (dDividend.length == 0) { - Log.v(TAG, "The size array must be greater than Zero"); - } - double[] dQuotient = new double[dDividend.length]; - - for (int i = 0; i < dDividend.length; i++) { - if (!(dDivisor == 0.0)) { - dQuotient[i] = dDividend[i]/dDivisor; - } else { - if (dDividend[i] > 0.0) { - dQuotient[i] = Double.POSITIVE_INFINITY; - } - if (dDividend[i] == 0.0) { - dQuotient[i] = Double.NaN; - } - if (dDividend[i] < 0.0) { - dQuotient[i] = Double.NEGATIVE_INFINITY; - } - } - } - return dQuotient; - } -} diff --git a/app/src/main/java/io/pslab/fragment/AboutUsFragment.java b/app/src/main/java/io/pslab/fragment/AboutUsFragment.java deleted file mode 100644 index c9c63d911..000000000 --- a/app/src/main/java/io/pslab/fragment/AboutUsFragment.java +++ /dev/null @@ -1,104 +0,0 @@ -package io.pslab.fragment; - - -import android.content.Intent; -import android.content.res.Configuration; -import android.net.Uri; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; - -import androidx.appcompat.app.AppCompatDelegate; -import androidx.fragment.app.Fragment; - -import com.google.android.material.appbar.AppBarLayout; - -import io.pslab.R; - -import butterknife.BindView; -import butterknife.ButterKnife; -import mehdi.sakout.aboutpage.AboutPage; -import mehdi.sakout.aboutpage.Element; - - -public class AboutUsFragment extends Fragment { - - @BindView(R.id.appBarAnim) - AppBarLayout appBarLayout; - - public static AboutUsFragment newInstance() { - return new AboutUsFragment(); - } - - public AboutUsFragment() { - } - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_about_us, container, false); - simulateDayNight(3); - ButterKnife.bind(this, view); - View aboutPage = new AboutPage(getActivity()) - .isRTL(false) - .setImage(R.drawable.logo200x200) - .addWebsite("https://goo.gl/forms/sHlmRAPFmzcGQ27u2", getString(R.string.nav_report)) - .addItem(new Element(getString(R.string.version), R.drawable.ic_widgets_black_24dp)) - .setDescription(getString(R.string.about_us_description)) - .addGroup("Connect with us") - .addEmail("pslab-fossasia@googlegroups.com") - .addWebsite("https://pslab.io/") - .addGitHub("fossasia?utf8=✓&q=pslab") - .addFacebook("pslabio") - .addTwitter("pslabio") - .addYoutube("UCQprMsG-raCIMlBudm20iLQ") - .addItem(addDevelopers()) - .create(); - - appBarLayout.addView(aboutPage, -1); - return view; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - return super.onOptionsItemSelected(item); - } - - private void simulateDayNight(int currentSetting) { - final int DAY = 0; - final int NIGHT = 1; - final int FOLLOW_SYSTEM = 3; - - int currentNightMode = getResources().getConfiguration().uiMode - & Configuration.UI_MODE_NIGHT_MASK; - if (currentSetting == DAY && currentNightMode != Configuration.UI_MODE_NIGHT_NO) { - AppCompatDelegate.setDefaultNightMode( - AppCompatDelegate.MODE_NIGHT_NO); - } else if (currentSetting == NIGHT && currentNightMode != Configuration.UI_MODE_NIGHT_YES) { - AppCompatDelegate.setDefaultNightMode( - AppCompatDelegate.MODE_NIGHT_YES); - } else if (currentSetting == FOLLOW_SYSTEM) { - AppCompatDelegate.setDefaultNightMode( - AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); - } - } - - private Element addDevelopers() { - Element developersElement = new Element(); - developersElement.setTitle(getString(R.string.developers)); - developersElement.setIconDrawable(R.drawable.ic_user__24dp); - developersElement.setOnClickListener(v -> { - String url = getString(R.string.github_developers_link); - if (!url.startsWith("http://") && !url.startsWith("https://")) { - url = "https://" + url; - } - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); - startActivity(browserIntent); - }); - return developersElement; - } - -} diff --git a/app/src/main/java/io/pslab/fragment/AccelerometerDataFragment.java b/app/src/main/java/io/pslab/fragment/AccelerometerDataFragment.java deleted file mode 100644 index 197910e0a..000000000 --- a/app/src/main/java/io/pslab/fragment/AccelerometerDataFragment.java +++ /dev/null @@ -1,497 +0,0 @@ -package io.pslab.fragment; - -import android.graphics.Bitmap; -import android.graphics.Color; -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; -import android.location.Location; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import androidx.annotation.NonNull; - -import com.google.android.material.snackbar.Snackbar; -import androidx.fragment.app.Fragment; - -import android.text.Html; -import android.util.Pair; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Timer; -import java.util.TimerTask; - -import io.pslab.R; -import io.pslab.activity.AccelerometerActivity; -import io.pslab.interfaces.OperationCallback; -import io.pslab.models.AccelerometerData; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; - -import static android.content.Context.SENSOR_SERVICE; -import static io.pslab.others.CSVLogger.CSV_DIRECTORY; - -/** - * Created by Kunal on 18-12-18 - */ - -public class AccelerometerDataFragment extends Fragment implements OperationCallback { - - private static final CSVDataLine CSV_HEADER = new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("ReadingsX") - .add("ReadingsY") - .add("ReadingsZ") - .add("Latitude") - .add("Longitude"); - private static int updatePeriod = 1000; - private static float highLimit = 1.2f; - private static float gain = 1; - private int turns = 0; - private boolean returningFromPause = false; - private Timer graphTimer; - private SensorManager sensorManager; - private Sensor sensor; - private long startTime, block; - private AccelerometerData sensorData; - private ArrayList recordedAccelerometerArray; - private AccelerometerActivity accelerometerSensor; - private ArrayList accelerometerViewFragments = new ArrayList<>(); - private int[] colors = {Color.YELLOW, Color.MAGENTA, Color.GREEN}; - private DecimalFormat df = new DecimalFormat("+#0.0;-#0.0"); - private View rootView; - - public static AccelerometerDataFragment newInstance() { - return new AccelerometerDataFragment(); - } - - public static void setParameters(float highLimit, int updatePeriod, String gain) { - AccelerometerDataFragment.highLimit = highLimit; - AccelerometerDataFragment.updatePeriod = updatePeriod; - AccelerometerDataFragment.gain = Integer.valueOf(gain); - } - - public static Pair> getParameters() { - return new Pair<>(updatePeriod, new Pair<>(highLimit, gain)); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - startTime = System.currentTimeMillis(); - accelerometerSensor = (AccelerometerActivity) getActivity(); - for (AccelerometerViewFragment fragment : accelerometerViewFragments) { - fragment.clear(); - } - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_accelerometer_data, container, false); - accelerometerViewFragments.clear(); - accelerometerViewFragments.add((AccelerometerViewFragment) getChildFragmentManager().findFragmentById(R.id.accelerometer_x_axis_fragment)); - accelerometerViewFragments.add((AccelerometerViewFragment) getChildFragmentManager().findFragmentById(R.id.accelerometer_y_axis_fragment)); - accelerometerViewFragments.add((AccelerometerViewFragment) getChildFragmentManager().findFragmentById(R.id.accelerometer_z_axis_fragment)); - - accelerometerViewFragments.get(1).getAccelerationAxisImage().setImageResource(R.drawable.phone_y_axis); - accelerometerViewFragments.get(2).getAccelerationAxisImage().setImageResource(R.drawable.phone_z_axis); - - setupInstruments(); - return rootView; - } - - @Override - public void onResume() { - super.onResume(); - if (accelerometerSensor.playingData) { - recordedAccelerometerArray = new ArrayList<>(); - resetInstrumentData(); - playRecordedData(); - } else if (accelerometerSensor.viewingData) { - recordedAccelerometerArray = new ArrayList<>(); - resetInstrumentData(); - plotAllRecordedData(); - } else if (!accelerometerSensor.isRecording) { - updateGraphs(); - initiateAccelerometerSensor(); - } else if (returningFromPause) { - updateGraphs(); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - if (graphTimer != null) { - graphTimer.cancel(); - } - if (sensorManager != null) { - sensorManager.unregisterListener(accelerometerSensorEventListener); - } - } - - private void plotAllRecordedData() { - recordedAccelerometerArray.addAll(accelerometerSensor.recordedAccelerometerData); - if (recordedAccelerometerArray.size() != 0) { - for (int i = 0; i < accelerometerViewFragments.size(); i++) { - AccelerometerViewFragment fragment = accelerometerViewFragments.get(i); - for (AccelerometerData d : recordedAccelerometerArray) { - if (fragment.getCurrentMax() < d.getAccelerometer()[i]) { - fragment.setCurrentMax(d.getAccelerometer()[i]); - } - if (fragment.getCurrentMin() > d.getAccelerometer()[i]) { - fragment.setCurrentMin(d.getAccelerometer()[i]); - } - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAccelerometer()[i]); - fragment.addEntry(entry); - } - - fragment.setYaxis(highLimit); - - LineDataSet dataSet = new LineDataSet(fragment.getEntries(), getString(R.string.accelerometer)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet.setLineWidth(1); - dataSet.setColor(colors[i]); - LineData data = new LineData(dataSet); - fragment.setChartData(data); - } - } - } - - private void playRecordedData() { - recordedAccelerometerArray.addAll(accelerometerSensor.recordedAccelerometerData); - try { - if (recordedAccelerometerArray.size() > 1) { - AccelerometerData i = recordedAccelerometerArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - private void processRecordedData(long timeGap) { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } else { - graphTimer = new Timer(); - } - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - if (accelerometerSensor.viewingData) { - try { - AccelerometerData d = recordedAccelerometerArray.get(turns); - turns++; - for (int i = 0; i < accelerometerViewFragments.size(); i++) { - AccelerometerViewFragment fragment = accelerometerViewFragments.get(i); - StringBuilder builder = new StringBuilder(); - builder.append(df.format(d.getAccelerometer()[i])); - builder.append(" "); - builder.append(getResources().getString(R.string.acceleration_unit)); - fragment.setAccelerationValue(Html.fromHtml(builder.toString())); - - if (fragment.getCurrentMax() < d.getAccelerometer()[i]) { - fragment.setCurrentMax(d.getAccelerometer()[i]); - StringBuilder max_builder = new StringBuilder(); - max_builder.append("Max: "); - max_builder.append(df.format(fragment.getCurrentMax())); - max_builder.append(" "); - max_builder.append(getResources().getString(R.string.acceleration_unit)); - fragment.setAccelerationMax(Html.fromHtml(max_builder.toString())); - } - if (fragment.getCurrentMin() > d.getAccelerometer()[i]) { - fragment.setCurrentMin(d.getAccelerometer()[i]); - StringBuilder min_builder = new StringBuilder(); - min_builder.append("Min: "); - min_builder.append(df.format(fragment.getCurrentMax())); - min_builder.append(" "); - min_builder.append(getResources().getString(R.string.acceleration_unit)); - fragment.setAccelerationMin(Html.fromHtml(min_builder.toString())); - } - - fragment.setYaxis(highLimit); - Entry entryX = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAccelerometer()[i]); - fragment.addEntry(entryX); - - LineDataSet dataSet = new LineDataSet(fragment.getEntries(), getString(R.string.accelerometer)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet.setLineWidth(1); - dataSet.setColor(colors[i]); - LineData data = new LineData(dataSet); - - fragment.setChartData(data); - } - } catch (IndexOutOfBoundsException e) { - graphTimer.cancel(); - graphTimer = null; - turns = 0; - accelerometerSensor.playingData = false; - accelerometerSensor.startedPlay = false; - accelerometerSensor.invalidateOptionsMenu(); - } - } - } - }); - } - }, 0, timeGap); - } - - @Override - public void playData() { - resetInstrumentData(); - accelerometerSensor.startedPlay = true; - try { - if (recordedAccelerometerArray.size() > 1) { - AccelerometerData i = recordedAccelerometerArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getActivity().getResources().getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - @Override - public void stopData() { - if (graphTimer != null) { - graphTimer.cancel(); - graphTimer = null; - } - recordedAccelerometerArray.clear(); - for (AccelerometerViewFragment fragment : accelerometerViewFragments) { - fragment.clearEntry(); - } - plotAllRecordedData(); - accelerometerSensor.startedPlay = false; - accelerometerSensor.playingData = false; - turns = 0; - accelerometerSensor.invalidateOptionsMenu(); - } - - @Override - public void saveGraph() { - accelerometerSensor.csvLogger.prepareLogFile(); - accelerometerSensor.csvLogger.writeMetaData(getResources().getString(R.string.accelerometer)); - accelerometerSensor.csvLogger.writeCSVFile(CSV_HEADER); - for (AccelerometerData accelerometerData : accelerometerSensor.recordedAccelerometerData) { - accelerometerSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(accelerometerData.getTime()) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(accelerometerData.getTime()))) - .add(accelerometerData.getAccelerometerX()) - .add(accelerometerData.getAccelerometerY()) - .add(accelerometerData.getAccelerometerZ()) - .add(accelerometerData.getLat()) - .add(accelerometerData.getLon()) - ); - } - View view = rootView.findViewById(R.id.accelerometer_linearlayout); - view.setDrawingCacheEnabled(true); - Bitmap b = view.getDrawingCache(); - try { - b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + accelerometerSensor.getSensorName() + - File.separator + CSVLogger.FILE_NAME_FORMAT.format(new Date()) + "_graph.jpg")); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - private void setupInstruments() { - for (AccelerometerViewFragment fragment : accelerometerViewFragments) { - fragment.setUp(); - } - } - - @Override - public void onPause() { - super.onPause(); - if (graphTimer != null) { - returningFromPause = true; - graphTimer.cancel(); - graphTimer = null; - if (accelerometerSensor.playingData) { - accelerometerSensor.finish(); - } - } - } - - private void updateGraphs() { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } - graphTimer = new Timer(); - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - try { - visualizeData(); - } catch (NullPointerException e) { - /* Pass for another refresh round */ - } - } - }); - } - }, 0, updatePeriod); - } - - private void writeLogToFile(long timestamp, float readingX, float readingY, float readingZ) { - if (getActivity() != null && accelerometerSensor.isRecording) { - if (accelerometerSensor.writeHeaderToFile) { - accelerometerSensor.csvLogger.prepareLogFile(); - accelerometerSensor.csvLogger.writeMetaData(getResources().getString(R.string.accelerometer)); - accelerometerSensor.csvLogger.writeCSVFile(CSV_HEADER); - block = timestamp; - accelerometerSensor.recordSensorDataBlockID(new SensorDataBlock(timestamp, accelerometerSensor.getSensorName())); - accelerometerSensor.writeHeaderToFile = !accelerometerSensor.writeHeaderToFile; - } - if (accelerometerSensor.addLocation && accelerometerSensor.gpsLogger.isGPSEnabled()) { - Location location = accelerometerSensor.gpsLogger.getDeviceLocation(); - accelerometerSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(readingX) - .add(readingY) - .add(readingZ) - .add(location.getLatitude()) - .add(location.getLongitude()) - ); - sensorData = new AccelerometerData(timestamp, block, accelerometerViewFragments.get(0).getCurrentValue(), accelerometerViewFragments.get(1).getCurrentValue(), accelerometerViewFragments.get(2).getCurrentValue(), location.getLatitude(), location.getLongitude()); - } else { - accelerometerSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(readingX) - .add(readingY) - .add(readingZ) - .add(0.0) - .add(0.0) - ); - sensorData = new AccelerometerData(timestamp, block, accelerometerViewFragments.get(0).getCurrentValue(), accelerometerViewFragments.get(1).getCurrentValue(), accelerometerViewFragments.get(2).getCurrentValue(), 0.0, 0.0); - } - accelerometerSensor.recordSensorData(sensorData); - } else { - accelerometerSensor.writeHeaderToFile = true; - } - } - - private void visualizeData() { - for (int i = 0; i < accelerometerViewFragments.size(); i++) { - AccelerometerViewFragment fragment = accelerometerViewFragments.get(i); - long timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - if (timeElapsed != fragment.getPreviousTimeElapsed()) { - fragment.setPreviousTimeElapsed(timeElapsed); - fragment.addEntry(new Entry((float) timeElapsed, fragment.getCurrentValue())); - - LineDataSet dataSet = new LineDataSet(fragment.getEntries(), getString(R.string.accelerometer)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet.setLineWidth(1); - dataSet.setColor(colors[i]); - LineData data = new LineData(dataSet); - - fragment.setChartData(data); - fragment.setYaxis(highLimit); - } - } - Long currentTime = System.currentTimeMillis(); - writeLogToFile(currentTime, accelerometerViewFragments.get(0).getCurrentValue(), accelerometerViewFragments.get(1).getCurrentValue(), accelerometerViewFragments.get(2).getCurrentValue()); - } - - private SensorEventListener accelerometerSensorEventListener = new SensorEventListener() { - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) {/**/} - - @Override - public void onSensorChanged(SensorEvent event) { - if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { - for (int i = 0; i < accelerometerViewFragments.size(); i++) { - AccelerometerViewFragment fragment = accelerometerViewFragments.get(i); - fragment.setCurrentValue(event.values[i]); - StringBuilder builder = new StringBuilder(); - builder.append(df.format(fragment.getCurrentValue())); - builder.append(" "); - builder.append(getResources().getString(R.string.acceleration_unit)); - fragment.setAccelerationValue(Html.fromHtml(builder.toString())); - - if (fragment.getCurrentValue() > fragment.getCurrentMax()) { - builder.insert(0, getResources().getString(R.string.text_max)); - builder.insert(3, " "); - fragment.setAccelerationMax(Html.fromHtml(builder.toString())); - fragment.setCurrentMax(fragment.getCurrentValue()); - } else if (fragment.getCurrentValue() < fragment.getCurrentMin()) { - builder.insert(0, getResources().getString(R.string.text_min)); - builder.insert(3, " "); - fragment.setAccelerationMin(Html.fromHtml(builder.toString())); - fragment.setCurrentMin(fragment.getCurrentValue()); - } - } - } - } - }; - - private void resetInstrumentData() { - for (AccelerometerViewFragment fragment : accelerometerViewFragments) { - fragment.clear(); - } - } - - private void initiateAccelerometerSensor() { - resetInstrumentData(); - sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE); - sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); - if (sensor == null) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getResources().getString(R.string.no_accelerometer_sensor), null, null, Snackbar.LENGTH_LONG); - } else { - sensorManager.registerListener(accelerometerSensorEventListener, - sensor, SensorManager.SENSOR_DELAY_FASTEST); - } - - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/fragment/AccelerometerSettingsFragment.java b/app/src/main/java/io/pslab/fragment/AccelerometerSettingsFragment.java deleted file mode 100644 index 0700ad869..000000000 --- a/app/src/main/java/io/pslab/fragment/AccelerometerSettingsFragment.java +++ /dev/null @@ -1,123 +0,0 @@ -package io.pslab.fragment; - -import android.annotation.SuppressLint; -import android.content.SharedPreferences; -import android.os.Bundle; -import androidx.preference.CheckBoxPreference; -import androidx.preference.EditTextPreference; -import androidx.preference.ListPreference; -import androidx.preference.PreferenceFragmentCompat; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.others.PSLabPermission; - -/** - * Created by Kunal on 18-12-2018. - */ -public class AccelerometerSettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { - - public static final String KEY_INCLUDE_LOCATION = "include_location_sensor_data"; - public static final String KEY_UPDATE_PERIOD = "setting_accelerometer_update_period"; - public static final String KEY_HIGH_LIMIT = "setting_accelerometer_high_limit"; - public static final String KEY_ACCELEROMETER_SENSOR_TYPE = "setting_accelerometer_sensor_type"; - public static final String KEY_ACCELEROMETER_SENSOR_GAIN = "setting_accelerometer_sensor_gain"; - - private PSLabPermission psLabPermission; - - private EditTextPreference updatePeriodPref; - private EditTextPreference higLimitPref; - private EditTextPreference sensorGainPref; - private CheckBoxPreference locationPreference; - private ListPreference sensorTypePreference; - private SharedPreferences sharedPref; - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - setPreferencesFromResource(R.xml.accelerometer_settings, rootKey); - updatePeriodPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_UPDATE_PERIOD); - higLimitPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_HIGH_LIMIT); - sensorGainPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_ACCELEROMETER_SENSOR_GAIN); - locationPreference = (CheckBoxPreference) getPreferenceScreen().findPreference(KEY_INCLUDE_LOCATION); - sensorTypePreference = (ListPreference) getPreferenceScreen().findPreference(KEY_ACCELEROMETER_SENSOR_TYPE); - sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); - - psLabPermission = PSLabPermission.getInstance(); - if (!psLabPermission.checkPermissions(getActivity(), PSLabPermission.MAP_PERMISSION)) { - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putBoolean(LuxMeterSettingFragment.KEY_INCLUDE_LOCATION, true); - editor.apply(); - } - } - - @Override - public void onResume() { - super.onResume(); - locationPreference.setChecked(sharedPref.getBoolean(KEY_INCLUDE_LOCATION, true)); - updatePeriodPref.setSummary(updatePeriodPref.getText() + " ms"); - higLimitPref.setSummary(higLimitPref.getText() + " m/s²"); - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - sensorGainPref.setSummary(sensorGainPref.getText()); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); - } - - @SuppressLint("ApplySharedPref") - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { - switch (s) { - case KEY_INCLUDE_LOCATION: - if (locationPreference.isChecked()) { - psLabPermission.checkPermissions( - getActivity(), PSLabPermission.MAP_PERMISSION); - } - break; - case KEY_UPDATE_PERIOD: - try { - Integer updatePeriod = Integer.valueOf(updatePeriodPref.getText()); - updatePeriodPref.setSummary(updatePeriod + " ms"); - } catch (NumberFormatException e) { - updatePeriodPref.setSummary("1000 ms"); - updatePeriodPref.setText("1000"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(s, "1000"); - editor.commit(); - } - break; - case KEY_ACCELEROMETER_SENSOR_GAIN: - try { - Integer gain = Integer.valueOf(sensorGainPref.getText()); - sensorGainPref.setSummary(String.valueOf(gain)); - } catch (NumberFormatException e) { - sensorGainPref.setSummary("1"); - sensorGainPref.setText("1"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(KEY_ACCELEROMETER_SENSOR_GAIN, "1"); - editor.commit(); - } - break; - case KEY_HIGH_LIMIT: - try { - Integer highLimit = Integer.valueOf(higLimitPref.getText()); - higLimitPref.setSummary(String.valueOf(highLimit)); - } catch (NumberFormatException e) { - higLimitPref.setSummary("2000 Lx"); - higLimitPref.setText("2000"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(KEY_HIGH_LIMIT, "2000"); - editor.commit(); - } - break; - case KEY_ACCELEROMETER_SENSOR_TYPE: - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - break; - default: - break; - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/AccelerometerViewFragment.java b/app/src/main/java/io/pslab/fragment/AccelerometerViewFragment.java deleted file mode 100644 index 9af1d239c..000000000 --- a/app/src/main/java/io/pslab/fragment/AccelerometerViewFragment.java +++ /dev/null @@ -1,188 +0,0 @@ -package io.pslab.fragment; - -import android.content.Context; -import android.graphics.Color; -import android.os.Bundle; -import androidx.fragment.app.Fragment; - -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; - -import java.util.ArrayList; - -import io.pslab.R; - -public class AccelerometerViewFragment extends Fragment { - - private TextView accelerationValue, accelerationMin, accelerationMax; - private LineChart accelerationChart; - private ImageView accelerationAxisImage; - private YAxis y; - private float currentMax = Integer.MIN_VALUE; - private float currentMin = Integer.MAX_VALUE; - private float currentValue = 0; - private ArrayList entries; - private long startTime; - private static int updatePeriod = 100; - private long previousTimeElapsed = (System.currentTimeMillis() - startTime) / updatePeriod; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.accelerometer_list_item, container, false); - - this.accelerationValue = rootView.findViewById(R.id.acceleration_value); - this.accelerationMax = rootView.findViewById(R.id.acceleration_max_text); - this.accelerationMin = rootView.findViewById(R.id.acceleration_min_text); - this.accelerationChart = rootView.findViewById(R.id.chart_accelerometer); - this.accelerationAxisImage = rootView.findViewById(R.id.acceleration_axis_image); - this.entries = new ArrayList<>(); - return rootView; - } - - @Override - public void onAttach(Context context) { - super.onAttach(context); - } - - @Override - public void onDetach() { - super.onDetach(); - } - - public ImageView getAccelerationAxisImage() { - return accelerationAxisImage; - } - - public float getCurrentMax() { - return currentMax; - } - - public void setCurrentMax(float currentMax) { - this.currentMax = currentMax; - } - - public float getCurrentMin() { - return currentMin; - } - - public void setCurrentMin(float currentMin) { - this.currentMin = currentMin; - } - - public float getCurrentValue() { - return currentValue; - } - - public void setCurrentValue(float currentValue) { - this.currentValue = currentValue; - } - - public void setUp() { - XAxis x = this.accelerationChart.getXAxis(); - this.y = this.accelerationChart.getAxisLeft(); - YAxis y2 = this.accelerationChart.getAxisRight(); - - this.accelerationChart.setTouchEnabled(true); - this.accelerationChart.setHighlightPerDragEnabled(true); - this.accelerationChart.setDragEnabled(true); - this.accelerationChart.setScaleEnabled(true); - this.accelerationChart.setDrawGridBackground(false); - this.accelerationChart.setPinchZoom(true); - this.accelerationChart.setScaleYEnabled(true); - this.accelerationChart.setBackgroundColor(Color.BLACK); - this.accelerationChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - this.accelerationChart.setData(data); - - Legend l = this.accelerationChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - x.setDrawLabels(false); - - this.y.setTextColor(Color.WHITE); - this.y.setAxisMaximum(currentMax); - this.y.setAxisMinimum(currentMin); - this.y.setDrawGridLines(true); - this.y.setLabelCount(10); - - y2.setDrawGridLines(false); - y2.setMaxWidth(0); - } - - public void addEntry(Entry entry) { - this.entries.add(entry); - } - - public ArrayList getEntries() { - return this.entries; - } - - public void clearEntry() { - this.entries.clear(); - } - - public void setAccelerationValue(CharSequence value) { - this.accelerationValue.setText(value); - } - - public void setAccelerationMax(CharSequence value) { - this.accelerationMax.setText(value); - } - - public void setAccelerationMin(CharSequence value) { - this.accelerationMin.setText(value); - } - - public void setYaxis(float maxLimit) { - this.y.setAxisMaximum(maxLimit); - this.y.setAxisMinimum(-maxLimit); - this.y.setLabelCount(5); - } - - public void setChartData(LineData data) { - this.accelerationChart.setData(data); - this.accelerationChart.notifyDataSetChanged(); - this.accelerationChart.setVisibleXRangeMaximum(3); - this.accelerationChart.moveViewToX(data.getEntryCount()); - this.accelerationChart.invalidate(); - } - - public void clear() { - this.currentMax = Integer.MIN_VALUE; - this.currentMin = Integer.MAX_VALUE; - this.entries.clear(); - this.accelerationChart.clear(); - this.accelerationChart.invalidate(); - this.startTime = System.currentTimeMillis(); - } - - public long getPreviousTimeElapsed() { - return previousTimeElapsed; - } - - public void setPreviousTimeElapsed(long previousTimeElapsed) { - this.previousTimeElapsed = previousTimeElapsed; - } -} diff --git a/app/src/main/java/io/pslab/fragment/BaroMeterDataFragment.java b/app/src/main/java/io/pslab/fragment/BaroMeterDataFragment.java deleted file mode 100644 index 6238e1c88..000000000 --- a/app/src/main/java/io/pslab/fragment/BaroMeterDataFragment.java +++ /dev/null @@ -1,666 +0,0 @@ -package io.pslab.fragment; - -import android.graphics.Bitmap; -import android.graphics.Color; -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; -import android.location.Location; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import androidx.annotation.NonNull; - -import com.google.android.material.snackbar.Snackbar; -import androidx.fragment.app.Fragment; - -import androidx.preference.PreferenceManager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.github.anastr.speedviewlib.PointerSpeedometer; -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; -import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Timer; -import java.util.TimerTask; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.activity.BarometerActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.BMP180; -import io.pslab.interfaces.OperationCallback; -import io.pslab.models.BaroData; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.ScienceLabCommon; - -import static android.content.Context.SENSOR_SERVICE; -import static io.pslab.others.CSVLogger.CSV_DIRECTORY; - -/** - * Created by Padmal on 12/13/18. - */ - -public class BaroMeterDataFragment extends Fragment implements OperationCallback { - - private static final CSVDataLine CSV_HEADER = new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("Pressure") - .add("Altitude") - .add("Latitude") - .add("Longitude"); - - private static int sensorType = 0; - private static float highLimit = 1.2f; - private static int updatePeriod = 1000; - private long timeElapsed; - private int count = 0, turns = 0; - private float sum = 0; - private boolean returningFromPause = false; - - private float baroValue = -1; - - private enum BARO_SENSOR {INBUILT_SENSOR, BMP180_SENSOR} - - @BindView(R.id.baro_max) - TextView statMax; - @BindView(R.id.baro_min) - TextView statMin; - @BindView(R.id.baro_avg) - TextView statMean; - @BindView(R.id.label_baro_sensor) - TextView sensorLabel; - @BindView(R.id.chart_baro_meter) - LineChart mChart; - @BindView(R.id.baro_meter) - PointerSpeedometer baroMeter; - @BindView(R.id.alti_value) - TextView altiValue; - - private Timer graphTimer; - private SensorManager sensorManager; - private Sensor sensor; - private long startTime, block; - private ArrayList pressureEntries; - private ArrayList altitudeEntries; - private ArrayList recordedBaroArray; - private BaroData sensorData; - private float currentMin = 2; - private float currentMax = 0.5f; - private YAxis y; - private YAxis y2; - private Unbinder unbinder; - private long previousTimeElapsed = (System.currentTimeMillis() - startTime) / updatePeriod; - private BarometerActivity baroSensor; - private View rootView; - - public static BaroMeterDataFragment newInstance() { - return new BaroMeterDataFragment(); - } - - public static void setParameters(float highLimit, int updatePeriod, String type) { - BaroMeterDataFragment.highLimit = highLimit; - BaroMeterDataFragment.updatePeriod = updatePeriod; - BaroMeterDataFragment.sensorType = Integer.valueOf(type); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - startTime = System.currentTimeMillis(); - pressureEntries = new ArrayList<>(); - altitudeEntries = new ArrayList<>(); - baroSensor = (BarometerActivity) getActivity(); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_barometer_data, container, false); - unbinder = ButterKnife.bind(this, rootView); - setupInstruments(); - return rootView; - } - - @Override - public void onResume() { - super.onResume(); - if (baroSensor.playingData) { - sensorLabel.setText(getResources().getString(R.string.baro_meter)); - recordedBaroArray = new ArrayList<>(); - resetInstrumentData(); - playRecordedData(); - } else if (baroSensor.viewingData) { - sensorLabel.setText(getResources().getString(R.string.baro_meter)); - recordedBaroArray = new ArrayList<>(); - resetInstrumentData(); - plotAllRecordedData(); - } else if (!baroSensor.isRecording) { - updateGraphs(); - sum = 0; - count = 0; - currentMin = 2; - currentMax = 0.5f; - pressureEntries.clear(); - altitudeEntries.clear(); - mChart.clear(); - mChart.invalidate(); - initiateBaroSensor(sensorType); - } else if (returningFromPause) { - updateGraphs(); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - if (graphTimer != null) { - graphTimer.cancel(); - } - if (sensorManager != null) { - sensorManager.unregisterListener(baroSensorEventListener); - } - unbinder.unbind(); - } - - private void plotAllRecordedData() { - recordedBaroArray.addAll(baroSensor.recordedBaroData); - if (recordedBaroArray.size() != 0) { - for (BaroData d : recordedBaroArray) { - if (currentMax < d.getBaro()) { - currentMax = d.getBaro(); - } - if (currentMin > d.getBaro()) { - currentMin = d.getBaro(); - } - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getBaro()); - pressureEntries.add(entry); - altitudeEntries.add(new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAltitude())); - altiValue.setText(String.format(Locale.getDefault(), PSLabSensor.BAROMETER_DATA_FORMAT, d.getAltitude())); - baroMeter.setWithTremble(false); - baroMeter.setSpeedAt(d.getBaro()); - sum += entry.getY(); - } - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setLabelCount(10); - y2.setAxisMaximum(getAltitude(currentMax)); - y2.setAxisMinimum(getAltitude(currentMin)); - y2.setLabelCount(10); - statMax.setText(String.format(Locale.getDefault(), PSLabSensor.BAROMETER_DATA_FORMAT, currentMax)); - statMin.setText(String.format(Locale.getDefault(), PSLabSensor.BAROMETER_DATA_FORMAT, currentMin)); - statMean.setText(String.format(Locale.getDefault(), PSLabSensor.BAROMETER_DATA_FORMAT, (sum / recordedBaroArray.size()))); - - List dataSets = new ArrayList<>(); - LineDataSet dataSet = new LineDataSet(pressureEntries, getString(R.string.baro_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - dataSets.add(dataSet); - - dataSet = new LineDataSet(altitudeEntries, getString(R.string.alti_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - dataSet.setColor(Color.YELLOW); - dataSets.add(dataSet); - LineData data = new LineData(dataSets); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } - } - - private void playRecordedData() { - recordedBaroArray.addAll(baroSensor.recordedBaroData); - try { - if (recordedBaroArray.size() > 1) { - BaroData i = recordedBaroArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getActivity().getResources().getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - private void processRecordedData(long timeGap) { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } else { - graphTimer = new Timer(); - } - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - if (baroSensor.playingData) { - try { - BaroData d = recordedBaroArray.get(turns); - turns++; - if (currentMax < d.getBaro()) { - currentMax = d.getBaro(); - statMax.setText(String.format(Locale.getDefault(), PSLabSensor.BAROMETER_DATA_FORMAT, d.getBaro())); - } - if (currentMin > d.getBaro()) { - currentMin = d.getBaro(); - statMin.setText(String.format(Locale.getDefault(), PSLabSensor.BAROMETER_DATA_FORMAT, d.getBaro())); - } - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setLabelCount(10); - y2.setAxisMaximum(getAltitude(currentMax)); - y2.setAxisMinimum(getAltitude(currentMin)); - y2.setLabelCount(10); - baroMeter.setWithTremble(false); - baroMeter.setSpeedAt(d.getBaro()); - - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getBaro()); - pressureEntries.add(entry); - altitudeEntries.add(new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAltitude())); - count++; - sum += entry.getY(); - statMean.setText(DataFormatter.formatDouble((sum / count), PSLabSensor.BAROMETER_DATA_FORMAT)); - altiValue.setText(String.format(Locale.getDefault(), PSLabSensor.BAROMETER_DATA_FORMAT, d.getAltitude())); - - List dataSets = new ArrayList<>(); - LineDataSet dataSet = new LineDataSet(pressureEntries, getString(R.string.baro_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - dataSets.add(dataSet); - - dataSet = new LineDataSet(altitudeEntries, getString(R.string.alti_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - dataSet.setColor(Color.YELLOW); - dataSets.add(dataSet); - LineData data = new LineData(dataSets); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } catch (IndexOutOfBoundsException e) { - graphTimer.cancel(); - graphTimer = null; - turns = 0; - baroSensor.playingData = false; - baroSensor.startedPlay = false; - baroSensor.invalidateOptionsMenu(); - } - } - } - }); - } - }, 0, timeGap); - } - - @Override - public void playData() { - resetInstrumentData(); - baroSensor.startedPlay = true; - try { - if (recordedBaroArray.size() > 1) { - BaroData i = recordedBaroArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getActivity().getResources().getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - @Override - public void stopData() { - if (graphTimer != null) { - graphTimer.cancel(); - graphTimer = null; - } - recordedBaroArray.clear(); - pressureEntries.clear(); - plotAllRecordedData(); - baroSensor.startedPlay = false; - baroSensor.playingData = false; - turns = 0; - baroSensor.invalidateOptionsMenu(); - } - - @Override - public void saveGraph() { - baroSensor.csvLogger.prepareLogFile(); - baroSensor.csvLogger.writeMetaData(getResources().getString(R.string.baro_meter)); - baroSensor.csvLogger.writeCSVFile(CSV_HEADER); - for (BaroData baroData : baroSensor.recordedBaroData) { - baroSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(baroData.getTime()) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(baroData.getTime()))) - .add(baroData.getBaro()) - .add(baroData.getAltitude()) - .add(baroData.getLat()) - .add(baroData.getLon()) - ); - } - View view = rootView.findViewById(R.id.barometer_linearlayout); - view.setDrawingCacheEnabled(true); - Bitmap b = view.getDrawingCache(); - try { - b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + baroSensor.getSensorName() + - File.separator + CSVLogger.FILE_NAME_FORMAT.format(new Date()) + "_graph.jpg")); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - private void setupInstruments() { - baroMeter.setMaxSpeed(PreferenceManager.getDefaultSharedPreferences(getActivity()).getFloat(baroSensor.BAROMETER_LIMIT, 2)); - XAxis x = mChart.getXAxis(); - this.y = mChart.getAxisLeft(); - this.y2 = mChart.getAxisRight(); - - mChart.setTouchEnabled(true); - mChart.setHighlightPerDragEnabled(true); - mChart.setDragEnabled(true); - mChart.setScaleEnabled(true); - mChart.setDrawGridBackground(false); - mChart.setPinchZoom(true); - mChart.setScaleYEnabled(true); - mChart.setBackgroundColor(Color.BLACK); - mChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - mChart.setData(data); - - Legend l = mChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setDrawGridLines(true); - y.setLabelCount(10); - - y2.setTextColor(Color.WHITE); - y2.setAxisMinimum(getAltitude(currentMin)); - y2.setAxisMaximum(getAltitude(currentMax)); - y2.setDrawGridLines(true); - y2.setLabelCount(10); - } - - @Override - public void onPause() { - super.onPause(); - if (graphTimer != null) { - returningFromPause = true; - graphTimer.cancel(); - graphTimer = null; - if (baroSensor.playingData) { - baroSensor.finish(); - } - } - } - - private void updateGraphs() { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } - graphTimer = new Timer(); - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - try { - visualizeData(); - } catch (NullPointerException e) { - /* Pass for another refresh round */ - } - } - }); - } - }, 0, updatePeriod); - } - - private void writeLogToFile(long timestamp, float sensorReading) { - if (getActivity() != null && baroSensor.isRecording) { - if (baroSensor.writeHeaderToFile) { - baroSensor.csvLogger.prepareLogFile(); - baroSensor.csvLogger.writeCSVFile(CSV_HEADER); - block = timestamp; - baroSensor.recordSensorDataBlockID(new SensorDataBlock(timestamp, baroSensor.getSensorName())); - baroSensor.writeHeaderToFile = !baroSensor.writeHeaderToFile; - } - if (baroSensor.addLocation && baroSensor.gpsLogger.isGPSEnabled()) { - Location location = baroSensor.gpsLogger.getDeviceLocation(); - baroSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(sensorReading) - .add(getAltitude(sensorReading)) - .add(location.getLatitude()) - .add(location.getLongitude()) - ); - sensorData = new BaroData(timestamp, block, baroValue, getAltitude(baroValue), location.getLatitude(), location.getLongitude()); - } else { - baroSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(sensorReading) - .add(getAltitude(sensorReading)) - .add(0.0) - .add(0.0) - ); - sensorData = new BaroData(timestamp, block, baroValue, getAltitude(baroValue), 0.0, 0.0); - } - baroSensor.recordSensorData(sensorData); - } else { - baroSensor.writeHeaderToFile = true; - } - } - - private void visualizeData() { - if (currentMax < baroValue) { - currentMax = baroValue; - statMax.setText(String.format(Locale.getDefault(), PSLabSensor.BAROMETER_DATA_FORMAT, baroValue)); - } - if (currentMin > baroValue) { - currentMin = baroValue; - statMin.setText(String.format(Locale.getDefault(), PSLabSensor.BAROMETER_DATA_FORMAT, baroValue)); - } - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setLabelCount(10); - y2.setAxisMaximum(getAltitude(currentMax)); - y2.setAxisMinimum(getAltitude(currentMin)); - y2.setLabelCount(10); - if (baroValue >= 0) { - baroMeter.setWithTremble(false); - baroMeter.setSpeedAt(baroValue); - if (baroValue > highLimit) - baroMeter.setPointerColor(Color.RED); - else - baroMeter.setPointerColor(Color.WHITE); - - timeElapsed = ((System.currentTimeMillis() - startTime) / updatePeriod); - if (timeElapsed != previousTimeElapsed) { - previousTimeElapsed = timeElapsed; - Entry entry = new Entry((float) timeElapsed, baroValue); - Long currentTime = System.currentTimeMillis(); - writeLogToFile(currentTime, baroValue); - pressureEntries.add(entry); - altitudeEntries.add(new Entry((float) timeElapsed, getAltitude(baroValue))); - - count++; - sum += entry.getY(); - statMean.setText(DataFormatter.formatDouble((sum / count), PSLabSensor.BAROMETER_DATA_FORMAT)); - altiValue.setText(String.format(Locale.getDefault(), PSLabSensor.BAROMETER_DATA_FORMAT, getAltitude(baroValue))); - - List dataSets = new ArrayList<>(); - LineDataSet dataSet = new LineDataSet(pressureEntries, getString(R.string.baro_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - dataSets.add(dataSet); - - dataSet = new LineDataSet(altitudeEntries, getString(R.string.alti_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - dataSet.setColor(Color.YELLOW); - dataSets.add(dataSet); - LineData data = new LineData(dataSets); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } - } - } - - private SensorEventListener baroSensorEventListener = new SensorEventListener() { - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) {/**/} - - @Override - public void onSensorChanged(SensorEvent event) { - if (event.sensor.getType() == Sensor.TYPE_PRESSURE) { - baroValue = Float.valueOf(String.format(Locale.ROOT, PSLabSensor.BAROMETER_DATA_FORMAT, event.values[0] / 1000)); - } - } - }; - - private void resetInstrumentData() { - baroValue = 0; - count = 0; - currentMin = 2; - currentMax = 0.5f; - sum = 0; - sensor = null; - if (sensorManager != null) { - sensorManager.unregisterListener(baroSensorEventListener); - } - startTime = System.currentTimeMillis(); - statMax.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - statMin.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - statMean.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - altiValue.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - baroMeter.setSpeedAt(0); - baroMeter.setWithTremble(false); - pressureEntries.clear(); - altitudeEntries.clear(); - } - - private void initiateBaroSensor(int type) { - BaroMeterDataFragment.BARO_SENSOR s = BaroMeterDataFragment.BARO_SENSOR.values()[type]; - resetInstrumentData(); - ScienceLab scienceLab; - switch (s) { - case INBUILT_SENSOR: - sensorLabel.setText(getResources().getStringArray(R.array.baro_sensors)[0]); - sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE); - sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); - if (sensor == null) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getResources().getString(R.string.no_baro_sensor), null, null, Snackbar.LENGTH_LONG); - } else { - float max = sensor.getMaximumRange() / 1000; - PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putFloat(baroSensor.BAROMETER_LIMIT, max).apply(); - baroMeter.setMaxSpeed(max); - sensorManager.registerListener(baroSensorEventListener, - sensor, SensorManager.SENSOR_DELAY_FASTEST); - } - break; - case BMP180_SENSOR: - sensorLabel.setText(getResources().getStringArray(R.array.baro_sensors)[1]); - scienceLab = ScienceLabCommon.scienceLab; - if (scienceLab.isConnected()) { - ArrayList data; - try { - I2C i2c = scienceLab.i2c; - data = i2c.scan(null); - if (data.contains(0x23)) { - BMP180 sensorBMP180 = new BMP180(i2c, scienceLab); - sensorBMP180.setOversampling(10); - sensorType = 0; - } else { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.sensor_not_connected_tls), null, null, Snackbar.LENGTH_SHORT); - sensorType = 0; - } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - } else { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.device_not_found), null, null, Snackbar.LENGTH_SHORT); - sensorType = 0; - } - break; - default: - break; - } - } - - private float getAltitude(float pressure) { - if (pressure <= 0.0) { - return 0; - } else { - return (float) (44330 * (1 - Math.pow(pressure, 1.0 / 5.255))); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/fragment/BaroMeterSettingsFragment.java b/app/src/main/java/io/pslab/fragment/BaroMeterSettingsFragment.java deleted file mode 100644 index 8f3f850f4..000000000 --- a/app/src/main/java/io/pslab/fragment/BaroMeterSettingsFragment.java +++ /dev/null @@ -1,119 +0,0 @@ -package io.pslab.fragment; - -import android.annotation.SuppressLint; -import android.content.SharedPreferences; -import android.os.Bundle; -import com.google.android.material.snackbar.Snackbar; -import androidx.preference.CheckBoxPreference; -import androidx.preference.EditTextPreference; -import androidx.preference.ListPreference; -import androidx.preference.PreferenceFragmentCompat; -import androidx.preference.PreferenceManager; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.PSLabPermission; - -public class BaroMeterSettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { - - public static final String KEY_INCLUDE_LOCATION = "include_location_sensor_data"; - public static final String KEY_UPDATE_PERIOD = "setting_baro_update_period"; - public static final String KEY_HIGH_LIMIT = "setting_baro_high_limit"; - public static final String KEY_BARO_SENSOR_TYPE = "setting_baro_sensor_type"; - - private PSLabPermission psLabPermission; - - private EditTextPreference updatePeriodPref; - private EditTextPreference highLimitPref; - private CheckBoxPreference locationPreference; - private ListPreference sensorTypePreference; - private SharedPreferences sharedPref; - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - setPreferencesFromResource(R.xml.baro_meter_settings, rootKey); - updatePeriodPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_UPDATE_PERIOD); - highLimitPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_HIGH_LIMIT); - locationPreference = (CheckBoxPreference) getPreferenceScreen().findPreference(KEY_INCLUDE_LOCATION); - sensorTypePreference = (ListPreference) getPreferenceScreen().findPreference(KEY_BARO_SENSOR_TYPE); - sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); - - psLabPermission = PSLabPermission.getInstance(); - if (!psLabPermission.checkPermissions(getActivity(), PSLabPermission.MAP_PERMISSION)) { - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putBoolean(BaroMeterSettingsFragment.KEY_INCLUDE_LOCATION, true); - editor.apply(); - } - } - - @Override - public void onResume() { - super.onResume(); - locationPreference.setChecked(sharedPref.getBoolean(KEY_INCLUDE_LOCATION, true)); - updatePeriodPref.setSummary(updatePeriodPref.getText() + " ms"); - highLimitPref.setSummary(highLimitPref.getText() + " atm"); - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); - } - - @SuppressLint("ApplySharedPref") - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { - switch (s) { - case KEY_INCLUDE_LOCATION: - if (locationPreference.isChecked()) { - psLabPermission.checkPermissions( - getActivity(), PSLabPermission.MAP_PERMISSION); - } - break; - case KEY_UPDATE_PERIOD: - try { - Integer updatePeriod = Integer.parseInt(updatePeriodPref.getText()); - if (updatePeriod > 2000 || updatePeriod < 100) { - throw new NumberFormatException(); - } else { - updatePeriodPref.setSummary(String.valueOf(updatePeriod) + " ms"); - } - } catch (NumberFormatException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.update_period_msg),null,null, Snackbar.LENGTH_SHORT); - updatePeriodPref.setSummary("1000 ms"); - updatePeriodPref.setText("1000"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(s, "1000"); - editor.commit(); - } - break; - case KEY_HIGH_LIMIT: - try { - double highLimit = Double.parseDouble(highLimitPref.getText()); - if (highLimit > 1.10 || highLimit < 0.00) { - throw new NumberFormatException(); - } else { - highLimitPref.setSummary(DataFormatter.formatDouble(highLimit, DataFormatter.LOW_PRECISION_FORMAT) + " atm"); - } - } catch (NumberFormatException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.high_limit_msg),null,null,Snackbar.LENGTH_SHORT); - highLimitPref.setSummary("1.10 atm"); - highLimitPref.setText("1.10"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(KEY_HIGH_LIMIT, "1.10"); - editor.commit(); - } - break; - case KEY_BARO_SENSOR_TYPE: - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - break; - default: - break; - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/BluetoothScanFragment.java b/app/src/main/java/io/pslab/fragment/BluetoothScanFragment.java deleted file mode 100644 index d6351bbdf..000000000 --- a/app/src/main/java/io/pslab/fragment/BluetoothScanFragment.java +++ /dev/null @@ -1,162 +0,0 @@ -package io.pslab.fragment; - -import android.bluetooth.BluetoothAdapter; -import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothSocket; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.ListView; -import android.widget.ProgressBar; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.fragment.app.DialogFragment; - -import com.google.android.material.snackbar.Snackbar; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import io.pslab.R; -import io.pslab.others.CustomSnackBar; - -public class BluetoothScanFragment extends DialogFragment { - private Button bluetoothScanStopButton; - private ProgressBar scanProgressBar; - private ListView scannedDevicesListView; - private ArrayAdapter deviceListAdapter; - private List deviceList; - private List bluetoothDevices; - private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (BluetoothDevice.ACTION_FOUND.equals(action)) { - BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); - if (device != null && !bluetoothDevices.contains(device)) { - String deviceName = device.getName(); - deviceList.add(deviceName == null ? device.getAddress() : deviceName); - bluetoothDevices.add(device); - deviceListAdapter.notifyDataSetChanged(); - } - } - } - }; - private BluetoothAdapter bluetoothAdapter; - private boolean startScanning = false; - private BluetoothDevice bluetoothDevice; - private BluetoothSocket mSocket; - private OutputStream mOutputStream; - private InputStream mInputStream; - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_bluetooth_scan, container, false); - scanProgressBar = rootView.findViewById(R.id.bluetooth_scan_progressbar); - scanProgressBar.setVisibility(View.GONE); - scannedDevicesListView = rootView.findViewById(R.id.bluetooth_scanned_devices_list); - deviceList = new ArrayList<>(); - bluetoothDevices = new ArrayList<>(); - deviceListAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, deviceList); - scannedDevicesListView.setAdapter(deviceListAdapter); - bluetoothScanStopButton = rootView.findViewById(R.id.bluetooth_scan_stop_button); - - - bluetoothScanStopButton.setOnClickListener(v -> { - if (startScanning) { - if (bluetoothAdapter != null) - bluetoothAdapter.cancelDiscovery(); - - scanProgressBar.setVisibility(View.GONE); - startScanning = false; - bluetoothScanStopButton.setText(getResources().getString(R.string.bluetooth_scan_text)); - scannedDevicesListView.setClickable(true); - } else - scanDevices(); - }); - - - IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); - getContext().registerReceiver(broadcastReceiver, filter); - - scannedDevicesListView.setOnItemClickListener((parent, view, position, id) -> { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - bluetoothDevices.get(position).getAddress(), null, null, Snackbar.LENGTH_SHORT); - bluetoothDevice = bluetoothDevices.get(position); - getDialog().cancel(); - connectBluetooth(); - }); - scanDevices(); - return rootView; - } - - @Override - public void onCancel(DialogInterface dialog) { - super.onCancel(dialog); - } - - private void scanDevices() { - deviceList.clear(); - bluetoothDevices.clear(); - bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); - if (bluetoothAdapter == null) { - startScanning = false; - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.bluetooth_not_supported), null, null, Snackbar.LENGTH_SHORT); - } else { - if (!bluetoothAdapter.isEnabled()) { - Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); - int BLUETOOTH_REQUEST_CODE = 100; - startActivityForResult(enableBtIntent, BLUETOOTH_REQUEST_CODE); - startScanning = false; - bluetoothScanStopButton.setText(getResources().getString(R.string.bluetooth_scan_text)); - scannedDevicesListView.setClickable(true); - } else { - startScanning = true; - scannedDevicesListView.setClickable(false); - bluetoothAdapter.startDiscovery(); - scanProgressBar.setVisibility(View.VISIBLE); - bluetoothScanStopButton.setText(getResources().getString(R.string.bluetooth_stop_text)); - } - } - } - - @Override - public void onResume() { - super.onResume(); - ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes(); - params.height = ViewGroup.LayoutParams.MATCH_PARENT; - params.width = ViewGroup.LayoutParams.MATCH_PARENT; - getDialog().getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); - } - - private void connectBluetooth() { - try { - UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID - mSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid); - mSocket.connect(); - mOutputStream = mSocket.getOutputStream(); - mInputStream = mSocket.getInputStream(); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/ChannelParametersFragment.java b/app/src/main/java/io/pslab/fragment/ChannelParametersFragment.java deleted file mode 100644 index 337d04eec..000000000 --- a/app/src/main/java/io/pslab/fragment/ChannelParametersFragment.java +++ /dev/null @@ -1,310 +0,0 @@ -package io.pslab.fragment; - -import android.Manifest; -import android.app.AlertDialog; -import android.content.DialogInterface; -import android.content.pm.PackageManager; -import android.os.Bundle; - -import androidx.annotation.NonNull; -import androidx.core.content.ContextCompat; -import androidx.fragment.app.Fragment; - -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.Spinner; - -import com.google.android.material.snackbar.Snackbar; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.activity.OscilloscopeActivity; -import io.pslab.others.CustomSnackBar; - -public class ChannelParametersFragment extends Fragment { - - private static final int RECORD_AUDIO_REQUEST_CODE = 1; - - private CheckBox checkBoxCH1; - private CheckBox checkBoxCH2; - private CheckBox checkBoxCH3; - private Spinner spinnerRangeCh1; - private Spinner spinnerRangeCh2; - private Spinner spinnerChannelSelect; - private CheckBox builtInMicCheckBox; - private CheckBox pslabMicCheckBox; - - public static ChannelParametersFragment newInstance() { - return new ChannelParametersFragment(); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - View v = inflater.inflate(R.layout.fragment_channel_parameters, container, false); - - final String[] ranges = {"+/-16V", "+/-8V", "+/-4V", "+/-3V", "+/-2V", - "+/-1" + DataFormatter.decSeparator + "5V", "+/-1V", "+/-500mV", "+/-160V"}; - final String[] channels = {"CH1", "CH2", "CH3", "MIC", "CAP", "RES", "VOL"}; - final String[] mics = {"MICROPHONE", "IN-BUILT MIC"}; - - spinnerRangeCh1 = v.findViewById(R.id.spinner_range_ch1_cp); - spinnerRangeCh2 = v.findViewById(R.id.spinner_range_ch2_cp); - spinnerChannelSelect = v.findViewById(R.id.spinner_channel_select_cp); - - boolean tabletSize = getResources().getBoolean(R.bool.isTablet); - checkBoxCH1 = v.findViewById(R.id.checkBox_ch1_cp); - checkBoxCH2 = v.findViewById(R.id.checkBox_ch2_cp); - checkBoxCH3 = v.findViewById(R.id.checkBox_ch3_cp); - checkBoxCH3.setText(getString(R.string.ch3_value, 3.3)); - - builtInMicCheckBox = v.findViewById(R.id.built_in_mic_cb); - pslabMicCheckBox = v.findViewById(R.id.pslab_mic_cb); - ArrayAdapter rangesAdapter; - ArrayAdapter channelsAdapter; - ArrayAdapter micsAdapter; - if (tabletSize) { - rangesAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner_tablet, ranges); - channelsAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner_tablet, channels); - micsAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner_mic_tablet, mics); - } else { - rangesAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner, ranges); - channelsAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner, channels); - micsAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner_mic, mics); - - } - rangesAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); - channelsAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); - micsAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); - - spinnerRangeCh1.setAdapter(rangesAdapter); - spinnerRangeCh1.setSelection(rangesAdapter.getPosition("+/-16V"), true); - spinnerRangeCh2.setAdapter(rangesAdapter); - spinnerRangeCh2.setSelection(rangesAdapter.getPosition("+/-16V"), true); - spinnerChannelSelect.setAdapter(channelsAdapter); - spinnerChannelSelect.setSelection(channelsAdapter.getPosition("CH1"), true); - - spinnerRangeCh1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - switch (position) { - case 0: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(16, -16); - break; - case 1: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(8, -8); - break; - case 2: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(4, -4); - break; - case 3: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(3, -3); - break; - case 4: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(2, -2); - break; - case 5: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(1.5, -1.5); - break; - case 6: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(1, -1); - break; - case 7: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(500, -500); - break; - case 8: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(160, -160); - openAlertDialogBox("CH1"); - break; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - spinnerRangeCh2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - switch (position) { - case 0: - ((OscilloscopeActivity) getActivity()).setRightYAxisScale(16, -16); - break; - case 1: - ((OscilloscopeActivity) getActivity()).setRightYAxisScale(8, -8); - break; - case 2: - ((OscilloscopeActivity) getActivity()).setRightYAxisScale(4, -4); - break; - case 3: - ((OscilloscopeActivity) getActivity()).setRightYAxisScale(3, -3); - break; - case 4: - ((OscilloscopeActivity) getActivity()).setRightYAxisScale(2, -2); - break; - case 5: - ((OscilloscopeActivity) getActivity()).setRightYAxisScale(1.5, -1.5); - break; - case 6: - ((OscilloscopeActivity) getActivity()).setRightYAxisScale(1, -1); - break; - case 7: - ((OscilloscopeActivity) getActivity()).setRightYAxisScale(500, -500); - break; - case 8: - ((OscilloscopeActivity) getActivity()).setRightYAxisScale(160, -160); - openAlertDialogBox("CH2"); - break; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - spinnerChannelSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - switch (position) { - case 0: - ((OscilloscopeActivity) getActivity()).setLeftYAxisLabel(spinnerChannelSelect.getSelectedItem().toString()); - spinnerRangeCh1.setEnabled(true); - break; - case 1: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(16, -16); - ((OscilloscopeActivity) getActivity()).setLeftYAxisLabel(spinnerChannelSelect.getSelectedItem().toString()); - spinnerRangeCh1.setEnabled(false); - break; - case 2: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(3, -3); - ((OscilloscopeActivity) getActivity()).setLeftYAxisLabel(spinnerChannelSelect.getSelectedItem().toString()); - spinnerRangeCh1.setEnabled(false); - break; - case 3: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(3, -3); - ((OscilloscopeActivity) getActivity()).setLeftYAxisLabel(spinnerChannelSelect.getSelectedItem().toString()); - break; - case 4: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(3, 0); - ((OscilloscopeActivity) getActivity()).setLeftYAxisLabel(spinnerChannelSelect.getSelectedItem().toString()); - spinnerRangeCh1.setEnabled(false); - break; - case 5: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(3, 0); - ((OscilloscopeActivity) getActivity()).setLeftYAxisLabel(spinnerChannelSelect.getSelectedItem().toString()); - spinnerRangeCh1.setEnabled(false); - break; - case 6: - ((OscilloscopeActivity) getActivity()).setLeftYAxisScale(3, 0); - ((OscilloscopeActivity) getActivity()).setLeftYAxisLabel(spinnerChannelSelect.getSelectedItem().toString()); - spinnerRangeCh1.setEnabled(false); - break; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - checkBoxCH1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - ((OscilloscopeActivity) getActivity()).isCH1Selected = isChecked; - } - }); - - checkBoxCH2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - ((OscilloscopeActivity) getActivity()).isCH2Selected = isChecked; - } - }); - - checkBoxCH3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - ((OscilloscopeActivity) getActivity()).isCH3Selected = isChecked; - } - }); - builtInMicCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - ((OscilloscopeActivity) getActivity()).isInBuiltMicSelected = isChecked; - ((OscilloscopeActivity) getActivity()).isAudioInputSelected = isChecked; - if (isChecked) { - ((OscilloscopeActivity) getActivity()).maxTimebase = 38.4f; - if (pslabMicCheckBox.isChecked()) { - ((OscilloscopeActivity) getActivity()).isMICSelected = false; - pslabMicCheckBox.setChecked(false); - ((OscilloscopeActivity) getActivity()).isAudioInputSelected = true; - } - if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { - requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, RECORD_AUDIO_REQUEST_CODE); - ((OscilloscopeActivity) getActivity()).isAudioInputSelected = false; - } - } else { - ((OscilloscopeActivity) getActivity()).maxTimebase = 102.4f; - } - } - }); - - pslabMicCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - ((OscilloscopeActivity) getActivity()).isMICSelected = isChecked; - ((OscilloscopeActivity) getActivity()).isAudioInputSelected = isChecked; - if (isChecked) { - if (builtInMicCheckBox.isChecked()) { - ((OscilloscopeActivity) getActivity()).isInBuiltMicSelected = false; - builtInMicCheckBox.setChecked(false); - ((OscilloscopeActivity) getActivity()).isAudioInputSelected = true; - } - if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { - requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, RECORD_AUDIO_REQUEST_CODE); - ((OscilloscopeActivity) getActivity()).isAudioInputSelected = false; - } - } - } - }); - return v; - } - - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { - if (requestCode == RECORD_AUDIO_REQUEST_CODE) { - if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - ((OscilloscopeActivity) getActivity()).isInBuiltMicSelected = true; - } else { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - "This feature won't work.", null, null, Snackbar.LENGTH_SHORT); - if (builtInMicCheckBox.isChecked()) - builtInMicCheckBox.toggle(); - } - } - } - - private void openAlertDialogBox(String inputSource) { - new AlertDialog.Builder(getActivity()) - .setIcon(android.R.drawable.ic_dialog_alert) - .setTitle("Message") - .setMessage("Connect a 10MOhm resistor with " + inputSource) - .setPositiveButton("OK", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - } - }) - .show(); - } -} diff --git a/app/src/main/java/io/pslab/fragment/CompassDataFragment.java b/app/src/main/java/io/pslab/fragment/CompassDataFragment.java deleted file mode 100644 index e4ce08413..000000000 --- a/app/src/main/java/io/pslab/fragment/CompassDataFragment.java +++ /dev/null @@ -1,675 +0,0 @@ -package io.pslab.fragment; - -import android.graphics.Bitmap; -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; -import android.location.Location; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import androidx.annotation.NonNull; - -import androidx.annotation.Nullable; -import com.google.android.material.snackbar.Snackbar; -import androidx.fragment.app.Fragment; - -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.Animation; -import android.view.animation.RotateAnimation; -import android.widget.ImageView; -import android.widget.RadioButton; -import android.widget.TextView; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.Timer; -import java.util.TimerTask; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import io.pslab.R; -import io.pslab.activity.CompassActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.interfaces.OperationCallback; -import io.pslab.models.CompassData; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.ScienceLabCommon; - -import static android.content.Context.SENSOR_SERVICE; -import static io.pslab.others.CSVLogger.CSV_DIRECTORY; - -public class CompassDataFragment extends Fragment implements OperationCallback { - - private static final CSVDataLine CSV_HEADER = new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("X-reading") - .add("Y-reading") - .add("Z-reading") - .add("Axis") - .add("Latitude") - .add("Longitude"); - private Unbinder unbinder; - private static int sensorType = 0; - @Nullable - @BindView(R.id.compass) - ImageView compass; - @BindView(R.id.degree_indicator) - TextView degreeIndicator; - - @BindView(R.id.compass_radio_button_x_axis) - RadioButton xAxisRadioButton; - @BindView(R.id.compass_radio_button_y_axis) - RadioButton yAxisRadioButton; - @BindView(R.id.compass_radio_button_z_axis) - RadioButton zAxisRadioButton; - - @BindView(R.id.tv_sensor_hmc5883l_bx) - TextView xAxisMagneticField; - @BindView(R.id.tv_sensor_hmc5883l_by) - TextView yAxisMagneticField; - @BindView(R.id.tv_sensor_hmc5883l_bz) - TextView zAxisMagneticField; - - private enum COMPASS_SENSOR {INBUILT_SENSOR, HMC5883L_SENSOR} - - private float currentDegree = 0f; - private int direction; - private SensorManager sensorManager; - private Sensor sensor; - private Timer graphTimer; - private long startTime, block; - private ArrayList recordedCompassArray; - private CompassData compassData = new CompassData(); - private CompassActivity compassActivity; - private static int updatePeriod = 1000; - private long previousTimeElapsed = (System.currentTimeMillis() - startTime) / updatePeriod; - private int turns = 0; - private boolean returningFromPause = false; - private View rootView; - - public static CompassDataFragment newInstance() { - return new CompassDataFragment(); - } - - public static void setParameters(String type) { - CompassDataFragment.sensorType = Integer.valueOf(type); - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - startTime = System.currentTimeMillis(); - compassActivity = (CompassActivity) getActivity(); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.activity_compass, container, false); - unbinder = ButterKnife.bind(this, rootView); - - xAxisRadioButton.setChecked(true); - direction = 0; - - xAxisRadioButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - xAxisRadioButton.setChecked(true); - yAxisRadioButton.setChecked(false); - zAxisRadioButton.setChecked(false); - compassData.setAxis(getContext().getResources().getString(R.string.compass_X_axis)); - direction = 0; - } - }); - - yAxisRadioButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - xAxisRadioButton.setChecked(false); - yAxisRadioButton.setChecked(true); - zAxisRadioButton.setChecked(false); - compassData.setAxis(getContext().getResources().getString(R.string.compass_Y_axis)); - direction = 1; - } - }); - - zAxisRadioButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - xAxisRadioButton.setChecked(false); - yAxisRadioButton.setChecked(false); - zAxisRadioButton.setChecked(true); - compassData.setAxis(getContext().getResources().getString(R.string.compass_Z_axis)); - direction = 2; - } - }); - compassActivity.addLocation = true; - return rootView; - } - - private SensorEventListener compassEventListner = new SensorEventListener() { - @Override - public void onSensorChanged(SensorEvent event) { - float degree; - switch (direction) { - case 0: - degree = Math.round(event.values[0]); - if (degree < 0) - degree += 360; - break; - case 1: - degree = Math.round(event.values[1]); - if (degree < 0) - degree += 360; - break; - case 2: - degree = Math.round(event.values[2]); - if (degree < 0) - degree += 360; - break; - default: - degree = Math.round(event.values[0]); - break; - } - - setCompassAnimation(degree); - - degreeIndicator.setText(String.valueOf(degree)); - currentDegree = -degree; - - degree = Math.round(event.values[0]); - if (degree < 0) - degree += 360; - compassData.setBx(degree); - xAxisMagneticField.setText(String.valueOf(degree)); - - degree = Math.round(event.values[1]); - if (degree < 0) - degree += 360; - compassData.setBy(degree); - yAxisMagneticField.setText(String.valueOf(degree)); - - degree = Math.round(event.values[2]); - if (degree < 0) - degree += 360; - compassData.setBz(degree); - zAxisMagneticField.setText(String.valueOf(degree)); - } - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) { - - } - }; - - private void setCompassAnimation(float degree) { - - RotateAnimation ra = new RotateAnimation( - currentDegree, - -degree, - Animation.RELATIVE_TO_SELF, 0.5f, - Animation.RELATIVE_TO_SELF, - 0.5f); - - ra.setDuration(210); - ra.setFillAfter(true); - - compass.startAnimation(ra); - } - - @Override - public void onResume() { - super.onResume(); - if (compassActivity.playingData) { - recordedCompassArray = new ArrayList<>(); - resetInstrumentData(); - playRecordedData(); - } else if (compassActivity.viewingData) { - recordedCompassArray = new ArrayList<>(); - resetInstrumentData(); - plotAllRecordedData(); - } else if (!compassActivity.isRecording) { - updateData(); - initiateCompassSensor(sensorType); - } else if (returningFromPause) { - updateData(); - } - } - - @Override - public void saveGraph() { - compassActivity.csvLogger.prepareLogFile(); - compassActivity.csvLogger.writeMetaData(getResources().getString(R.string.compass)); - compassActivity.csvLogger.writeCSVFile(CSV_HEADER); - for (CompassData compassData : compassActivity.recordedCompassData) { - compassActivity.csvLogger.writeCSVFile( - new CSVDataLine() - .add(compassData.getTime()) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(compassData.getTime()))) - .add(compassData.getBx()) - .add(compassData.getBy()) - .add(compassData.getBz()) - .add(compassData.getAxis()) - .add(compassData.getLat()) - .add(compassData.getLon()) - ); - } - View view = rootView.findViewById(R.id.compass_card); - view.setDrawingCacheEnabled(true); - Bitmap b = view.getDrawingCache(); - try { - b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + compassActivity.getSensorName() + - File.separator + CSVLogger.FILE_NAME_FORMAT.format(new Date()) + "_graph.jpg")); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - private void processRecordedData(long timeGap) { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } else { - graphTimer = new Timer(); - } - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - if (compassActivity.playingData) { - try { - CompassData d = recordedCompassArray.get(turns); - if (d.getAxis().equals(getContext().getResources().getString(R.string.compass_X_axis))) { - direction = 0; - xAxisRadioButton.setChecked(true); - yAxisRadioButton.setChecked(false); - zAxisRadioButton.setChecked(false); - } else if (d.getAxis().equals(getContext().getResources().getString(R.string.compass_Y_axis))) { - direction = 1; - xAxisRadioButton.setChecked(false); - yAxisRadioButton.setChecked(true); - zAxisRadioButton.setChecked(false); - } else if (d.getAxis().equals(getContext().getResources().getString(R.string.compass_Z_axis))) { - direction = 2; - xAxisRadioButton.setChecked(false); - yAxisRadioButton.setChecked(false); - zAxisRadioButton.setChecked(true); - } - turns++; - float degree = 0; - switch (direction) { - case 0: - if (d.getBx() != null) { - degree = Math.round(d.getBx()); - if (degree < 0) - degree += 360; - } - break; - case 1: - if (d.getBy() != null) { - degree = Math.round(d.getBy()); - if (degree < 0) - degree += 360; - } - break; - case 2: - if (d.getBz() != null) { - degree = Math.round(d.getBz()); - if (degree < 0) - degree += 360; - } - break; - default: - if (d.getBx() != null) { - degree = Math.round(d.getBx()); - } - break; - } - - setCompassAnimation(degree); - - degreeIndicator.setText(String.valueOf(degree)); - currentDegree = -degree; - - if (d.getBx() != null) { - degree = Math.round(d.getBx()); - } - if (degree < 0) - degree += 360; - compassData.setBx(degree); - xAxisMagneticField.setText(String.valueOf(degree)); - - if (d.getBy() != null) { - degree = Math.round(d.getBy()); - } - if (degree < 0) - degree += 360; - compassData.setBy(degree); - yAxisMagneticField.setText(String.valueOf(degree)); - - if (d.getBz() != null) { - degree = Math.round(d.getBz()); - } - if (degree < 0) - degree += 360; - compassData.setBz(degree); - zAxisMagneticField.setText(String.valueOf(degree)); - - } catch (IndexOutOfBoundsException e) { - graphTimer.cancel(); - graphTimer = null; - turns = 0; - compassActivity.playingData = false; - compassActivity.startedPlay = false; - compassActivity.invalidateOptionsMenu(); - } - } - } - }); - } - }, 0, timeGap); - } - - @Override - public void playData() { - resetInstrumentData(); - compassActivity.startedPlay = true; - try { - if (recordedCompassArray.size() > 1) { - CompassData i = recordedCompassArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - @Override - public void stopData() { - if (graphTimer != null) { - graphTimer.cancel(); - graphTimer = null; - } - recordedCompassArray.clear(); - plotAllRecordedData(); - compassActivity.startedPlay = false; - compassActivity.playingData = false; - turns = 0; - compassActivity.invalidateOptionsMenu(); - } - - private void plotAllRecordedData() { - recordedCompassArray.addAll(compassActivity.recordedCompassData); - if (recordedCompassArray.size() != 0) { - for (CompassData d : recordedCompassArray) { - float degree = 0; - switch (direction) { - case 0: - if (d.getBx() != null) { - degree = Math.round(d.getBx()); - if (degree < 0) - degree += 360; - } - break; - case 1: - if (d.getBy() != null) { - degree = Math.round(d.getBy()); - if (degree < 0) - degree += 360; - } - break; - case 2: - if (d.getBz() != null) { - degree = Math.round(d.getBz()); - if (degree < 0) - degree += 360; - } - break; - default: - if (d.getBx() != null) { - degree = Math.round(d.getBx()); - } - break; - } - - setCompassAnimation(degree); - - degreeIndicator.setText(String.valueOf(degree)); - currentDegree = -degree; - - if (d.getBx() != null) { - degree = Math.round(d.getBx()); - } - if (degree < 0) - degree += 360; - compassData.setBx(degree); - xAxisMagneticField.setText(String.valueOf(degree)); - - if (d.getBy() != null) { - degree = Math.round(d.getBy()); - } - if (degree < 0) - degree += 360; - compassData.setBy(degree); - yAxisMagneticField.setText(String.valueOf(degree)); - - if (d.getBz() != null) { - degree = Math.round(d.getBz()); - } - if (degree < 0) - degree += 360; - compassData.setBz(degree); - zAxisMagneticField.setText(String.valueOf(degree)); - - if (d.getAxis().equals(getContext().getResources().getString(R.string.compass_X_axis))) { - xAxisRadioButton.setChecked(true); - yAxisRadioButton.setChecked(false); - zAxisRadioButton.setChecked(false); - } else if (d.getAxis().equals(getContext().getResources().getString(R.string.compass_Y_axis))) { - xAxisRadioButton.setChecked(false); - yAxisRadioButton.setChecked(true); - zAxisRadioButton.setChecked(false); - } else if (d.getAxis().equals(getContext().getResources().getString(R.string.compass_Z_axis))) { - xAxisRadioButton.setChecked(false); - yAxisRadioButton.setChecked(false); - zAxisRadioButton.setChecked(true); - } - } - } - } - - private void playRecordedData() { - recordedCompassArray.addAll(compassActivity.recordedCompassData); - try { - if (recordedCompassArray.size() > 1) { - CompassData i = recordedCompassArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - if (graphTimer != null) { - graphTimer.cancel(); - } - if (sensorManager != null) { - sensorManager.unregisterListener(compassEventListner); - } - unbinder.unbind(); - } - - @Override - public void onPause() { - super.onPause(); - if (graphTimer != null) { - returningFromPause = true; - graphTimer.cancel(); - graphTimer = null; - if (compassActivity.playingData) { - compassActivity.finish(); - } - } - } - - private void updateData() { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } - graphTimer = new Timer(); - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - try { - visualizeData(); - } catch (NullPointerException e) { - /* Pass for another refresh round */ - } - } - }); - } - }, 0, updatePeriod); - } - - private void visualizeData() { - long timeElapsed = ((System.currentTimeMillis() - startTime) / updatePeriod); - if (timeElapsed != previousTimeElapsed) { - previousTimeElapsed = timeElapsed; - long currentTime = System.currentTimeMillis(); - writeLogToFile(currentTime, compassData.getBx(), compassData.getBy(), compassData.getBz(), compassData.getAxis()); - } - } - - private void writeLogToFile(long timestamp, Float compassXvalue, Float compassYvalue, Float compassZvalue, String compassAxis) { - if (getActivity() != null && compassActivity.isRecording) { - if (compassActivity.writeHeaderToFile) { - compassActivity.csvLogger.prepareLogFile(); - compassActivity.csvLogger.writeMetaData(getResources().getString(R.string.compass)); - compassActivity.csvLogger.writeCSVFile(CSV_HEADER); - block = timestamp; - compassActivity.recordSensorDataBlockID(new SensorDataBlock(timestamp, compassActivity.getSensorName())); - compassActivity.writeHeaderToFile = !compassActivity.writeHeaderToFile; - } - if (compassActivity.addLocation && compassActivity.gpsLogger.isGPSEnabled()) { - Location location = compassActivity.gpsLogger.getDeviceLocation(); - compassActivity.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(compassXvalue) - .add(compassYvalue) - .add(compassZvalue) - .add(compassAxis) - .add(location.getLatitude()) - .add(location.getLongitude()) - ); - compassData = new CompassData(timestamp, block, compassXvalue, compassYvalue, compassZvalue, compassAxis, location.getLatitude(), location.getLongitude()); - } else { - compassActivity.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(compassXvalue) - .add(compassYvalue) - .add(compassZvalue) - .add(compassAxis) - .add(0.0) - .add(0.0) - ); - compassData = new CompassData(timestamp, block, compassXvalue, compassYvalue, compassZvalue, compassAxis, 0.0, 0.0); - } - compassActivity.recordSensorData(compassData); - } else { - compassActivity.writeHeaderToFile = true; - } - } - - private void resetInstrumentData() { - sensor = null; - if (sensorManager != null) { - sensorManager.unregisterListener(compassEventListner); - } - startTime = System.currentTimeMillis(); - xAxisMagneticField.setText(getResources().getString(R.string.value_null)); - yAxisMagneticField.setText(getResources().getString(R.string.value_null)); - zAxisMagneticField.setText(getResources().getString(R.string.value_null)); - } - - private void initiateCompassSensor(int type) { - - CompassDataFragment.COMPASS_SENSOR s = CompassDataFragment.COMPASS_SENSOR.values()[type]; - resetInstrumentData(); - ScienceLab scienceLab; - switch (s) { - case INBUILT_SENSOR: - degreeIndicator.setText(getResources().getStringArray(R.array.compass_sensors)[0]); - sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE); - sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); - if (sensor == null) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_compass_sensor), null, null, Snackbar.LENGTH_LONG); - } else { - sensorManager.registerListener(compassEventListner, sensor, SensorManager.SENSOR_DELAY_GAME); - } - break; - case HMC5883L_SENSOR: - degreeIndicator.setText(getResources().getStringArray(R.array.compass_sensors)[1]); - scienceLab = ScienceLabCommon.scienceLab; - if (scienceLab.isConnected()) { - try { - I2C i2c = scienceLab.i2c; - ArrayList data; - data = i2c.scan(null); - if (data.contains(0x39)) { - sensorType = 1; - } else { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.sensor_not_connected_tls), null, null, Snackbar.LENGTH_SHORT); - sensorType = 0; - } - } catch (IOException e) { - e.printStackTrace(); - } - } else { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.device_not_found), null, null, Snackbar.LENGTH_SHORT); - sensorType = 0; - } - break; - default: - break; - } - - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/fragment/CompassSettingsFragment.java b/app/src/main/java/io/pslab/fragment/CompassSettingsFragment.java deleted file mode 100644 index 8562b21a4..000000000 --- a/app/src/main/java/io/pslab/fragment/CompassSettingsFragment.java +++ /dev/null @@ -1,62 +0,0 @@ -package io.pslab.fragment; - -import android.annotation.SuppressLint; -import android.content.SharedPreferences; -import android.os.Bundle; -import androidx.preference.ListPreference; -import androidx.preference.PreferenceFragmentCompat; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.others.PSLabPermission; - -public class CompassSettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { - - public static final String KEY_COMPASS_SENSOR_TYPE = "setting_compass_sensor_type"; - public static final String KEY_INCLUDE_LOCATION = "include_location_sensor_data"; - - private PSLabPermission psLabPermission; - - private ListPreference sensorTypePreference; - private SharedPreferences sharedPref; - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - setPreferencesFromResource(R.xml.compass_settings, rootKey); - sensorTypePreference = (ListPreference) getPreferenceScreen().findPreference(KEY_COMPASS_SENSOR_TYPE); - sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); - - psLabPermission = PSLabPermission.getInstance(); - if (!psLabPermission.checkPermissions(getActivity(), PSLabPermission.MAP_PERMISSION)) { - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putBoolean(CompassSettingsFragment.KEY_INCLUDE_LOCATION, true); - editor.apply(); - } - } - - @Override - public void onResume() { - super.onResume(); - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); - } - - @SuppressLint("ApplySharedPref") - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { - switch (s) { - case KEY_COMPASS_SENSOR_TYPE: - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - break; - default: - break; - } - } -} - diff --git a/app/src/main/java/io/pslab/fragment/ControlFragmentAdvanced.java b/app/src/main/java/io/pslab/fragment/ControlFragmentAdvanced.java deleted file mode 100644 index a9c3317c8..000000000 --- a/app/src/main/java/io/pslab/fragment/ControlFragmentAdvanced.java +++ /dev/null @@ -1,447 +0,0 @@ -package io.pslab.fragment; - -import android.content.DialogInterface; -import android.os.Bundle; -import android.text.InputType; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.Spinner; - -import androidx.annotation.Nullable; -import androidx.appcompat.app.AlertDialog; -import androidx.fragment.app.Fragment; - -import com.google.android.material.snackbar.Snackbar; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.EditTextWidget; -import io.pslab.others.ScienceLabCommon; - -import java.util.HashMap; -import java.util.Map; - - -public class ControlFragmentAdvanced extends Fragment { - - private ScienceLab scienceLab; - private Map state = new HashMap<>(); - - public static ControlFragmentAdvanced newInstance() { - return new ControlFragmentAdvanced(); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - scienceLab = ScienceLabCommon.scienceLab; - state.put("SQR1", 0); - state.put("SQR2", 0); - state.put("SQR3", 0); - state.put("SQR4", 0); - } - - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_control_advanced, container, false); - - Button buttonControlAdvanced1 = view.findViewById(R.id.button_control_advanced1); - Button buttonControlAdvanced2 = view.findViewById(R.id.button_control_advanced2); - - final EditText etWidgetControlAdvanced1 = view.findViewById(R.id.etwidget_control_advanced1); - final EditText etWidgetControlAdvanced2 = view.findViewById(R.id.etwidget_control_advanced2); - final EditText etWidgetControlAdvanced3 = view.findViewById(R.id.etwidget_control_advanced3); - final EditText etWidgetControlAdvanced4 = view.findViewById(R.id.etwidget_control_advanced4); - final EditText etWidgetControlAdvanced5 = view.findViewById(R.id.etwidget_control_advanced5); - final EditText etWidgetControlAdvanced6 = view.findViewById(R.id.etwidget_control_advanced6); - final EditText etWidgetControlAdvanced7 = view.findViewById(R.id.etwidget_control_advanced7); - final EditText etWidgetControlAdvanced8 = view.findViewById(R.id.etwidget_control_advanced8); - final EditText etWidgetControlAdvanced9 = view.findViewById(R.id.etwidget_control_advanced9); - final EditText etWidgetControlAdvanced10 = view.findViewById(R.id.etwidget_control_advanced10); - final EditText etWidgetControlAdvanced11 = view.findViewById(R.id.etwidget_control_advanced11); - final Spinner spinnerControlAdvanced1 = view.findViewById(R.id.spinner_control_advanced1); - final Spinner spinnerControlAdvanced2 = view.findViewById(R.id.spinner_control_advanced2); - - CheckBox checkBoxControlAdvanced1 = view.findViewById(R.id.checkbox_control_advanced1); - CheckBox checkBoxControlAdvanced2 = view.findViewById(R.id.checkbox_control_advanced2); - CheckBox checkBoxControlAdvanced3 = view.findViewById(R.id.checkbox_control_advanced3); - CheckBox checkBoxControlAdvanced4 = view.findViewById(R.id.checkbox_control_advanced4); - - etWidgetControlAdvanced1.setInputType(InputType.TYPE_NULL); - etWidgetControlAdvanced2.setInputType(InputType.TYPE_NULL); - etWidgetControlAdvanced3.setInputType(InputType.TYPE_NULL); - etWidgetControlAdvanced4.setInputType(InputType.TYPE_NULL); - etWidgetControlAdvanced5.setInputType(InputType.TYPE_NULL); - etWidgetControlAdvanced6.setInputType(InputType.TYPE_NULL); - etWidgetControlAdvanced7.setInputType(InputType.TYPE_NULL); - etWidgetControlAdvanced8.setInputType(InputType.TYPE_NULL); - etWidgetControlAdvanced9.setInputType(InputType.TYPE_NULL); - etWidgetControlAdvanced10.setInputType(InputType.TYPE_NULL); - etWidgetControlAdvanced11.setInputType(InputType.TYPE_NULL); - - etWidgetControlAdvanced1.setText(DataFormatter.formatDouble(10, DataFormatter.MINIMAL_PRECISION_FORMAT)); - etWidgetControlAdvanced2.setText(DataFormatter.formatDouble(10, DataFormatter.MINIMAL_PRECISION_FORMAT)); - etWidgetControlAdvanced3.setText(DataFormatter.formatDouble(10, DataFormatter.MINIMAL_PRECISION_FORMAT)); - etWidgetControlAdvanced4.setText(DataFormatter.formatDouble(0, DataFormatter.MINIMAL_PRECISION_FORMAT)); - etWidgetControlAdvanced5.setText(DataFormatter.formatDouble(0, DataFormatter.MINIMAL_PRECISION_FORMAT)); - etWidgetControlAdvanced6.setText(DataFormatter.formatDouble(0, DataFormatter.MINIMAL_PRECISION_FORMAT)); - etWidgetControlAdvanced7.setText(DataFormatter.formatDouble(0, DataFormatter.MINIMAL_PRECISION_FORMAT)); - etWidgetControlAdvanced8.setText(DataFormatter.formatDouble(0, DataFormatter.MINIMAL_PRECISION_FORMAT)); - etWidgetControlAdvanced9.setText(DataFormatter.formatDouble(0, DataFormatter.MINIMAL_PRECISION_FORMAT)); - etWidgetControlAdvanced10.setText(DataFormatter.formatDouble(0, DataFormatter.MINIMAL_PRECISION_FORMAT)); - etWidgetControlAdvanced11.setText(DataFormatter.formatDouble(0, DataFormatter.MINIMAL_PRECISION_FORMAT)); - etWidgetControlAdvanced1.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View arg0) { - showInputDialog(etWidgetControlAdvanced1, 1.0, 10.0, 5000.0); - } - }); - - etWidgetControlAdvanced1.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (hasFocus) { - showInputDialog(etWidgetControlAdvanced1, 1.0, 10.0, 5000.0); - } - } - }); - - etWidgetControlAdvanced2.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View arg0) { - - showInputDialog(etWidgetControlAdvanced2, 1.0, 10.0, 5000.0); - - } - }); - - etWidgetControlAdvanced2.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (hasFocus) { - showInputDialog(etWidgetControlAdvanced2, 1.0, 10.0, 5000.0); - } - } - }); - - etWidgetControlAdvanced3.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View arg0) { - showInputDialog(etWidgetControlAdvanced3, 1.0, 0.0, 360.0); - - } - }); - - etWidgetControlAdvanced3.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (hasFocus) { - showInputDialog(etWidgetControlAdvanced3, 1.0, 0.0, 360.0); - } - } - }); - - etWidgetControlAdvanced4.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View arg0) { - showInputDialog(etWidgetControlAdvanced4, 0.1, 0.0, 1.0); - } - }); - - etWidgetControlAdvanced4.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (hasFocus) { - showInputDialog(etWidgetControlAdvanced4, 0.1, 0.0, 1.0); - } - } - }); - - etWidgetControlAdvanced5.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View arg0) { - showInputDialog(etWidgetControlAdvanced5, 1.0, 0.0, 360.0); - } - }); - - etWidgetControlAdvanced5.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (hasFocus) { - showInputDialog(etWidgetControlAdvanced5, 1.0, 0.0, 360.0); - } - } - }); - - etWidgetControlAdvanced6.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View arg0) { - - showInputDialog(etWidgetControlAdvanced6, 0.1, 0.0, 1.0); - - } - }); - - etWidgetControlAdvanced6.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (hasFocus) { - showInputDialog(etWidgetControlAdvanced6, 0.1, 0.0, 1.0); - } - } - }); - - etWidgetControlAdvanced7.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View arg0) { - - showInputDialog(etWidgetControlAdvanced7, 1.0, 0.0, 360.0); - - } - }); - - etWidgetControlAdvanced7.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (hasFocus) { - showInputDialog(etWidgetControlAdvanced7, 1.0, 0.0, 360.0); - } - } - }); - - etWidgetControlAdvanced8.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View arg0) { - - showInputDialog(etWidgetControlAdvanced8, 0.1, 0.0, 1.0); - - } - }); - - etWidgetControlAdvanced8.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (hasFocus) { - showInputDialog(etWidgetControlAdvanced8, 0.1, 0.0, 1.0); - } - } - }); - - etWidgetControlAdvanced9.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View arg0) { - - showInputDialog(etWidgetControlAdvanced9, 1.0, 0.0, 360.0); - - } - }); - - etWidgetControlAdvanced9.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (hasFocus) { - showInputDialog(etWidgetControlAdvanced9, 1.0, 0.0, 360.0); - } - } - }); - - etWidgetControlAdvanced10.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View arg0) { - - showInputDialog(etWidgetControlAdvanced10, 0.1, 0.0, 1.0); - - } - }); - - etWidgetControlAdvanced10.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (hasFocus) { - showInputDialog(etWidgetControlAdvanced10, 0.1, 0.0, 1.0); - } - } - }); - - etWidgetControlAdvanced11.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View arg0) { - - showInputDialog(etWidgetControlAdvanced11, 1.0, 10.0, 5000.0); - - } - }); - - etWidgetControlAdvanced11.setOnFocusChangeListener(new View.OnFocusChangeListener() { - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (hasFocus) { - showInputDialog(etWidgetControlAdvanced11, 1.0, 10.0, 5000.0); - } - } - }); - - buttonControlAdvanced1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - try { - Double frequencySI1 = Double.parseDouble(etWidgetControlAdvanced1.getText().toString()); - Double frequencySI2 = Double.parseDouble(etWidgetControlAdvanced2.getText().toString()); - float phase = Float.parseFloat(etWidgetControlAdvanced3.getText().toString()); - - String wavetypeSI1 = spinnerControlAdvanced1.getSelectedItem().toString(); - String wavetypeSI2 = spinnerControlAdvanced2.getSelectedItem().toString(); - - if ("SINE".equals(wavetypeSI1) && scienceLab.isConnected()) - scienceLab.setSine1(frequencySI1); - else if ("SQUARE".equals(wavetypeSI1) && scienceLab.isConnected()) - scienceLab.setSqr1(frequencySI1, -1, false); - - if ("SINE".equals(wavetypeSI2) && scienceLab.isConnected()) - scienceLab.setSine2(frequencySI2); - else if ("SQUARE".equals(wavetypeSI2) && scienceLab.isConnected()) - scienceLab.setSqr2(frequencySI2, -1); - } catch (NumberFormatException e) { - etWidgetControlAdvanced1.setText("0"); - etWidgetControlAdvanced2.setText("0"); - etWidgetControlAdvanced3.setText("0"); - } - } - }); - - buttonControlAdvanced2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - try { - double phase2 = Double.parseDouble(etWidgetControlAdvanced5.getText().toString()); - double phase3 = Double.parseDouble(etWidgetControlAdvanced7.getText().toString()); - double phase4 = Double.parseDouble(etWidgetControlAdvanced9.getText().toString()); - - double dutyCycle1 = Double.parseDouble(etWidgetControlAdvanced4.getText().toString()); - double dutyCycle2 = Double.parseDouble(etWidgetControlAdvanced6.getText().toString()); - double dutyCycle3 = Double.parseDouble(etWidgetControlAdvanced8.getText().toString()); - double dutyCycle4 = Double.parseDouble(etWidgetControlAdvanced10.getText().toString()); - - double frequency = Double.parseDouble(etWidgetControlAdvanced11.getText().toString()); - - if (scienceLab.isConnected()) - scienceLab.sqrPWM(frequency, dutyCycle1, phase2, dutyCycle2, phase3, dutyCycle3, - phase4, dutyCycle4, true); - } catch (NumberFormatException e) { - etWidgetControlAdvanced4.setText("0"); - etWidgetControlAdvanced5.setText("0"); - etWidgetControlAdvanced6.setText("0"); - etWidgetControlAdvanced7.setText("0"); - etWidgetControlAdvanced8.setText("0"); - etWidgetControlAdvanced9.setText("0"); - etWidgetControlAdvanced10.setText("0"); - etWidgetControlAdvanced11.setText("0"); - } - } - }); - - checkBoxControlAdvanced1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) state.put("SQR1", 1); - else state.put("SQR1", 0); - if (scienceLab.isConnected()) - scienceLab.setState(state); - } - }); - - checkBoxControlAdvanced2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) state.put("SQR2", 1); - else state.put("SQR2", 0); - if (scienceLab.isConnected()) - scienceLab.setState(state); - } - }); - - checkBoxControlAdvanced3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) state.put("SQR3", 1); - else state.put("SQR3", 0); - if (scienceLab.isConnected()) - scienceLab.setState(state); - } - }); - - checkBoxControlAdvanced4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) state.put("SQR4", 1); - else state.put("SQR4", 0); - if (scienceLab.isConnected()) - scienceLab.setState(state); - } - }); - - return view; - } - - private void showInputDialog(final EditText et, final double leastCount, final double minima, final double maxima) { - LayoutInflater li = LayoutInflater.from(getContext()); - View promptsView = li.inflate(R.layout.dialog_input_edit_text_widget, null); - - AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext()); - - alertDialogBuilder.setView(promptsView); - final EditTextWidget userInput = - promptsView.findViewById(R.id.editTextDialogUserInput); - - userInput.init(getContext(), leastCount, minima, maxima); - userInput.setText(et.getText().toString()); - - alertDialogBuilder - .setPositiveButton("OK", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - // get user input and set it to result - // edit text - String input = userInput.getText(); - - if (Double.parseDouble(input) > maxima) { - input = DataFormatter.formatDouble(maxima, DataFormatter.LOW_PRECISION_FORMAT); - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - "The Maximum value for this field is " + maxima,null,null, Snackbar.LENGTH_SHORT); - } - if (Double.parseDouble(input) < minima) { - input = DataFormatter.formatDouble(minima, DataFormatter.MEDIUM_PRECISION_FORMAT); - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - "The Minimum value for this field is " + minima,null,null, Snackbar.LENGTH_SHORT); - } - et.setText(input); - } - }) - .setNegativeButton("Cancel", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.cancel(); - } - }); - AlertDialog alertDialog = alertDialogBuilder.create(); - alertDialog.show(); - } -} diff --git a/app/src/main/java/io/pslab/fragment/ControlFragmentMain.java b/app/src/main/java/io/pslab/fragment/ControlFragmentMain.java deleted file mode 100644 index 40df5345c..000000000 --- a/app/src/main/java/io/pslab/fragment/ControlFragmentMain.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.pslab.fragment; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import io.pslab.R; -import io.pslab.adapters.ControlMainAdapter; - - -public class ControlFragmentMain extends Fragment { - - private ControlMainAdapter mAdapter; - - public static ControlFragmentMain newInstance() { - return new ControlFragmentMain(); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mAdapter = new ControlMainAdapter(new String[]{"PV1", "PV2", "PV3", "PCS", "WAVE 1" , "WAVE 2" , "SQUARE"}); - setRetainInstance(true); - } - - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_control_main, container, false); - RecyclerView mRecyclerView = view.findViewById(R.id.control_main_recycler_view); - mRecyclerView.setHasFixedSize(false); - - LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity()); - mRecyclerView.setLayoutManager(mLayoutManager); - mRecyclerView.setAdapter(mAdapter); - return view; - - } -} diff --git a/app/src/main/java/io/pslab/fragment/ControlFragmentRead.java b/app/src/main/java/io/pslab/fragment/ControlFragmentRead.java deleted file mode 100644 index 3a650d921..000000000 --- a/app/src/main/java/io/pslab/fragment/ControlFragmentRead.java +++ /dev/null @@ -1,150 +0,0 @@ -package io.pslab.fragment; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.others.ScienceLabCommon; - -import java.text.DecimalFormat; - -public class ControlFragmentRead extends Fragment { - - private ScienceLab scienceLab; - - private TextView tvControlRead1; - private TextView tvControlRead2; - private TextView tvControlRead3; - private TextView tvControlRead4; - private TextView tvControlRead5; - private TextView tvControlRead6; - private TextView tvControlRead7; - private TextView tvControlRead8; - private TextView tvControlRead9; - private TextView tvControlRead10; - private Spinner spinnerControlRead1; - private Spinner spinnerControlRead2; - - public static ControlFragmentRead newInstance() { - return new ControlFragmentRead(); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - scienceLab = ScienceLabCommon.scienceLab; - } - - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_control_read, container, false); - - tvControlRead1 = view.findViewById(R.id.tv_control_read1); - tvControlRead2 = view.findViewById(R.id.tv_control_read2); - tvControlRead3 = view.findViewById(R.id.tv_control_read3); - tvControlRead4 = view.findViewById(R.id.tv_control_read4); - tvControlRead5 = view.findViewById(R.id.tv_control_read5); - tvControlRead6 = view.findViewById(R.id.tv_control_read6); - tvControlRead7 = view.findViewById(R.id.tv_control_read7); - tvControlRead8 = view.findViewById(R.id.tv_control_read8); - tvControlRead9 = view.findViewById(R.id.tv_control_read9); - tvControlRead10 = view.findViewById(R.id.tv_control_read10); - Button buttonControlRead1 = view.findViewById(R.id.button_control_read1); - Button buttonControlRead2 = view.findViewById(R.id.button_control_read2); - Button buttonControlRead3 = view.findViewById(R.id.button_control_read3); - Button buttonControlRead4 = view.findViewById(R.id.button_control_read4); - Button buttonControlRead5 = view.findViewById(R.id.button_control_read5); - Button buttonControlRead6 = view.findViewById(R.id.button_control_read6); - spinnerControlRead1 = view.findViewById(R.id.spinner_control_read1); - spinnerControlRead2 = view.findViewById(R.id.spinner_control_read2); - - buttonControlRead1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (scienceLab.isConnected()) { - DecimalFormat resistanceFormat = new DecimalFormat("#.##"); - Double resistance = scienceLab.getResistance(); - String Resistance = ""; - if (resistance == null) { - Resistance = "Infinity"; - } else { - if (resistance > 10e5) { - Resistance = resistanceFormat.format((resistance / 10e5)) + " MOhms"; - } else if (resistance > 10e2) { - Resistance = resistanceFormat.format((resistance / 10e2)) + " kOhms"; - } else if (resistance > 1) { - Resistance = resistanceFormat.format(resistance) + " Ohms"; - } else { - Resistance = "Cannot measure!"; - } - } - tvControlRead1.setText(Resistance); - } - } - }); - buttonControlRead2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (scienceLab.isConnected()) { - Double capacitance = scienceLab.getCapacitance(); - tvControlRead2.setText(String.valueOf(capacitance)); - } - } - }); - buttonControlRead3.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - String channel = spinnerControlRead1.getSelectedItem().toString(); - if (scienceLab.isConnected()) { - Double frequency = scienceLab.getFrequency(channel); - tvControlRead3.setText(DataFormatter.formatDouble(frequency, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - }); - buttonControlRead4.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - String channel = spinnerControlRead2.getSelectedItem().toString(); - if (scienceLab.isConnected()) { - scienceLab.countPulses(channel); - double pulseCount = scienceLab.readPulseCount(); - tvControlRead4.setText(DataFormatter.formatDouble(pulseCount, DataFormatter.MEDIUM_PRECISION_FORMAT)); - } - } - }); - buttonControlRead5.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - tvControlRead1.setText(""); - tvControlRead2.setText(""); - tvControlRead3.setText(""); - tvControlRead4.setText(""); - } - }); - buttonControlRead6.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (scienceLab.isConnected()) { - tvControlRead5.setText(DataFormatter.formatDouble(scienceLab.getVoltage("CH1", 1), DataFormatter.LOW_PRECISION_FORMAT)); - tvControlRead6.setText(DataFormatter.formatDouble(scienceLab.getVoltage("CAP", 1), DataFormatter.LOW_PRECISION_FORMAT)); - tvControlRead7.setText(DataFormatter.formatDouble(scienceLab.getVoltage("CH2", 1), DataFormatter.LOW_PRECISION_FORMAT)); - tvControlRead8.setText(DataFormatter.formatDouble(scienceLab.getVoltage("RES", 1), DataFormatter.LOW_PRECISION_FORMAT)); - tvControlRead9.setText(DataFormatter.formatDouble(scienceLab.getVoltage("CH3", 1), DataFormatter.LOW_PRECISION_FORMAT)); - tvControlRead10.setText(DataFormatter.formatDouble(scienceLab.getVoltage("VOL", 1), DataFormatter.LOW_PRECISION_FORMAT)); - } - - } - }); - return view; - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/fragment/DataAnalysisFragment.java b/app/src/main/java/io/pslab/fragment/DataAnalysisFragment.java deleted file mode 100644 index e42ae8dba..000000000 --- a/app/src/main/java/io/pslab/fragment/DataAnalysisFragment.java +++ /dev/null @@ -1,289 +0,0 @@ -package io.pslab.fragment; - -import android.os.Bundle; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.inputmethod.EditorInfo; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.SeekBar; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.fragment.app.Fragment; - -import io.pslab.R; -import io.pslab.activity.OscilloscopeActivity; -import io.pslab.others.FloatSeekBar; - -public class DataAnalysisFragment extends Fragment { - - private Spinner spinnerCurveFit; - private Spinner spinnerChannelSelect1; - private Spinner spinnerChannelSelect2; - private CheckBox checkBoxFouierTransform; - private Spinner spinnerChannelSelectHorizontalOffset; - private Spinner spinnerChannelSelectVerticalOffset; - private FloatSeekBar seekBarHorizontalOffset; - private FloatSeekBar seekBarVerticalOffset; - private EditText editTextHorizontalOffset; - private EditText editTextVerticalOffset; - boolean _ignore = false; - - public static DataAnalysisFragment newInstance() { - return new DataAnalysisFragment(); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View v = inflater.inflate(R.layout.fragment_data_analysis_main, container, false); - String[] curveFits = {"Sine Fit", "Square Fit"}; - String[] channels = {"None", "CH1", "CH2", "CH3", "MIC"}; - - spinnerCurveFit = v.findViewById(R.id.spinner_curve_fit_da); - spinnerChannelSelect1 = v.findViewById(R.id.spinner_channel_select_da1); - spinnerChannelSelect2 = v.findViewById(R.id.spinner_channel_select_da2); - spinnerChannelSelectHorizontalOffset = v.findViewById(R.id.spinner_channel_select_horizontal_offset); - spinnerChannelSelectVerticalOffset = v.findViewById(R.id.spinner_channel_select_vertical_offset); - seekBarHorizontalOffset = v.findViewById(R.id.seekbar_horizontal_offset); - seekBarVerticalOffset = v.findViewById(R.id.seekbar_vertical_offset); - editTextHorizontalOffset = v.findViewById(R.id.edittext_horizontal_offset); - editTextVerticalOffset = v.findViewById(R.id.edittext_vertical_offset); - checkBoxFouierTransform = v.findViewById(R.id.checkBox_fourier_da); - boolean tabletSize = getResources().getBoolean(R.bool.isTablet); - ArrayAdapter curveFitAdapter; - ArrayAdapter adapter; - - if (tabletSize) { - curveFitAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner_tablet, curveFits); - adapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner_tablet, channels); - } else { - curveFitAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner, curveFits); - adapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner, channels); - } - - curveFitAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); - adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); - - spinnerCurveFit.setAdapter(curveFitAdapter); - spinnerChannelSelect1.setAdapter(adapter); - spinnerChannelSelect2.setAdapter(adapter); - spinnerChannelSelectHorizontalOffset.setAdapter(adapter); - spinnerChannelSelectVerticalOffset.setAdapter(adapter); - - spinnerCurveFit.setSelection(curveFitAdapter.getPosition("Sine Fit"), true); - spinnerChannelSelect1.setSelection(adapter.getPosition("None"), true); - spinnerChannelSelect2.setSelection(adapter.getPosition("None"), true); - spinnerChannelSelectHorizontalOffset.setSelection(adapter.getPosition("None"), true); - spinnerChannelSelectVerticalOffset.setSelection(adapter.getPosition("None"), true); - - spinnerCurveFit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (position == 0) { - ((OscilloscopeActivity) getActivity()).sineFit = true; - ((OscilloscopeActivity) getActivity()).squareFit = false; - } else { - ((OscilloscopeActivity) getActivity()).sineFit = false; - ((OscilloscopeActivity) getActivity()).squareFit = true; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - spinnerChannelSelect1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - ((OscilloscopeActivity) getActivity()).curveFittingChannel1 = spinnerChannelSelect1.getItemAtPosition(position).toString(); - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - spinnerChannelSelect2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - ((OscilloscopeActivity) getActivity()).curveFittingChannel2 = spinnerChannelSelect2.getItemAtPosition(position).toString(); - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - spinnerChannelSelectHorizontalOffset.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView adapterView, View view, int i, long l) { - if (spinnerChannelSelectHorizontalOffset.getSelectedItem() != "None") { - seekBarHorizontalOffset.setValue(((OscilloscopeActivity) getActivity()).xOffsets.get(spinnerChannelSelectHorizontalOffset.getSelectedItem().toString())); - } - } - - @Override - public void onNothingSelected(AdapterView adapterView) { - // Do nothing - } - }); - - spinnerChannelSelectVerticalOffset.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView adapterView, View view, int i, long l) { - if (spinnerChannelSelectVerticalOffset.getSelectedItem() != "None") { - seekBarVerticalOffset.setValue(((OscilloscopeActivity) getActivity()).yOffsets.get(spinnerChannelSelectVerticalOffset.getSelectedItem().toString())); - } - } - - @Override - public void onNothingSelected(AdapterView adapterView) { - // Do nothing - } - }); - - if (((OscilloscopeActivity) getActivity()).xAxisScale == 875) { - seekBarHorizontalOffset.setters(0, ((OscilloscopeActivity) getActivity()).xAxisScale / 1000.0); - } else { - seekBarHorizontalOffset.setters(0, ((OscilloscopeActivity) getActivity()).xAxisScale); - } - seekBarHorizontalOffset.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int i, boolean b) { - if (!_ignore) { - editTextHorizontalOffset.setText(String.format("%s", seekBarHorizontalOffset.getValue())); - ((OscilloscopeActivity) getActivity()).xOffsets.put(spinnerChannelSelectHorizontalOffset.getSelectedItem().toString(), seekBarHorizontalOffset.getValue()); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - // Do nothing - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - // Do nothing - } - }); - seekBarHorizontalOffset.setProgress(100); - seekBarHorizontalOffset.setProgress(0); - - seekBarVerticalOffset.setters(-1 * ((OscilloscopeActivity) getActivity()).yAxisScale, ((OscilloscopeActivity) getActivity()).yAxisScale); - seekBarVerticalOffset.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int i, boolean b) { - if (!_ignore) { - editTextVerticalOffset.setText(String.format("%s", seekBarVerticalOffset.getValue())); - ((OscilloscopeActivity) getActivity()).yOffsets.put(spinnerChannelSelectVerticalOffset.getSelectedItem().toString(), seekBarVerticalOffset.getValue()); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - // Do nothing - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - // Do nothing - } - }); - seekBarVerticalOffset.setProgress(50); - - editTextHorizontalOffset.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - editTextHorizontalOffset.setCursorVisible(true); - return false; - } - }); - - editTextHorizontalOffset.setOnEditorActionListener(new EditText.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_DONE) { - if (!editTextHorizontalOffset.getText().toString().isEmpty() && !editTextHorizontalOffset.getText().toString().equals("-") && !editTextHorizontalOffset.getText().toString().equals(".") && !editTextVerticalOffset.getText().toString().equals("-.")) { - double xAxisScale = (((OscilloscopeActivity) getActivity()).xAxisScale == 875) ? ((OscilloscopeActivity) getActivity()).xAxisScale / 1000.0 : ((OscilloscopeActivity) getActivity()).xAxisScale; - _ignore = true; - if (Double.parseDouble(editTextHorizontalOffset.getText().toString()) > xAxisScale) { - editTextHorizontalOffset.setText(String.format("%s", xAxisScale)); - seekBarHorizontalOffset.setValue(xAxisScale); - ((OscilloscopeActivity) getActivity()).xOffsets.put(spinnerChannelSelectHorizontalOffset.getSelectedItem().toString(), seekBarHorizontalOffset.getValue()); - _ignore = false; - } else { - seekBarHorizontalOffset.setValue(Double.parseDouble(editTextHorizontalOffset.getText().toString())); - editTextHorizontalOffset.setText(String.format("%s", Double.parseDouble(editTextHorizontalOffset.getText().toString()))); - ((OscilloscopeActivity) getActivity()).xOffsets.put(spinnerChannelSelectHorizontalOffset.getSelectedItem().toString(), seekBarHorizontalOffset.getValue()); - _ignore = false; - } - } else { - seekBarHorizontalOffset.setProgress(0); - } - } - editTextHorizontalOffset.setCursorVisible(false); - return false; - } - }); - - editTextVerticalOffset.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - editTextVerticalOffset.setCursorVisible(true); - return false; - } - }); - - editTextVerticalOffset.setOnEditorActionListener(new EditText.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_DONE) { - if (!editTextVerticalOffset.getText().toString().isEmpty() && !editTextVerticalOffset.getText().toString().equals("-") && !editTextVerticalOffset.getText().toString().equals(".") && !editTextVerticalOffset.getText().toString().equals("-.")) { - _ignore = true; - if (Double.parseDouble(editTextVerticalOffset.getText().toString()) > ((OscilloscopeActivity) getActivity()).yAxisScale) { - editTextVerticalOffset.setText(String.format("%s", ((OscilloscopeActivity) getActivity()).yAxisScale)); - seekBarVerticalOffset.setValue(((OscilloscopeActivity) getActivity()).yAxisScale); - ((OscilloscopeActivity) getActivity()).yOffsets.put(spinnerChannelSelectVerticalOffset.getSelectedItem().toString(), seekBarVerticalOffset.getValue()); - _ignore = false; - } else if (Double.parseDouble(editTextVerticalOffset.getText().toString()) < -((OscilloscopeActivity) getActivity()).yAxisScale) { - editTextVerticalOffset.setText(String.format("%s", -((OscilloscopeActivity) getActivity()).yAxisScale)); - seekBarVerticalOffset.setValue(-((OscilloscopeActivity) getActivity()).yAxisScale); - ((OscilloscopeActivity) getActivity()).yOffsets.put(spinnerChannelSelectVerticalOffset.getSelectedItem().toString(), seekBarVerticalOffset.getValue()); - _ignore = false; - } else { - seekBarVerticalOffset.setValue(Double.parseDouble(editTextVerticalOffset.getText().toString())); - editTextVerticalOffset.setText(String.format("%s", Double.parseDouble(editTextVerticalOffset.getText().toString()))); - ((OscilloscopeActivity) getActivity()).yOffsets.put(spinnerChannelSelectVerticalOffset.getSelectedItem().toString(), seekBarVerticalOffset.getValue()); - _ignore = false; - } - } else { - seekBarVerticalOffset.setProgress(50); - } - } - editTextVerticalOffset.setCursorVisible(false); - - return false; - } - }); - - checkBoxFouierTransform.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - ((OscilloscopeActivity) getActivity()).isFourierTransformSelected = isChecked; - } - }); - return v; - } -} diff --git a/app/src/main/java/io/pslab/fragment/DustSensorDataFragment.java b/app/src/main/java/io/pslab/fragment/DustSensorDataFragment.java deleted file mode 100644 index dfcc5367e..000000000 --- a/app/src/main/java/io/pslab/fragment/DustSensorDataFragment.java +++ /dev/null @@ -1,471 +0,0 @@ -package io.pslab.fragment; - -import android.graphics.Bitmap; -import android.graphics.Color; -import android.location.Location; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import androidx.annotation.NonNull; - -import androidx.annotation.Nullable; -import com.google.android.material.snackbar.Snackbar; -import androidx.fragment.app.Fragment; - -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.github.anastr.speedviewlib.PointerSpeedometer; -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.Locale; -import java.util.Timer; -import java.util.TimerTask; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.activity.DustSensorActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.interfaces.OperationCallback; -import io.pslab.models.DustSensorData; -import io.pslab.models.GasSensorData; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.ScienceLabCommon; - -import static io.pslab.others.CSVLogger.CSV_DIRECTORY; - -public class DustSensorDataFragment extends Fragment implements OperationCallback { - - private static final CSVDataLine CSV_HEADER = - new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("ppmValue") - .add("Latitude") - .add("Longitude"); - - @BindView(R.id.dust_sensor_value) - TextView dustValue; - @BindView(R.id.dust_sensor_status) - TextView dustStatus; - @BindView(R.id.label_dust_sensor) - TextView sensorLabel; - @BindView(R.id.chart_dust_sensor) - LineChart mChart; - @BindView(R.id.dust_sensor) - PointerSpeedometer dustSensorMeter; - - // TODO: Support multiple kinds of dust sensors - private static int sensorType = 0; - private static double highLimit = 4.0; - private static int updatePeriod = 1000; - - private DustSensorActivity dustSensorActivity; - private View rootView; - private Unbinder unbinder; - private ScienceLab scienceLab; - private YAxis y; - private Timer graphTimer; - private ArrayList entries; - private long startTime; - private long timeElapsed; - private long previousTimeElapsed = (System.currentTimeMillis() - startTime) / updatePeriod; - private long block; - private GasSensorData sensorData; - private boolean returningFromPause = false; - private int turns = 0; - private ArrayList recordedDustSensorArray; - - public static DustSensorDataFragment newInstance() { - return new DustSensorDataFragment(); - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - startTime = System.currentTimeMillis(); - dustSensorActivity = (DustSensorActivity) getActivity(); - } - - public static void setParameters(double highLimit, int updatePeriod, String type) { - DustSensorDataFragment.highLimit = highLimit; - DustSensorDataFragment.updatePeriod = updatePeriod; - DustSensorDataFragment.sensorType = Integer.valueOf(type); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_dust_sensor, container, false); - unbinder = ButterKnife.bind(this, rootView); - scienceLab = ScienceLabCommon.scienceLab; - entries = new ArrayList<>(); - setupInstruments(); - if (!scienceLab.isConnected()) - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), getString(R.string.not_connected), null, null, Snackbar.LENGTH_SHORT); - return rootView; - } - - @Override - public void onResume() { - super.onResume(); - if (dustSensorActivity.playingData) { - sensorLabel.setText(getResources().getString(R.string.baro_meter)); - recordedDustSensorArray = new ArrayList<>(); - resetInstrumentData(); - playRecordedData(); - } else if (dustSensorActivity.viewingData) { - sensorLabel.setText(getResources().getString(R.string.baro_meter)); - recordedDustSensorArray = new ArrayList<>(); - resetInstrumentData(); - plotAllRecordedData(); - } else if (!dustSensorActivity.isRecording) { - updateGraphs(); - entries.clear(); - mChart.clear(); - mChart.invalidate(); - } else if (returningFromPause) { - updateGraphs(); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - if (graphTimer != null) { - graphTimer.cancel(); - } - unbinder.unbind(); - } - - private void plotAllRecordedData() { - recordedDustSensorArray.addAll(dustSensorActivity.recordedDustSensorData); - if (recordedDustSensorArray.size() != 0) { - for (DustSensorData d : recordedDustSensorArray) { - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getPpmValue()); - entries.add(entry); - dustSensorMeter.setWithTremble(false); - float ppm = d.getPpmValue(); - dustSensorMeter.setSpeedAt(ppm); - dustSensorMeter.setPointerColor(ppm > highLimit ? Color.WHITE : Color.RED); - dustValue.setText(String.format(Locale.getDefault(), "%.2f", ppm)); - String status = ppm > highLimit ? "Good" : "Bad"; - dustStatus.setText(status); - } - y.setAxisMaximum(5); - y.setAxisMinimum(0); - y.setLabelCount(10); - - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.baro_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } - } - - private void playRecordedData() { - recordedDustSensorArray.addAll(dustSensorActivity.recordedDustSensorData); - try { - if (recordedDustSensorArray.size() > 1) { - DustSensorData i = recordedDustSensorArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - private void processRecordedData(long timeGap) { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } else { - graphTimer = new Timer(); - } - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - if (dustSensorActivity.playingData) { - try { - DustSensorData d = recordedDustSensorArray.get(turns); - turns++; - float ppm = d.getPpmValue(); - dustSensorMeter.setPointerColor(ppm > highLimit ? Color.WHITE : Color.RED); - dustValue.setText(String.format(Locale.getDefault(), "%.2f", ppm)); - String status = ppm > highLimit ? "Good" : "Bad"; - dustStatus.setText(status); - - y.setAxisMaximum(5); - y.setAxisMinimum(0); - y.setLabelCount(10); - dustSensorMeter.setWithTremble(false); - dustSensorMeter.setSpeedAt(ppm); - - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getPpmValue()); - entries.add(entry); - - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.baro_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } catch (IndexOutOfBoundsException e) { - graphTimer.cancel(); - graphTimer = null; - turns = 0; - dustSensorActivity.playingData = false; - dustSensorActivity.startedPlay = false; - dustSensorActivity.invalidateOptionsMenu(); - } - } - } - }); - } - }, 0, timeGap); - } - - @Override - public void playData() { - resetInstrumentData(); - dustSensorActivity.startedPlay = true; - try { - if (recordedDustSensorArray.size() > 1) { - DustSensorData i = recordedDustSensorArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - @Override - public void stopData() { - if (graphTimer != null) { - graphTimer.cancel(); - graphTimer = null; - } - recordedDustSensorArray.clear(); - entries.clear(); - plotAllRecordedData(); - dustSensorActivity.startedPlay = false; - dustSensorActivity.playingData = false; - turns = 0; - dustSensorActivity.invalidateOptionsMenu(); - } - - @Override - public void saveGraph() { - dustSensorActivity.csvLogger.prepareLogFile(); - dustSensorActivity.csvLogger.writeMetaData(getResources().getString(R.string.gas_sensor)); - dustSensorActivity.csvLogger.writeCSVFile(CSV_HEADER); - for (DustSensorData dustSensorData : dustSensorActivity.recordedDustSensorData) { - dustSensorActivity.csvLogger.writeCSVFile( - new CSVDataLine() - .add(dustSensorData.getTime()) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(dustSensorData.getTime()))) - .add(dustSensorData.getPpmValue()) - .add(dustSensorData.getLat()) - .add(dustSensorData.getLon()) - ); - } - View view = rootView.findViewById(R.id.gas_sensor_linearlayout); - view.setDrawingCacheEnabled(true); - Bitmap b = view.getDrawingCache(); - try { - b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + dustSensorActivity.getSensorName() + - File.separator + CSVLogger.FILE_NAME_FORMAT.format(new Date()) + "_graph.jpg")); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - @Override - public void onPause() { - super.onPause(); - if (graphTimer != null) { - returningFromPause = true; - graphTimer.cancel(); - graphTimer = null; - if (dustSensorActivity.playingData) { - dustSensorActivity.finish(); - } - } - } - - private void updateGraphs() { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } - graphTimer = new Timer(); - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(() -> { - try { - visualizeData(); - } catch (NullPointerException e) { - } - }); - } - }, 0, 1000); - } - - private void writeLogToFile(long timestamp, float ppmValue) { - if (getActivity() != null && dustSensorActivity.isRecording) { - if (dustSensorActivity.writeHeaderToFile) { - dustSensorActivity.csvLogger.prepareLogFile(); - dustSensorActivity.csvLogger.writeCSVFile(CSV_HEADER); - block = timestamp; - dustSensorActivity.recordSensorDataBlockID(new SensorDataBlock(timestamp, dustSensorActivity.getSensorName())); - dustSensorActivity.writeHeaderToFile = !dustSensorActivity.writeHeaderToFile; - } - if (dustSensorActivity.addLocation && dustSensorActivity.gpsLogger.isGPSEnabled()) { - Location location = dustSensorActivity.gpsLogger.getDeviceLocation(); - dustSensorActivity.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(ppmValue) - .add(location.getLatitude()) - .add(location.getLongitude()) - ); - sensorData = new GasSensorData(timestamp, block, ppmValue, location.getLatitude(), location.getLongitude()); - } else { - dustSensorActivity.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(ppmValue) - .add(0.0) - .add(0.0) - ); - sensorData = new GasSensorData(timestamp, block, ppmValue, 0.0, 0.0); - } - dustSensorActivity.recordSensorData(sensorData); - } else { - dustSensorActivity.writeHeaderToFile = true; - } - } - - private void visualizeData() { - if (scienceLab.isConnected()) { - double ppm = scienceLab.getVoltage("CH1", 1); - dustSensorMeter.setPointerColor(ppm > highLimit ? Color.WHITE : Color.RED); - dustValue.setText(String.format(Locale.getDefault(), "%.2f", ppm)); - String status = ppm > highLimit ? "Good" : "Bad"; - dustStatus.setText(status); - dustSensorMeter.setWithTremble(false); - dustSensorMeter.setSpeedAt((float) ppm); - timeElapsed = ((System.currentTimeMillis() - startTime) / updatePeriod); - if (timeElapsed != previousTimeElapsed) { - previousTimeElapsed = timeElapsed; - Entry entry = new Entry((float) timeElapsed, (float) ppm); - entries.add(entry); - writeLogToFile(System.currentTimeMillis(), (float) ppm); - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.gas_sensor_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } - } - } - - private void setupInstruments() { - dustSensorMeter.setMaxSpeed(5); - XAxis x = mChart.getXAxis(); - this.y = mChart.getAxisLeft(); - YAxis y2 = mChart.getAxisRight(); - - mChart.setTouchEnabled(true); - mChart.setHighlightPerDragEnabled(true); - mChart.setDragEnabled(true); - mChart.setScaleEnabled(true); - mChart.setDrawGridBackground(false); - mChart.setPinchZoom(true); - mChart.setScaleYEnabled(true); - mChart.setBackgroundColor(Color.BLACK); - mChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - mChart.setData(data); - - Legend l = mChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(5); - y.setAxisMinimum(0); - y.setDrawGridLines(true); - y.setLabelCount(10); - - y2.setDrawGridLines(false); - y2.setMaxWidth(0); - } - - private void resetInstrumentData() { - startTime = System.currentTimeMillis(); - dustValue.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - dustStatus.setText(getString(R.string.unknown)); - dustSensorMeter.setSpeedAt(0); - dustSensorMeter.setWithTremble(false); - entries.clear(); - } - -} diff --git a/app/src/main/java/io/pslab/fragment/DustSensorSettingsFragment.java b/app/src/main/java/io/pslab/fragment/DustSensorSettingsFragment.java deleted file mode 100644 index d2848ef63..000000000 --- a/app/src/main/java/io/pslab/fragment/DustSensorSettingsFragment.java +++ /dev/null @@ -1,118 +0,0 @@ -package io.pslab.fragment; - -import android.annotation.SuppressLint; -import android.content.SharedPreferences; -import android.os.Bundle; -import com.google.android.material.snackbar.Snackbar; -import androidx.preference.CheckBoxPreference; -import androidx.preference.EditTextPreference; -import androidx.preference.ListPreference; -import androidx.preference.PreferenceFragmentCompat; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.PSLabPermission; - -public class DustSensorSettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { - - public static final String KEY_INCLUDE_LOCATION = "include_location_sensor_data"; - public static final String KEY_UPDATE_PERIOD = "setting_dust_update_period"; - public static final String KEY_HIGH_LIMIT = "setting_dust_high_limit"; - public static final String KEY_DUST_SENSOR_TYPE = "setting_dust_sensor_type"; - - private PSLabPermission psLabPermission; - - private EditTextPreference updatePeriodPref; - private EditTextPreference highLimitPref; - private CheckBoxPreference locationPreference; - private ListPreference sensorTypePreference; - private SharedPreferences sharedPref; - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - setPreferencesFromResource(R.xml.dust_sensor_settings, rootKey); - updatePeriodPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_UPDATE_PERIOD); - highLimitPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_HIGH_LIMIT); - locationPreference = (CheckBoxPreference) getPreferenceScreen().findPreference(KEY_INCLUDE_LOCATION); - sensorTypePreference = (ListPreference) getPreferenceScreen().findPreference(KEY_DUST_SENSOR_TYPE); - sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); - - psLabPermission = PSLabPermission.getInstance(); - if (!psLabPermission.checkPermissions(getActivity(), PSLabPermission.MAP_PERMISSION)) { - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putBoolean(DustSensorSettingsFragment.KEY_INCLUDE_LOCATION, true); - editor.apply(); - } - } - - @Override - public void onResume() { - super.onResume(); - locationPreference.setChecked(sharedPref.getBoolean(KEY_INCLUDE_LOCATION, true)); - updatePeriodPref.setSummary(updatePeriodPref.getText() + " ms"); - highLimitPref.setSummary(highLimitPref.getText() + " PPM"); - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); - } - - @SuppressLint("ApplySharedPref") - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { - switch (s) { - case KEY_INCLUDE_LOCATION: - if (locationPreference.isChecked()) { - psLabPermission.checkPermissions( - getActivity(), PSLabPermission.MAP_PERMISSION); - } - break; - case KEY_UPDATE_PERIOD: - try { - int updatePeriod = Integer.parseInt(updatePeriodPref.getText()); - if (updatePeriod > 1000 || updatePeriod < 100) { - throw new NumberFormatException(); - } else { - updatePeriodPref.setSummary(updatePeriod + " ms"); - } - } catch (NumberFormatException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.update_period_msg),null,null, Snackbar.LENGTH_SHORT); - updatePeriodPref.setSummary("1000 ms"); - updatePeriodPref.setText("1000"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(s, "1000"); - editor.commit(); - } - break; - case KEY_HIGH_LIMIT: - try { - double highLimit = Double.parseDouble(highLimitPref.getText()); - if (highLimit > 5.0 || highLimit < 0.0) { - throw new NumberFormatException(); - } else { - highLimitPref.setSummary(String.valueOf(highLimit) + " PPM"); - } - } catch (NumberFormatException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.high_limit_msg),null,null,Snackbar.LENGTH_SHORT); - highLimitPref.setSummary("4.0 V"); - highLimitPref.setText("4.0"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(KEY_HIGH_LIMIT, "4.0"); - editor.commit(); - } - break; - case KEY_DUST_SENSOR_TYPE: - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - break; - default: - break; - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/ESPFragment.java b/app/src/main/java/io/pslab/fragment/ESPFragment.java deleted file mode 100644 index 3c13b32ae..000000000 --- a/app/src/main/java/io/pslab/fragment/ESPFragment.java +++ /dev/null @@ -1,128 +0,0 @@ -package io.pslab.fragment; - -import android.app.Activity; -import android.os.AsyncTask; -import android.os.Bundle; -import android.util.Log; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.inputmethod.EditorInfo; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ProgressBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.fragment.app.DialogFragment; - -import com.google.android.material.snackbar.Snackbar; - -import java.io.IOException; - -import io.pslab.R; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.ScienceLabCommon; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -public class ESPFragment extends DialogFragment { - private String espIPAddress = ""; - private ProgressBar espConnectProgressBar; - private Button espConnectBtn; - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_esp, container, false); - EditText espIPEditText = rootView.findViewById(R.id.esp_ip_edit_text); - espConnectBtn = rootView.findViewById(R.id.esp_connect_btn); - espConnectProgressBar = rootView.findViewById(R.id.esp_connect_progressbar); - espConnectBtn.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - espIPAddress = espIPEditText.getText().toString(); - espConnectBtn.onEditorAction(EditorInfo.IME_ACTION_DONE); - Activity activity; - if (espIPAddress.isEmpty() && ((activity = getActivity()) != null)) { - CustomSnackBar.showSnackBar(activity.findViewById(android.R.id.content), - getString(R.string.incorrect_IP_address_message), null, null, Snackbar.LENGTH_SHORT); - - } else { - new ESPTask().execute(); - } - } - - }); - espIPEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if (actionId == EditorInfo.IME_ACTION_DONE) { - espConnectBtn.performClick(); - return true; - } - return false; - } - }); - return rootView; - } - - @Override - public void onResume() { - super.onResume(); - ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes(); - params.height = ViewGroup.LayoutParams.WRAP_CONTENT; - params.width = ViewGroup.LayoutParams.MATCH_PARENT; - getDialog().getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); - } - - private class ESPTask extends AsyncTask { - - @Override - protected void onPreExecute() { - espConnectBtn.setVisibility(View.GONE); - espConnectProgressBar.setVisibility(View.VISIBLE); - } - - @Override - protected String doInBackground(Void... voids) { - String result = ""; - try { - OkHttpClient client = new OkHttpClient(); - Request request = new Request.Builder() - .url("http://" + espIPAddress) - .build(); - Response response = client.newCall(request).execute(); - if (response.code() == 200) { - ScienceLabCommon.setIsWifiConnected(true); - ScienceLabCommon.setEspBaseIP(espIPAddress); - } - result = response.body().string(); - } catch (IOException e) { - e.printStackTrace(); - } - return result; - } - - @Override - protected void onPostExecute(String result) { - espConnectProgressBar.setVisibility(View.GONE); - espConnectBtn.setVisibility(View.VISIBLE); - Activity activity; - if (result.isEmpty() && ((activity = getActivity()) != null)) { - CustomSnackBar.showSnackBar(activity.findViewById(android.R.id.content), - getString(R.string.incorrect_IP_address_message), null, null, Snackbar.LENGTH_SHORT); - } else { - Log.v("Response", result); - } - } - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/fragment/FAQFragment.java b/app/src/main/java/io/pslab/fragment/FAQFragment.java deleted file mode 100644 index 49c3755db..000000000 --- a/app/src/main/java/io/pslab/fragment/FAQFragment.java +++ /dev/null @@ -1,153 +0,0 @@ -package io.pslab.fragment; - -import android.os.Bundle; -import android.text.Html; -import android.text.method.LinkMovementMethod; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.BaseExpandableListAdapter; -import android.widget.ExpandableListView; -import android.widget.TextView; - -import androidx.fragment.app.Fragment; - -import io.pslab.R; - -public class FAQFragment extends Fragment { - - private String[] questions; - private String[][] answers; - - public static FAQFragment newInstance() { - return new FAQFragment(); - } - - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - questions = getResources().getStringArray(R.array.faq_questions); - - String[] ans = getResources().getStringArray(R.array.faq_answers); - answers = new String[ans.length][]; - for (int i = 0; i < ans.length; i++) { - answers[i] = new String[]{ans[i]}; - } - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View rootView; - rootView = inflater.inflate(R.layout.fragment_faq, container, false); - return rootView; - } - - @Override - public void onViewCreated(View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - ExpandableListView listView; - - listView = (ExpandableListView) view.findViewById(R.id.expListView); - listView.setAdapter(new ExpandableListAdapter(questions, answers)); - listView.setGroupIndicator(null); - - } - - public class ExpandableListAdapter extends BaseExpandableListAdapter { - - private final LayoutInflater inf; - private String[] questions; - private String[][] answers; - - public ExpandableListAdapter(String[] questions, String[][] answers) { - this.questions = questions; - this.answers = answers; - inf = LayoutInflater.from(getActivity()); - } - - @Override - public int getGroupCount() { - return questions.length; - } - - @Override - public int getChildrenCount(int questionPosition) { - return answers[questionPosition].length; - } - - @Override - public Object getGroup(int questionPosition) { - return questions[questionPosition]; - } - - @Override - public Object getChild(int questionPosition, int answerPosition) { - return answers[questionPosition][answerPosition]; - } - - @Override - public long getGroupId(int questionPosition) { - return questionPosition; - } - - @Override - public long getChildId(int questionPosition, int answerPosition) { - return answerPosition; - } - - @Override - public boolean hasStableIds() { - return true; - } - - @Override - public View getChildView(int questionPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { - - ViewHolder holder; - View v = convertView; - if (v == null) { - v = inf.inflate(R.layout.list_item, parent, false); - holder = new ViewHolder(); - - holder.text = (TextView) v.findViewById(R.id.lblListItem); - v.setTag(holder); - } else { - holder = (ViewHolder) v.getTag(); - } - - holder.text.setClickable(true); - holder.text.setMovementMethod(LinkMovementMethod.getInstance()); - holder.text.setText(Html.fromHtml(getChild(questionPosition, childPosition).toString())); - - return v; - } - - @Override - public View getGroupView(int questionPosition, boolean isExpanded, View convertView, ViewGroup parent) { - ViewHolder holder; - View v = convertView; - if (v == null) { - v = inf.inflate(R.layout.list_group, parent, false); - - holder = new ViewHolder(); - holder.text = (TextView) v.findViewById(R.id.lblListHeader); - v.setTag(holder); - } else { - holder = (ViewHolder) v.getTag(); - } - - holder.text.setText(getGroup(questionPosition).toString()); - - return v; - } - - @Override - public boolean isChildSelectable(int questionPosition, int answerPosition) { - return true; - } - - private class ViewHolder { - private TextView text; - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/GasSensorDataFragment.java b/app/src/main/java/io/pslab/fragment/GasSensorDataFragment.java deleted file mode 100644 index b1bd70482..000000000 --- a/app/src/main/java/io/pslab/fragment/GasSensorDataFragment.java +++ /dev/null @@ -1,449 +0,0 @@ -package io.pslab.fragment; - -import android.graphics.Bitmap; -import android.graphics.Color; -import android.location.Location; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import androidx.annotation.NonNull; - -import androidx.annotation.Nullable; -import com.google.android.material.snackbar.Snackbar; -import androidx.fragment.app.Fragment; - -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.github.anastr.speedviewlib.PointerSpeedometer; -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.Locale; -import java.util.Timer; -import java.util.TimerTask; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.activity.GasSensorActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.interfaces.OperationCallback; -import io.pslab.models.GasSensorData; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.ScienceLabCommon; - -import static io.pslab.others.CSVLogger.CSV_DIRECTORY; - -public class GasSensorDataFragment extends Fragment implements OperationCallback { - - private static final CSVDataLine CSV_HEADER = new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("ppmValue") - .add("Latitude") - .add("Longitude"); - @BindView(R.id.gas_sensor_value) - TextView gasValue; - @BindView(R.id.label_gas_sensor) - TextView sensorLabel; - @BindView(R.id.chart_gas_sensor) - LineChart mChart; - @BindView(R.id.gas_sensor) - PointerSpeedometer gasSensorMeter; - private GasSensorActivity gasSensorActivity; - private View rootView; - private Unbinder unbinder; - private ScienceLab scienceLab; - private YAxis y; - private Timer graphTimer; - private ArrayList entries; - private long updatePeriod = 1000; - private long startTime; - private long timeElapsed; - private long previousTimeElapsed = (System.currentTimeMillis() - startTime) / updatePeriod; - private long block; - private GasSensorData sensorData; - private boolean returningFromPause = false; - private int turns = 0; - private ArrayList recordedGasSensorArray; - - - public static GasSensorDataFragment newInstance() { - return new GasSensorDataFragment(); - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - startTime = System.currentTimeMillis(); - gasSensorActivity = (GasSensorActivity) getActivity(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_gas_sensor, container, false); - unbinder = ButterKnife.bind(this, rootView); - scienceLab = ScienceLabCommon.scienceLab; - if (!scienceLab.isConnected()) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.not_connected), null, null, Snackbar.LENGTH_SHORT); - } - entries = new ArrayList<>(); - setupInstruments(); - return rootView; - } - - @Override - public void onResume() { - super.onResume(); - if (gasSensorActivity.playingData) { - sensorLabel.setText(getResources().getString(R.string.baro_meter)); - recordedGasSensorArray = new ArrayList<>(); - resetInstrumentData(); - playRecordedData(); - } else if (gasSensorActivity.viewingData) { - sensorLabel.setText(getResources().getString(R.string.baro_meter)); - recordedGasSensorArray = new ArrayList<>(); - resetInstrumentData(); - plotAllRecordedData(); - } else if (!gasSensorActivity.isRecording) { - updateGraphs(); - entries.clear(); - mChart.clear(); - mChart.invalidate(); - } else if (returningFromPause) { - updateGraphs(); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - if (graphTimer != null) { - graphTimer.cancel(); - } - unbinder.unbind(); - } - - private void plotAllRecordedData() { - recordedGasSensorArray.addAll(gasSensorActivity.recordedGasSensorData); - if (recordedGasSensorArray.size() != 0) { - for (GasSensorData d : recordedGasSensorArray) { - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getPpmValue()); - entries.add(entry); - gasSensorMeter.setWithTremble(false); - gasSensorMeter.setSpeedAt(d.getPpmValue()); - gasValue.setText(String.format(Locale.getDefault(), "%.2f", d.getPpmValue())); - } - y.setAxisMaximum(1024); - y.setAxisMinimum(0); - y.setLabelCount(10); - - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.baro_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } - } - - private void playRecordedData() { - recordedGasSensorArray.addAll(gasSensorActivity.recordedGasSensorData); - try { - if (recordedGasSensorArray.size() > 1) { - GasSensorData i = recordedGasSensorArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - private void processRecordedData(long timeGap) { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } else { - graphTimer = new Timer(); - } - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - if (gasSensorActivity.playingData) { - try { - GasSensorData d = recordedGasSensorArray.get(turns); - turns++; - gasValue.setText(String.format(Locale.getDefault(), "%.2f", d.getPpmValue())); - y.setAxisMaximum(1024); - y.setAxisMinimum(0); - y.setLabelCount(10); - gasSensorMeter.setWithTremble(false); - gasSensorMeter.setSpeedAt(d.getPpmValue()); - - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getPpmValue()); - entries.add(entry); - - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.baro_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } catch (IndexOutOfBoundsException e) { - graphTimer.cancel(); - graphTimer = null; - turns = 0; - gasSensorActivity.playingData = false; - gasSensorActivity.startedPlay = false; - gasSensorActivity.invalidateOptionsMenu(); - } - } - } - }); - } - }, 0, timeGap); - } - - @Override - public void playData() { - resetInstrumentData(); - gasSensorActivity.startedPlay = true; - try { - if (recordedGasSensorArray.size() > 1) { - GasSensorData i = recordedGasSensorArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - @Override - public void stopData() { - if (graphTimer != null) { - graphTimer.cancel(); - graphTimer = null; - } - recordedGasSensorArray.clear(); - entries.clear(); - plotAllRecordedData(); - gasSensorActivity.startedPlay = false; - gasSensorActivity.playingData = false; - turns = 0; - gasSensorActivity.invalidateOptionsMenu(); - } - - @Override - public void saveGraph() { - gasSensorActivity.csvLogger.prepareLogFile(); - gasSensorActivity.csvLogger.writeMetaData(getResources().getString(R.string.gas_sensor)); - gasSensorActivity.csvLogger.writeCSVFile(CSV_HEADER); - for (GasSensorData baroData : gasSensorActivity.recordedGasSensorData) { - gasSensorActivity.csvLogger.writeCSVFile( - new CSVDataLine() - .add(baroData.getTime()) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(baroData.getTime()))) - .add(baroData.getPpmValue()) - .add(baroData.getLat()) - .add(baroData.getLon()) - ); - } - View view = rootView.findViewById(R.id.gas_sensor_linearlayout); - view.setDrawingCacheEnabled(true); - Bitmap b = view.getDrawingCache(); - try { - b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + gasSensorActivity.getSensorName() + - File.separator + CSVLogger.FILE_NAME_FORMAT.format(new Date()) + "_graph.jpg")); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - @Override - public void onPause() { - super.onPause(); - if (graphTimer != null) { - returningFromPause = true; - graphTimer.cancel(); - graphTimer = null; - if (gasSensorActivity.playingData) { - gasSensorActivity.finish(); - } - } - } - - private void updateGraphs() { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } - graphTimer = new Timer(); - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - try { - visualizeData(); - } catch (NullPointerException e) { - } - } - }); - } - }, 0, 1000); - } - - private void writeLogToFile(long timestamp, float ppmValue) { - if (getActivity() != null && gasSensorActivity.isRecording) { - if (gasSensorActivity.writeHeaderToFile) { - gasSensorActivity.csvLogger.prepareLogFile(); - gasSensorActivity.csvLogger.writeCSVFile(CSV_HEADER); - block = timestamp; - gasSensorActivity.recordSensorDataBlockID(new SensorDataBlock(timestamp, gasSensorActivity.getSensorName())); - gasSensorActivity.writeHeaderToFile = !gasSensorActivity.writeHeaderToFile; - } - if (gasSensorActivity.addLocation && gasSensorActivity.gpsLogger.isGPSEnabled()) { - Location location = gasSensorActivity.gpsLogger.getDeviceLocation(); - gasSensorActivity.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(ppmValue) - .add(location.getLatitude()) - .add(location.getLongitude()) - ); - sensorData = new GasSensorData(timestamp, block, ppmValue, location.getLatitude(), location.getLongitude()); - } else { - gasSensorActivity.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(ppmValue) - .add(0.0) - .add(0.0) - ); - sensorData = new GasSensorData(timestamp, block, ppmValue, 0.0, 0.0); - } - gasSensorActivity.recordSensorData(sensorData); - } else { - gasSensorActivity.writeHeaderToFile = true; - } - } - - private void visualizeData() { - double ppmValue = 0d; - if (scienceLab.isConnected()) { - double volt = scienceLab.getVoltage("CH1", 1); - ppmValue = (volt / 3.3) * 1024.0; - gasValue.setText(String.format(Locale.getDefault(), "%.2f", ppmValue)); - gasSensorMeter.setWithTremble(false); - gasSensorMeter.setSpeedAt((float) ppmValue); - timeElapsed = ((System.currentTimeMillis() - startTime) / updatePeriod); - if (timeElapsed != previousTimeElapsed) { - previousTimeElapsed = timeElapsed; - Entry entry = new Entry((float) timeElapsed, (float) ppmValue); - entries.add(entry); - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.gas_sensor_unit)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } - } - writeLogToFile(System.currentTimeMillis(), (float) ppmValue); - } - - private void setupInstruments() { - gasSensorMeter.setMaxSpeed(1024); - XAxis x = mChart.getXAxis(); - this.y = mChart.getAxisLeft(); - YAxis y2 = mChart.getAxisRight(); - - mChart.setTouchEnabled(true); - mChart.setHighlightPerDragEnabled(true); - mChart.setDragEnabled(true); - mChart.setScaleEnabled(true); - mChart.setDrawGridBackground(false); - mChart.setPinchZoom(true); - mChart.setScaleYEnabled(true); - mChart.setBackgroundColor(Color.BLACK); - mChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - mChart.setData(data); - - Legend l = mChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(1024); - y.setAxisMinimum(0); - y.setDrawGridLines(true); - y.setLabelCount(10); - - y2.setDrawGridLines(false); - y2.setMaxWidth(0); - } - - private void resetInstrumentData() { - startTime = System.currentTimeMillis(); - gasValue.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - gasSensorMeter.setSpeedAt(0); - gasSensorMeter.setWithTremble(false); - entries.clear(); - } -} diff --git a/app/src/main/java/io/pslab/fragment/GyroscopeDataFragment.java b/app/src/main/java/io/pslab/fragment/GyroscopeDataFragment.java deleted file mode 100644 index 68de4b1e1..000000000 --- a/app/src/main/java/io/pslab/fragment/GyroscopeDataFragment.java +++ /dev/null @@ -1,516 +0,0 @@ -package io.pslab.fragment; - -import android.graphics.Bitmap; -import android.graphics.Color; -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; -import android.location.Location; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import androidx.annotation.NonNull; - -import com.google.android.material.snackbar.Snackbar; -import androidx.fragment.app.Fragment; - -import android.text.Html; -import android.util.Pair; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.LinearLayout; -import android.widget.TextView; - -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Timer; -import java.util.TimerTask; - -import io.pslab.R; -import io.pslab.activity.GyroscopeActivity; -import io.pslab.interfaces.OperationCallback; -import io.pslab.models.GyroData; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; - -import static android.content.Context.SENSOR_SERVICE; -import static io.pslab.others.CSVLogger.CSV_DIRECTORY; - -public class GyroscopeDataFragment extends Fragment implements OperationCallback { - - private static final CSVDataLine CSV_HEADER = new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("ReadingsX") - .add("ReadingsY") - .add("ReadingsZ") - .add("Latitude") - .add("Longitude"); - private static int updatePeriod = 1000; - private static float highLimit = 1.2f; - private static float gain = 1; - private int turns = 0; - private boolean returningFromPause = false; - private Timer graphTimer; - private SensorManager sensorManager; - private Sensor sensor; - private long startTime, block; - private GyroData sensorData; - private ArrayList recordedGyroArray; - private GyroscopeActivity gyroSensor; - private ArrayList gyroscopeViewFragments = new ArrayList<>(); - private int[] colors = {Color.YELLOW, Color.MAGENTA, Color.GREEN}; - private DecimalFormat df = new DecimalFormat("+#0.0;-#0.0"); - private View rootView; - private TextView noSensorText; - private LinearLayout gyroLinearLayout; - - public static GyroscopeDataFragment newInstance() { - return new GyroscopeDataFragment(); - } - - public static void setParameters(float highLimit, int updatePeriod, String gain) { - GyroscopeDataFragment.highLimit = highLimit; - GyroscopeDataFragment.updatePeriod = updatePeriod; - GyroscopeDataFragment.gain = Integer.valueOf(gain); - } - - public static Pair> getParameters() { - return new Pair<>(updatePeriod, new Pair<>(highLimit, gain)); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - startTime = System.currentTimeMillis(); - gyroSensor = (GyroscopeActivity) getActivity(); - for (GyroscopeViewFragment fragment : gyroscopeViewFragments) { - fragment.clear(); - } - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_gyroscope_data, container, false); - gyroscopeViewFragments.clear(); - gyroscopeViewFragments.add((GyroscopeViewFragment) getChildFragmentManager().findFragmentById(R.id.gyroscope_x_axis_fragment)); - gyroscopeViewFragments.add((GyroscopeViewFragment) getChildFragmentManager().findFragmentById(R.id.gyroscope_y_axis_fragment)); - gyroscopeViewFragments.add((GyroscopeViewFragment) getChildFragmentManager().findFragmentById(R.id.gyroscope_z_axis_fragment)); - - gyroscopeViewFragments.get(1).getGyroAxisImage().setImageResource(R.drawable.phone_y_axis); - gyroscopeViewFragments.get(2).getGyroAxisImage().setImageResource(R.drawable.phone_z_axis); - gyroLinearLayout = rootView.findViewById(R.id.gyro_linearlayout); - noSensorText = new TextView(getContext()); - - setupInstruments(); - return rootView; - } - - @Override - public void onResume() { - super.onResume(); - if (gyroSensor.playingData) { - recordedGyroArray = new ArrayList<>(); - resetInstrumentData(); - playRecordedData(); - } else if (gyroSensor.viewingData) { - recordedGyroArray = new ArrayList<>(); - resetInstrumentData(); - plotAllRecordedData(); - - } else if (!gyroSensor.isRecording) { - updateGraphs(); - initiateGyroSensor(); - } else if (returningFromPause) { - updateGraphs(); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - if (graphTimer != null) { - graphTimer.cancel(); - } - if (sensorManager != null) { - sensorManager.unregisterListener(gyroScopeSensorEventListener); - } else { - gyroLinearLayout.removeView(noSensorText); - } - } - - private void plotAllRecordedData() { - recordedGyroArray.addAll(gyroSensor.recordedGyroData); - if (recordedGyroArray.size() != 0) { - for (int i = 0; i < gyroscopeViewFragments.size(); i++) { - GyroscopeViewFragment fragment = gyroscopeViewFragments.get(i); - for (GyroData d : recordedGyroArray) { - if (fragment.getCurrentMax() < d.getGyro()[i]) { - fragment.setCurrentMax(d.getGyro()[i]); - } - if (fragment.getCurrentMin() < d.getGyro()[i]) { - fragment.setCurrentMin(d.getGyro()[i]); - } - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getGyro()[i]); - fragment.addEntry(entry); - } - - fragment.setYaxis(highLimit); - - LineDataSet dataSet = new LineDataSet(fragment.getEntries(), getString(R.string.gyroscope)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet.setLineWidth(1); - dataSet.setColor(colors[i]); - LineData data = new LineData(dataSet); - fragment.setChartData(data); - } - } - } - - private void playRecordedData() { - recordedGyroArray.addAll(gyroSensor.recordedGyroData); - try { - if (recordedGyroArray.size() > 1) { - GyroData i = recordedGyroArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - private void processRecordedData(long timeGap) { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } else { - graphTimer = new Timer(); - } - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - if (gyroSensor.playingData) { - try { - GyroData d = recordedGyroArray.get(turns); - turns++; - for (int i = 0; i < gyroscopeViewFragments.size(); i++) { - GyroscopeViewFragment fragment = gyroscopeViewFragments.get(i); - StringBuilder builder = new StringBuilder(); - builder.append(df.format(d.getGyro()[i])); - builder.append(" "); - builder.append(getResources().getString(R.string.radian_per_sec_text)); - fragment.setGyroValue(Html.fromHtml(builder.toString())); - - if (fragment.getCurrentMax() < d.getGyro()[i]) { - fragment.setCurrentMax(d.getGyro()[i]); - StringBuilder max_builder = new StringBuilder(); - max_builder.append("Max: "); - max_builder.append(df.format(fragment.getCurrentMax())); - max_builder.append(" "); - max_builder.append(getResources().getString(R.string.radian_per_sec_text)); - fragment.setGyroMax(Html.fromHtml(max_builder.toString())); - } - if (fragment.getCurrentMin() < d.getGyro()[i]) { - fragment.setCurrentMin(d.getGyro()[i]); - StringBuilder min_builder = new StringBuilder(); - min_builder.append("Min: "); - min_builder.append(df.format(fragment.getCurrentMax())); - min_builder.append(" "); - min_builder.append(getResources().getString(R.string.radian_per_sec_text)); - fragment.setGyroMin(Html.fromHtml(min_builder.toString())); - } - - fragment.setYaxis(highLimit); - Entry entryX = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getGyro()[i]); - fragment.addEntry(entryX); - - LineDataSet dataSet = new LineDataSet(fragment.getEntries(), getString(R.string.gyroscope)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet.setLineWidth(1); - dataSet.setColor(colors[i]); - LineData data = new LineData(dataSet); - - fragment.setChartData(data); - } - } catch (IndexOutOfBoundsException e) { - graphTimer.cancel(); - graphTimer = null; - turns = 0; - gyroSensor.playingData = false; - gyroSensor.startedPlay = false; - gyroSensor.invalidateOptionsMenu(); - } - } - } - }); - } - }, 0, timeGap); - } - - @Override - public void playData() { - resetInstrumentData(); - gyroSensor.startedPlay = true; - try { - if (recordedGyroArray.size() > 1) { - GyroData i = recordedGyroArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - @Override - public void stopData() { - if (graphTimer != null) { - graphTimer.cancel(); - graphTimer = null; - } - recordedGyroArray.clear(); - for (GyroscopeViewFragment fragment : gyroscopeViewFragments) { - fragment.clearEntry(); - } - plotAllRecordedData(); - gyroSensor.startedPlay = false; - gyroSensor.playingData = false; - turns = 0; - gyroSensor.invalidateOptionsMenu(); - } - - @Override - public void saveGraph() { - gyroSensor.csvLogger.prepareLogFile(); - gyroSensor.csvLogger.writeMetaData(getResources().getString(R.string.gyroscope)); - gyroSensor.csvLogger.writeCSVFile(CSV_HEADER); - for (GyroData gyroData : gyroSensor.recordedGyroData) { - gyroSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(gyroData.getTime()) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(gyroData.getTime()))) - .add(gyroData.getGyroX()) - .add(gyroData.getGyroY()) - .add(gyroData.getGyroZ()) - .add(gyroData.getLat()) - .add(gyroData.getLon()) - ); - } - View view = rootView.findViewById(R.id.gyro_linearlayout); - view.setDrawingCacheEnabled(true); - Bitmap b = view.getDrawingCache(); - try { - b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + gyroSensor.getSensorName() + - File.separator + CSVLogger.FILE_NAME_FORMAT.format(new Date()) + "_graph.jpg")); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - private void setupInstruments() { - for (GyroscopeViewFragment fragment : gyroscopeViewFragments) { - fragment.setUp(); - } - } - - @Override - public void onPause() { - super.onPause(); - if (graphTimer != null) { - returningFromPause = true; - graphTimer.cancel(); - graphTimer = null; - if (gyroSensor.playingData) { - gyroSensor.finish(); - } - } - } - - private void updateGraphs() { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } - graphTimer = new Timer(); - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - try { - visualizeData(); - } catch (NullPointerException e) { - /* Pass for another refresh round */ - } - } - }); - } - }, 0, updatePeriod); - } - - private void writeLogToFile(long timestamp, float readingX, float readingY, float readingZ) { - if (getActivity() != null && gyroSensor.isRecording) { - if (gyroSensor.writeHeaderToFile) { - gyroSensor.csvLogger.prepareLogFile(); - gyroSensor.csvLogger.writeMetaData(getResources().getString(R.string.gyroscope)); - gyroSensor.csvLogger.writeCSVFile(CSV_HEADER); - gyroSensor.csvLogger.writeCSVFile(CSV_HEADER); - block = timestamp; - gyroSensor.recordSensorDataBlockID(new SensorDataBlock(timestamp, gyroSensor.getSensorName())); - gyroSensor.writeHeaderToFile = !gyroSensor.writeHeaderToFile; - } - if (gyroSensor.addLocation && gyroSensor.gpsLogger.isGPSEnabled()) { - Location location = gyroSensor.gpsLogger.getDeviceLocation(); - gyroSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(readingX) - .add(readingY) - .add(readingZ) - .add(location.getLatitude()) - .add(location.getLongitude()) - ); - sensorData = new GyroData(timestamp, block, gyroscopeViewFragments.get(0).getCurrentValue(), gyroscopeViewFragments.get(1).getCurrentValue(), gyroscopeViewFragments.get(2).getCurrentValue(), location.getLatitude(), location.getLongitude()); - } else { - gyroSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(readingX) - .add(readingY) - .add(readingZ) - .add(0.0) - .add(0.0) - ); - sensorData = new GyroData(timestamp, block, gyroscopeViewFragments.get(0).getCurrentValue(), gyroscopeViewFragments.get(1).getCurrentValue(), gyroscopeViewFragments.get(2).getCurrentValue(), 0.0, 0.0); - } - gyroSensor.recordSensorData(sensorData); - } else { - gyroSensor.writeHeaderToFile = true; - } - } - - private void visualizeData() { - for (int i = 0; i < gyroscopeViewFragments.size(); i++) { - GyroscopeViewFragment fragment = gyroscopeViewFragments.get(i); - long timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - if (timeElapsed != fragment.getPreviousTimeElapsed()) { - fragment.setPreviousTimeElapsed(timeElapsed); - fragment.addEntry(new Entry((float) timeElapsed, fragment.getCurrentValue())); - - LineDataSet dataSet = new LineDataSet(fragment.getEntries(), getString(R.string.gyroscope)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet.setLineWidth(1); - dataSet.setColor(colors[i]); - LineData data = new LineData(dataSet); - - fragment.setChartData(data); - fragment.setYaxis(highLimit); - } - } - Long currentTime = System.currentTimeMillis(); - writeLogToFile(currentTime, gyroscopeViewFragments.get(0).getCurrentValue(), gyroscopeViewFragments.get(1).getCurrentValue(), gyroscopeViewFragments.get(2).getCurrentValue()); - } - - private SensorEventListener gyroScopeSensorEventListener = new SensorEventListener() { - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) {/**/} - - @Override - public void onSensorChanged(SensorEvent event) { - if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) { - for (int i = 0; i < gyroscopeViewFragments.size(); i++) { - GyroscopeViewFragment fragment = gyroscopeViewFragments.get(i); - fragment.setCurrentValue(event.values[i]); - StringBuilder builder = new StringBuilder(); - builder.append(df.format(fragment.getCurrentValue())); - builder.append(" "); - builder.append(getResources().getString(R.string.radian_per_sec_text)); - fragment.setGyroValue(Html.fromHtml(builder.toString())); - - if (fragment.getCurrentValue() > fragment.getCurrentMax()) { - builder.insert(0, getResources().getString(R.string.text_max)); - builder.insert(3, " "); - fragment.setGyroMax(Html.fromHtml(builder.toString())); - fragment.setCurrentMax(fragment.getCurrentValue()); - } else if (fragment.getCurrentValue() < fragment.getCurrentMin()) { - builder.insert(0, getResources().getString(R.string.text_min)); - builder.insert(3, " "); - fragment.setGyroMin(Html.fromHtml(builder.toString())); - fragment.setCurrentMin(fragment.getCurrentValue()); - } - } - } - } - }; - - private void resetInstrumentData() { - for (GyroscopeViewFragment fragment : gyroscopeViewFragments) { - fragment.clear(); - } - } - - private void initiateGyroSensor() { - resetInstrumentData(); - sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE); - if (sensorManager == null) { - noSensorLayoutUpdate(); - } else { - sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); - if (sensor == null) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_gyroscope_sensor), null, null, Snackbar.LENGTH_LONG); - } else { - sensorManager.registerListener(gyroScopeSensorEventListener, - sensor, SensorManager.SENSOR_DELAY_FASTEST); - } - } - } - - private void noSensorLayoutUpdate() { - gyroscopeViewFragments.clear(); - rootView.findViewById(R.id.gyroscope_x_axis_fragment).setVisibility(View.GONE); - rootView.findViewById(R.id.gyroscope_y_axis_fragment).setVisibility(View.GONE); - rootView.findViewById(R.id.gyroscope_z_axis_fragment).setVisibility(View.GONE); - noSensorText.setText(getResources().getString(R.string.no_data_recorded_gyro)); - noSensorText.setAllCaps(true); - gyroLinearLayout.addView(noSensorText); - } -} diff --git a/app/src/main/java/io/pslab/fragment/GyroscopeSettingsFragment.java b/app/src/main/java/io/pslab/fragment/GyroscopeSettingsFragment.java deleted file mode 100644 index 87a6c1e7f..000000000 --- a/app/src/main/java/io/pslab/fragment/GyroscopeSettingsFragment.java +++ /dev/null @@ -1,126 +0,0 @@ -package io.pslab.fragment; - -import android.annotation.SuppressLint; -import android.content.SharedPreferences; -import android.os.Bundle; -import com.google.android.material.snackbar.Snackbar; -import androidx.preference.CheckBoxPreference; -import androidx.preference.EditTextPreference; -import androidx.preference.PreferenceFragmentCompat; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.PSLabPermission; - -public class GyroscopeSettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { - - public static final String KEY_INCLUDE_LOCATION = "include_location_sensor_data"; - public static final String KEY_UPDATE_PERIOD = "setting_gyro_update_period"; - public static final String KEY_HIGH_LIMIT = "setting_gyro_high_limit"; - public static final String KEY_GYROSCOPE_SENSOR_GAIN = "setting_gyro_sensor_gain"; - - private PSLabPermission psLabPermission; - - private EditTextPreference updatePeriodPref; - private EditTextPreference higLimitPref; - private EditTextPreference sensorGainPref; - private CheckBoxPreference locationPreference; - private SharedPreferences sharedPref; - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - setPreferencesFromResource(R.xml.gyro_scope_settings, rootKey); - updatePeriodPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_UPDATE_PERIOD); - higLimitPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_HIGH_LIMIT); - sensorGainPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_GYROSCOPE_SENSOR_GAIN); - locationPreference = (CheckBoxPreference) getPreferenceScreen().findPreference(KEY_INCLUDE_LOCATION); - sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); - - psLabPermission = PSLabPermission.getInstance(); - if (!psLabPermission.checkPermissions(getActivity(), PSLabPermission.MAP_PERMISSION)) { - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putBoolean(LuxMeterSettingFragment.KEY_INCLUDE_LOCATION, true); - editor.apply(); - } - } - - @Override - public void onResume() { - super.onResume(); - locationPreference.setChecked(sharedPref.getBoolean(KEY_INCLUDE_LOCATION, true)); - updatePeriodPref.setSummary(updatePeriodPref.getText() + " ms"); - higLimitPref.setSummary(higLimitPref.getText() + " rad/s"); - sensorGainPref.setSummary(sensorGainPref.getText()); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); - } - - @SuppressLint("ApplySharedPref") - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { - switch (s) { - case KEY_INCLUDE_LOCATION: - if (locationPreference.isChecked()) { - psLabPermission.checkPermissions( - getActivity(), PSLabPermission.MAP_PERMISSION); - } - break; - case KEY_UPDATE_PERIOD: - try { - Integer updatePeriod = Integer.parseInt(updatePeriodPref.getText()); - if (updatePeriod > 2000 || updatePeriod < 100) { - throw new NumberFormatException(); - } else { - updatePeriodPref.setSummary(updatePeriod + " ms"); - } - } catch (NumberFormatException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.update_period_msg),null,null, Snackbar.LENGTH_SHORT); - updatePeriodPref.setSummary("1000 ms"); - updatePeriodPref.setText("1000"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(s, "1000"); - editor.commit(); - } - break; - case KEY_GYROSCOPE_SENSOR_GAIN: - try { - Integer gain = Integer.valueOf(sensorGainPref.getText()); - sensorGainPref.setSummary(String.valueOf(gain)); - } catch (NumberFormatException e) { - sensorGainPref.setSummary("1"); - sensorGainPref.setText("1"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(KEY_GYROSCOPE_SENSOR_GAIN, "1"); - editor.commit(); - } - break; - case KEY_HIGH_LIMIT: - try { - Integer highLimit = Integer.parseInt(higLimitPref.getText()); - if (highLimit > 1000 || highLimit < 0) { - throw new NumberFormatException(); - } else { - higLimitPref.setSummary(String.valueOf(highLimit) + " rad/s"); - } - } catch (NumberFormatException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.high_limit_msg),null,null, Snackbar.LENGTH_SHORT); - higLimitPref.setSummary("20 " + "rad/s"); - higLimitPref.setText("20"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(KEY_HIGH_LIMIT, "20"); - editor.commit(); - } - break; - default: - break; - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/GyroscopeViewFragment.java b/app/src/main/java/io/pslab/fragment/GyroscopeViewFragment.java deleted file mode 100644 index 06c9b6771..000000000 --- a/app/src/main/java/io/pslab/fragment/GyroscopeViewFragment.java +++ /dev/null @@ -1,174 +0,0 @@ -package io.pslab.fragment; - -import android.graphics.Color; -import android.os.Bundle; -import androidx.annotation.NonNull; - -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; - -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; - -import java.util.ArrayList; - -import io.pslab.R; - -public class GyroscopeViewFragment extends Fragment { - - private TextView gyroValue, gyroMin, gyroMax; - private LineChart gyroChart; - private ImageView gyroAxisImage; - private YAxis y; - private float currentMax = Integer.MIN_VALUE; - private float currentMin = Integer.MAX_VALUE; - private float currentValue = 0; - private ArrayList entries; - private long startTime; - private static int updatePeriod = 100; - private long previousTimeElapsed = (System.currentTimeMillis() - startTime) / updatePeriod; - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.gyroscope_list_item, container, false); - - this.gyroValue = rootView.findViewById(R.id.gyro_value); - this.gyroMax = rootView.findViewById(R.id.gyro_max_text); - this.gyroMin = rootView.findViewById(R.id.gyro_min_text); - this.gyroChart = rootView.findViewById(R.id.chart_gyroscope); - this.gyroAxisImage = rootView.findViewById(R.id.axis_image); - this.entries = new ArrayList<>(); - return rootView; - } - - public ImageView getGyroAxisImage() { - return gyroAxisImage; - } - - public void setUp() { - XAxis x = this.gyroChart.getXAxis(); - this.y = this.gyroChart.getAxisLeft(); - YAxis y2 = this.gyroChart.getAxisRight(); - - this.gyroChart.setTouchEnabled(true); - this.gyroChart.setHighlightPerDragEnabled(true); - this.gyroChart.setDragEnabled(true); - this.gyroChart.setScaleEnabled(true); - this.gyroChart.setDrawGridBackground(false); - this.gyroChart.setPinchZoom(true); - this.gyroChart.setScaleYEnabled(true); - this.gyroChart.setBackgroundColor(Color.BLACK); - this.gyroChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - this.gyroChart.setData(data); - - Legend l = this.gyroChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - x.setDrawLabels(false); - - this.y.setTextColor(Color.WHITE); - this.y.setAxisMaximum(currentMax); - this.y.setAxisMinimum(currentMin); - this.y.setDrawGridLines(true); - this.y.setLabelCount(10); - - y2.setDrawGridLines(false); - y2.setMaxWidth(0); - } - - public void setCurrentMax(float currentMax) { - this.currentMax = currentMax; - } - - public float getCurrentMax() { - return this.currentMax; - } - - public void setCurrentMin(float currentMin) { - this.currentMin = currentMin; - } - - public float getCurrentMin() { - return this.currentMin; - } - - public void setCurrentValue(float currentValue) { - this.currentValue = currentValue; - } - - public float getCurrentValue() { - return this.currentValue; - } - - public void addEntry(Entry entry) { - this.entries.add(entry); - } - - public ArrayList getEntries() { - return this.entries; - } - - public void clearEntry() { - this.entries.clear(); - } - - public void setGyroValue(CharSequence value) { - this.gyroValue.setText(value); - } - - public void setGyroMax(CharSequence value) { - this.gyroMax.setText(value); - } - - public void setGyroMin(CharSequence value) { - this.gyroMin.setText(value); - } - - public void setYaxis(float maxLimit) { - this.y.setAxisMaximum(maxLimit); - this.y.setAxisMinimum(-maxLimit); - this.y.setLabelCount(5); - } - - public void setChartData(LineData data) { - this.gyroChart.setData(data); - this.gyroChart.notifyDataSetChanged(); - this.gyroChart.setVisibleXRangeMaximum(3); - this.gyroChart.moveViewToX(data.getEntryCount()); - this.gyroChart.invalidate(); - } - - public void clear() { - this.currentMax = Integer.MIN_VALUE; - this.currentMin = Integer.MAX_VALUE; - this.entries.clear(); - this.gyroChart.clear(); - this.gyroChart.invalidate(); - this.startTime = System.currentTimeMillis(); - } - - public long getPreviousTimeElapsed() { - return previousTimeElapsed; - } - - public void setPreviousTimeElapsed(long previousTimeElapsed) { - this.previousTimeElapsed = previousTimeElapsed; - } -} diff --git a/app/src/main/java/io/pslab/fragment/HelpAndFeedbackFragment.java b/app/src/main/java/io/pslab/fragment/HelpAndFeedbackFragment.java deleted file mode 100644 index a109a6b75..000000000 --- a/app/src/main/java/io/pslab/fragment/HelpAndFeedbackFragment.java +++ /dev/null @@ -1,49 +0,0 @@ -package io.pslab.fragment; - - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; - -import androidx.fragment.app.Fragment; - -import com.google.android.material.appbar.AppBarLayout; - -import org.jetbrains.annotations.NotNull; - -import io.pslab.R; - -import butterknife.BindView; -import butterknife.ButterKnife; - - -public class HelpAndFeedbackFragment extends Fragment { - - @BindView(R.id.appBarAnim) - AppBarLayout appBarLayout; - - public static HelpAndFeedbackFragment newInstance() { - return new HelpAndFeedbackFragment(); - } - - public HelpAndFeedbackFragment() { - } - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_help_feedback, container, false); - ButterKnife.bind(this, view); - - return view; - } - - @Override - public boolean onOptionsItemSelected(@NotNull MenuItem item) { - return super.onOptionsItemSelected(item); - } - -} diff --git a/app/src/main/java/io/pslab/fragment/HomeFragment.java b/app/src/main/java/io/pslab/fragment/HomeFragment.java deleted file mode 100644 index 9574f1e58..000000000 --- a/app/src/main/java/io/pslab/fragment/HomeFragment.java +++ /dev/null @@ -1,206 +0,0 @@ -package io.pslab.fragment; - -import static io.pslab.others.ScienceLabCommon.scienceLab; - -import android.graphics.Bitmap; -import android.graphics.Paint; -import android.os.Bundle; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.webkit.WebView; -import android.webkit.WebViewClient; -import android.widget.Button; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ProgressBar; -import android.widget.ScrollView; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; - -import java.io.IOException; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import io.pslab.R; -import io.pslab.others.InitializationVariable; -import io.pslab.others.ScienceLabCommon; - -public class HomeFragment extends Fragment { - - public static InitializationVariable booleanVariable; - public static boolean isWebViewShowing = false; - @BindView(R.id.tv_device_status) - TextView tvDeviceStatus; - @BindView(R.id.tv_device_version) - TextView tvVersion; - @BindView(R.id.img_device_status) - ImageView imgViewDeviceStatus; - @BindView(R.id.tv_device_description) - TextView deviceDescription; - @BindView(R.id.tv_connect_msg) - LinearLayout tvConnectMsg; - @BindView(R.id.pslab_web_view) - WebView webView; - @BindView(R.id.home_content_scroll_view) - ScrollView svHomeContent; - @BindView(R.id.web_view_progress) - ProgressBar wvProgressBar; - @BindView(R.id.steps_header_text) - TextView stepsHeader; - @BindView(R.id.bluetooth_btn) - Button bluetoothButton; - @BindView(R.id.wifi_btn) - Button wifiButton; - @BindView(R.id.bluetooth_wifi_option_tv) - TextView bluetoothWifiOption; - private boolean deviceFound = false, deviceConnected = false; - private Unbinder unbinder; - - public static HomeFragment newInstance(boolean deviceConnected, boolean deviceFound) { - HomeFragment homeFragment = new HomeFragment(); - homeFragment.deviceConnected = deviceConnected; - homeFragment.deviceFound = deviceFound; - return homeFragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (booleanVariable == null) { - booleanVariable = new InitializationVariable(); - } - booleanVariable.setVariable(true); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.home_fragment, container, false); - unbinder = ButterKnife.bind(this, view); - stepsHeader.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG); - deviceDescription.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG); - wvProgressBar = (ProgressBar) view.findViewById(R.id.web_view_progress); - - if (deviceFound & deviceConnected) { - tvConnectMsg.setVisibility(View.GONE); - try { - tvVersion.setText(scienceLab.getVersion()); - tvVersion.setVisibility(View.VISIBLE); - } catch (IOException e) { - e.printStackTrace(); - } - imgViewDeviceStatus.setImageResource(R.drawable.icons8_usb_connected_100); - tvDeviceStatus.setText(getString(R.string.device_connected_successfully)); - } else { - imgViewDeviceStatus.setImageResource(R.drawable.icons_usb_disconnected_100); - tvDeviceStatus.setText(getString(R.string.device_not_found)); - } - - /* - * The null-checks in the OnClickListener may seem unnecessary, but even though the - * respective variables are initialized before the setter is called, they may contain null - * in later phases of the lifecycle of this Fragment and cause NullPointerExceptions if not - * checked before access. - * - * See: https://github.com/fossasia/pslab-android/issues/2211 - */ - deviceDescription.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (webView == null) { - return; - } - - webView.loadUrl("https://pslab.io"); - webView.getSettings().setDomStorageEnabled(true); - webView.getSettings().setJavaScriptEnabled(true); - svHomeContent.setVisibility(View.GONE); - webView.setWebViewClient(new WebViewClient() { - @Override - public void onPageStarted(WebView view, String url, Bitmap favicon) { - if (wvProgressBar != null) { - wvProgressBar.setIndeterminate(true); - wvProgressBar.setVisibility(View.VISIBLE); - } - } - - public void onPageFinished(WebView view, String url) { - if (wvProgressBar != null) { - wvProgressBar.setVisibility(View.GONE); - } - if (webView != null) { - webView.setVisibility(View.VISIBLE); - } - } - }); - isWebViewShowing = true; - } - }); - - webView.setOnKeyListener(new View.OnKeyListener() { - @Override - public boolean onKey(View v, int keyCode, KeyEvent event) { - if (event.getAction() == KeyEvent.ACTION_DOWN) { - WebView webView = (WebView) v; - switch (keyCode) { - case KeyEvent.KEYCODE_BACK: - if (webView.canGoBack()) { - webView.goBack(); - return true; - } - break; - default: - return false; - } - } - return false; - } - }); - if (ScienceLabCommon.scienceLab.isConnected()) { - bluetoothButton.setVisibility(View.GONE); - wifiButton.setVisibility(View.GONE); - bluetoothWifiOption.setVisibility(View.GONE); - } else { - bluetoothButton.setVisibility(View.VISIBLE); - wifiButton.setVisibility(View.VISIBLE); - bluetoothWifiOption.setVisibility(View.VISIBLE); - } - bluetoothButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - BluetoothScanFragment bluetoothScanFragment = new BluetoothScanFragment(); - bluetoothScanFragment.show(getActivity().getSupportFragmentManager(), "bluetooth"); - bluetoothScanFragment.setCancelable(true); - } - }); - - wifiButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - ESPFragment espFragment = new ESPFragment(); - espFragment.show(getActivity().getSupportFragmentManager(), "wifi"); - espFragment.setCancelable(true); - } - }); - return view; - } - - public void hideWebView() { - webView.setVisibility(View.GONE); - svHomeContent.setVisibility(View.VISIBLE); - isWebViewShowing = false; - webView.loadUrl(""); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } -} diff --git a/app/src/main/java/io/pslab/fragment/InstrumentsFragment.java b/app/src/main/java/io/pslab/fragment/InstrumentsFragment.java deleted file mode 100644 index c60ce6643..000000000 --- a/app/src/main/java/io/pslab/fragment/InstrumentsFragment.java +++ /dev/null @@ -1,242 +0,0 @@ -package io.pslab.fragment; - -import android.content.Context; -import android.content.Intent; -import android.content.res.Configuration; -import android.os.Build; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.util.Supplier; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentActivity; -import androidx.fragment.app.FragmentManager; -import androidx.recyclerview.widget.DefaultItemAnimator; -import androidx.recyclerview.widget.GridLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.pslab.R; -import io.pslab.activity.AccelerometerActivity; -import io.pslab.activity.BarometerActivity; -import io.pslab.activity.CompassActivity; -import io.pslab.activity.DustSensorActivity; -import io.pslab.activity.GasSensorActivity; -import io.pslab.activity.GyroscopeActivity; -import io.pslab.activity.LogicalAnalyzerActivity; -import io.pslab.activity.LuxMeterActivity; -import io.pslab.activity.MultimeterActivity; -import io.pslab.activity.OscilloscopeActivity; -import io.pslab.activity.PowerSourceActivity; -import io.pslab.activity.RoboticArmActivity; -import io.pslab.activity.SensorActivity; -import io.pslab.activity.SoundMeterActivity; -import io.pslab.activity.ThermometerActivity; -import io.pslab.activity.WaveGeneratorActivity; -import io.pslab.adapters.ApplicationAdapter; -import io.pslab.items.ApplicationItem; - - -/** - * Created by viveksb007 on 29/3/17. - */ - -public final class InstrumentsFragment extends Fragment { - - private Map> intentSupplierMap; - - private ApplicationAdapter applicationAdapter; - private List applicationItemList; - private Context context; - - public static InstrumentsFragment newInstance() { - return new InstrumentsFragment(); - } - - @Nullable - @Override - public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable final ViewGroup container, - @Nullable final Bundle savedInstanceState) { - intentSupplierMap = generateIntentMap(); - - final View view = inflater.inflate(R.layout.applications_fragment, container, false); - context = getContext(); - applicationItemList = new ArrayList<>(); - applicationAdapter = new ApplicationAdapter(applicationItemList, - item -> { - final String applicationName = item.getApplicationName(); - final Intent intent = createIntent(applicationName); - if (intent != null) { - startActivity(intent); - } - }); - final int rows = context.getResources().getConfiguration().orientation - == Configuration.ORIENTATION_PORTRAIT ? 1 : 2; - - initiateViews(view, rows); - - return view; - } - - private Intent createIntent(@NonNull final String applicationName) { - final Supplier callable = intentSupplierMap.get(applicationName); - return callable == null ? null : callable.get(); - } - - /** - * Initiate Recycler view - */ - private void initiateViews(@NonNull final View view, final int rows) { - final RecyclerView listView = view.findViewById(R.id.applications_recycler_view); - final RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(context, rows); - listView.setLayoutManager(mLayoutManager); - new LoadList().doTask(listView); - - } - - /** - * Generate an array of Application Items and add them to the adapter - */ - private class LoadList { - - private void doTask(@NonNull final RecyclerView listView) { - - final int[] descriptions = { - R.string.oscilloscope_description, - R.string.multimeter_description, - R.string.logic_analyzer_description, - R.string.sensors_description, - R.string.wave_generator_description, - R.string.power_source_description, - R.string.lux_meter_description, - R.string.accelerometer_description, - R.string.baro_meter_description, - R.string.compass_description, - R.string.gyroscope_description, - R.string.thermometer_desc, - R.string.robotic_arm_description, - R.string.gas_sensor_description, - R.string.dust_sensor_description, - R.string.sound_meter_desc - }; - - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.oscilloscope), R.drawable.tile_icon_oscilloscope, getResources().getString(descriptions[0])) - ); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.multimeter), R.drawable.tile_icon_multimeter, getResources().getString(descriptions[1])) - ); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.logical_analyzer), R.drawable.tile_icon_logic_analyzer, getResources().getString(descriptions[2])) - ); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.sensors), R.drawable.tile_icon_sensors, getResources().getString(descriptions[3])) - ); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.wave_generator), R.drawable.tile_icon_wave_generator, getResources().getString(descriptions[4])) - ); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.power_source), R.drawable.tile_icon_power_source, getResources().getString(descriptions[5])) - ); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.lux_meter), R.drawable.tile_icon_lux_meter, getResources().getString(descriptions[6])) - ); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.accelerometer), R.drawable.tile_icon_accelerometer, getResources().getString(descriptions[7])) - ); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.baro_meter), R.drawable.tile_icon_barometer, getResources().getString(descriptions[8]) - )); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.compass), R.drawable.tile_icon_compass, getResources().getString(descriptions[9]) - )); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.gyroscope), R.drawable.gyroscope_logo, getResources().getString(descriptions[10]) - )); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.thermometer), R.drawable.thermometer_logo, getResources().getString(descriptions[11]) - )); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.robotic_arm), R.drawable.robotic_arm, getResources().getString(descriptions[12]) - )); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.gas_sensor), R.drawable.tile_icon_gas, getResources().getString(descriptions[13]) - )); - applicationItemList.add(new ApplicationItem( - getResources().getString(R.string.dust_sensor), R.drawable.tile_icon_gas, getResources().getString(descriptions[14]) - )); - applicationItemList.add(new ApplicationItem( - getString(R.string.sound_meter), R.drawable.tile_icon_gas, getString(descriptions[15]) - )); - listView.setItemAnimator(new DefaultItemAnimator()); - listView.setAdapter(applicationAdapter); - - } - } - - @Override - public void onConfigurationChanged(@NonNull final Configuration newConfig) { - super.onConfigurationChanged(newConfig); - - final FragmentActivity activity = getActivity(); - if (activity != null) { - final FragmentManager fragmentManager = activity.getSupportFragmentManager(); - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { - fragmentManager.beginTransaction().detach(this).attach(this).commitAllowingStateLoss(); - } else { - fragmentManager.beginTransaction().detach(this).commitNowAllowingStateLoss(); - fragmentManager.beginTransaction().attach(this).commitNowAllowingStateLoss(); - } - } - } - - private Map> generateIntentMap() { - final Map> map = new HashMap<>(); - - map.put(getString(R.string.oscilloscope), () -> { - final Intent intent = new Intent(context, OscilloscopeActivity.class); - intent.putExtra("who", "Instruments"); - return intent; - }); - map.put(getString(R.string.multimeter), () -> - new Intent(context, MultimeterActivity.class)); - map.put(getString(R.string.logical_analyzer), () -> - new Intent(context, LogicalAnalyzerActivity.class)); - map.put(getString(R.string.sensors), () -> - new Intent(context, SensorActivity.class)); - map.put(getString(R.string.wave_generator), () -> - new Intent(context, WaveGeneratorActivity.class)); - map.put(getString(R.string.power_source), () -> - new Intent(context, PowerSourceActivity.class)); - map.put(getString(R.string.lux_meter), () -> - new Intent(context, LuxMeterActivity.class)); - map.put(getString(R.string.accelerometer), () -> - new Intent(context, AccelerometerActivity.class)); - map.put(getString(R.string.baro_meter), () -> - new Intent(context, BarometerActivity.class)); - map.put(getString(R.string.compass), () -> - new Intent(context, CompassActivity.class)); - map.put(getString(R.string.gyroscope), () -> - new Intent(context, GyroscopeActivity.class)); - map.put(getString(R.string.thermometer), () -> - new Intent(context, ThermometerActivity.class)); - map.put(getString(R.string.robotic_arm), () -> - new Intent(context, RoboticArmActivity.class)); - map.put(getString(R.string.gas_sensor), () -> - new Intent(context, GasSensorActivity.class)); - map.put(getString(R.string.dust_sensor), () -> - new Intent(context, DustSensorActivity.class)); - map.put(getString(R.string.sound_meter), () -> - new Intent(context, SoundMeterActivity.class)); - - return map; - } -} diff --git a/app/src/main/java/io/pslab/fragment/LALogicLinesFragment.java b/app/src/main/java/io/pslab/fragment/LALogicLinesFragment.java deleted file mode 100644 index 1dadeba1e..000000000 --- a/app/src/main/java/io/pslab/fragment/LALogicLinesFragment.java +++ /dev/null @@ -1,1475 +0,0 @@ -package io.pslab.fragment; - -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.graphics.Color; -import android.location.Location; -import android.location.LocationManager; -import android.os.AsyncTask; -import android.os.Bundle; -import android.util.DisplayMetrics; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.LinearLayout; -import android.widget.ProgressBar; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.annotation.Nullable; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.fragment.app.Fragment; -import androidx.viewpager.widget.ViewPager; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; -import com.github.mikephil.charting.highlight.Highlight; -import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; -import com.github.mikephil.charting.listener.OnChartValueSelectedListener; -import com.google.android.material.snackbar.Snackbar; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; - -import butterknife.ButterKnife; -import in.goodiebag.carouselpicker.CarouselPicker; -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.activity.DataLoggerActivity; -import io.pslab.activity.LogicalAnalyzerActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.digitalChannel.DigitalChannel; -import io.pslab.models.LogicAnalyzerData; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.GPSLogger; -import io.pslab.others.LocalDataLog; -import io.pslab.others.LogicAnalyzerAxisFormatter; -import io.pslab.others.ScienceLabCommon; -import io.realm.Realm; -import io.realm.RealmObject; -import io.realm.RealmResults; - -/** - * Created by viveksb007 on 9/6/17. - */ - -public class LALogicLinesFragment extends Fragment { - - private static final int EVERY_EDGE = 1; - private static final int DISABLED = 0; - private static final int EVERY_FOURTH_RISING_EDGE = 4; - private static final int EVERY_RISING_EDGE = 3; - private static final int EVERY_FALLING_EDGE = 2; - - private static final CSVDataLine CSV_HEADER = - new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("Channel") - .add("ChannelMode") - .add("xData") - .add("yData") - .add("lat") - .add("lon"); - - private final Object lock = new Object(); - List tempInput; - DigitalChannel digitalChannel; - ArrayList digitalChannelArray; - List dataSets; - - // Graph Plot - private CarouselPicker carouselPicker; - private LinearLayout llChannel1, llChannel2, llChannel3, llChannel4; - private Spinner channelSelectSpinner1, channelSelectSpinner2, channelSelectSpinner3, channelSelectSpinner4; - private Spinner edgeSelectSpinner1, edgeSelectSpinner2, edgeSelectSpinner3, edgeSelectSpinner4; - private Button analyze_button; - private ProgressBar progressBar; - private CaptureOne captureOne; - private CaptureTwo captureTwo; - private CaptureThree captureThree; - private CaptureFour captureFour; - private int currentChannel = 0; - private int[] colors = new int[]{Color.MAGENTA, Color.GREEN, Color.CYAN, Color.YELLOW}; - private OnChartValueSelectedListener listener; - - private Activity activity; - private int channelMode; - private ScienceLab scienceLab; - private LineChart logicLinesChart; - private ArrayList channelNames = new ArrayList<>(); - private ArrayList edgesNames = new ArrayList<>(); - private TextView tvTimeUnit, xCoordinateText; - private Realm realm; - private GPSLogger gpsLogger; - private CSVLogger csvLogger; - private ArrayList recordXAxis; - private ArrayList recordYAxis; - private ArrayList recordChannelMode; - private String[] channels = new String[]{"LA1", "LA2", "LA3", "LA4"}; - private HashMap channelMap; - private ArrayList channelSelectSpinners; - private ArrayList edgeSelectSpinners; - private View rootView; - - public static LALogicLinesFragment newInstance(Activity activity) { - LALogicLinesFragment laLogicLinesFragment = new LALogicLinesFragment(); - laLogicLinesFragment.activity = activity; - return laLogicLinesFragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ButterKnife.bind(getActivity()); - scienceLab = ScienceLabCommon.scienceLab; - realm = LocalDataLog.with().getRealm(); - gpsLogger = new GPSLogger(getContext(), (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE)); - csvLogger = new CSVLogger(getString(R.string.logical_analyzer)); - recordXAxis = new ArrayList<>(); - recordYAxis = new ArrayList<>(); - recordChannelMode = new ArrayList<>(); - channelSelectSpinners = new ArrayList<>(); - edgeSelectSpinners = new ArrayList<>(); - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.logic_analyzer_logic_lines, container, false); - - // Heading - tvTimeUnit = rootView.findViewById(R.id.la_tv_time_unit); - tvTimeUnit.setText(getString(R.string.time_unit_la)); - - // Carousel View - carouselPicker = rootView.findViewById(R.id.carouselPicker); - llChannel1 = rootView.findViewById(R.id.ll_chart_channel_1); - llChannel1.setVisibility(View.VISIBLE); - llChannel2 = rootView.findViewById(R.id.ll_chart_channel_2); - llChannel2.setVisibility(View.GONE); - llChannel3 = rootView.findViewById(R.id.ll_chart_channel_3); - llChannel3.setVisibility(View.GONE); - llChannel4 = rootView.findViewById(R.id.ll_chart_channel_4); - llChannel4.setVisibility(View.GONE); - channelSelectSpinner1 = rootView.findViewById(R.id.channel_select_spinner_1); - channelSelectSpinner2 = rootView.findViewById(R.id.channel_select_spinner_2); - channelSelectSpinner3 = rootView.findViewById(R.id.channel_select_spinner_3); - channelSelectSpinner4 = rootView.findViewById(R.id.channel_select_spinner_4); - edgeSelectSpinner1 = rootView.findViewById(R.id.edge_select_spinner_1); - edgeSelectSpinner2 = rootView.findViewById(R.id.edge_select_spinner_2); - edgeSelectSpinner3 = rootView.findViewById(R.id.edge_select_spinner_3); - edgeSelectSpinner4 = rootView.findViewById(R.id.edge_select_spinner_4); - analyze_button = rootView.findViewById(R.id.analyze_button); - channelMode = 1; - channelSelectSpinners.add(channelSelectSpinner1); - channelSelectSpinners.add(channelSelectSpinner2); - channelSelectSpinners.add(channelSelectSpinner3); - channelSelectSpinners.add(channelSelectSpinner4); - - edgeSelectSpinners.add(edgeSelectSpinner1); - edgeSelectSpinners.add(edgeSelectSpinner2); - edgeSelectSpinners.add(edgeSelectSpinner3); - edgeSelectSpinners.add(edgeSelectSpinner4); - channelMap = new HashMap<>(); - channelMap.put(channels[0], 0); - channelMap.put(channels[1], 1); - channelMap.put(channels[2], 2); - channelMap.put(channels[3], 3); - // Axis Indicator - xCoordinateText = rootView.findViewById(R.id.x_coordinate_text); - xCoordinateText.setText("Time: 0.0 mS"); - progressBar = rootView.findViewById(R.id.la_progressBar); - progressBar.setVisibility(View.GONE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(false); - - // Declaring digital data set - digitalChannelArray = new ArrayList<>(); - dataSets = new ArrayList<>(); - - // Creating base layout for chart - logicLinesChart = rootView.findViewById(R.id.chart_la); - logicLinesChart.setBorderWidth(2); - Legend legend = logicLinesChart.getLegend(); - legend.setTextColor(Color.WHITE); - XAxis xAxis = logicLinesChart.getXAxis(); - xAxis.setPosition(XAxis.XAxisPosition.TOP); - xAxis.setTextColor(Color.WHITE); - - setCarouselPicker(); - setAdapters(); - LogicalAnalyzerActivity laActivity = (LogicalAnalyzerActivity) getActivity(); - if (laActivity.isPlayback) { - if (laActivity.recordedLAData.isEmpty()) { - CustomSnackBar.showSnackBar(container, getString(R.string.no_playback_data), - null, null, Snackbar.LENGTH_SHORT); - } else { - setPlayBackData(laActivity.recordedLAData); - } - } - return rootView; - } - - public void logData() { - long block = System.currentTimeMillis(); - double lat; - double lon; - if (gpsLogger.isGPSEnabled()) { - Location location = gpsLogger.getDeviceLocation(); - if (location != null) { - lat = location.getLatitude(); - lon = location.getLongitude(); - } else { - lat = 0.0; - lon = 0.0; - } - } else { - lat = 0.0; - lon = 0.0; - } - csvLogger.prepareLogFile(); - csvLogger.writeMetaData(getContext().getResources().getString(R.string.logical_analyzer)); - csvLogger.writeCSVFile(CSV_HEADER); - recordSensorDataBlockID(new SensorDataBlock(block, getResources().getString(R.string.logical_analyzer))); - long timestamp = System.currentTimeMillis(); - String timeData = timestamp + "," + CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp)); - for (int i = 0; i < recordXAxis.size(); i++) { - recordSensorData(new LogicAnalyzerData(timestamp + i, block, channels[i], recordChannelMode.get(i), recordXAxis.get(i), recordYAxis.get(i), lat, lon)); - - CSVDataLine data = new CSVDataLine() - .add(timeData) - .add(channels[i]) - .add(recordChannelMode.get(i)) - .add(recordXAxis.get(i)) - .add(recordYAxis.get(i)) - .add(lat) - .add(lon); - csvLogger.writeCSVFile(data); - } - CustomSnackBar.showSnackBar(rootView, - getString(R.string.csv_store_text) + " " + csvLogger.getCurrentFilePath() - , getString(R.string.open), new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(getContext(), DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getResources().getString(R.string.logical_analyzer)); - startActivity(intent); - } - }, Snackbar.LENGTH_SHORT); - } - - private void setPlayBackData(RealmResults data) { - analyze_button.setVisibility(View.GONE); - currentChannel = 0; - setViewVisibility(data.size() - 1); - channelNames.clear(); - disableSpinners(); - carouselPicker.setCurrentItem(data.size() - 1); - for (int i = 0; i < data.size(); i++) { - LogicAnalyzerData laData = data.get(i); - channelNames.add(laData.getChannel()); - edgeSelectSpinners.get(i).setSelection(laData.getChannelMode() - 1); - channelSelectSpinners.get(i).setSelection(channelMap.get(laData.getChannel())); - String[] xPoints = laData.getDataX().split(" "); - String[] yPoints = laData.getDataY().split(" "); - int n = Math.min(xPoints.length, yPoints.length); - double[] xaxis = new double[n]; - double[] yaxis = new double[n]; - for (int j = 0; j < n; j++) { - xaxis[j] = Double.valueOf(xPoints[j]); - yaxis[j] = Double.valueOf(yPoints[j]); - } - switch (laData.getChannelMode()) { - case 1: - singleChannelEveryEdge(xaxis, yaxis); - break; - case 4: - singleChannelFourthRisingEdge(xaxis); - break; - case 3: - singleChannelRisingEdges(xaxis, yaxis); - break; - case 2: - singleChannelFallingEdges(xaxis, yaxis); - break; - default: - singleChannelOtherEdges(xaxis, yaxis); - break; - } - currentChannel++; - } - logicLinesChart.setData(new LineData(dataSets)); - logicLinesChart.invalidate(); - - YAxis left = logicLinesChart.getAxisLeft(); - left.setValueFormatter(new LogicAnalyzerAxisFormatter(channelNames)); - left.setTextColor(Color.WHITE); - left.setGranularity(1f); - left.setTextSize(12f); - logicLinesChart.getAxisRight().setDrawLabels(false); - logicLinesChart.getDescription().setEnabled(false); - logicLinesChart.setScaleYEnabled(false); - } - - @Override - public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - - carouselPicker.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { - @Override - public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { - } - - @Override - public void onPageSelected(int position) { - } - - @Override - public void onPageScrollStateChanged(int state) { - if (state == 0) { - setViewVisibility(carouselPicker.getCurrentItem()); - } - } - }); - - analyze_button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (channelMode > 0) { - if (scienceLab != null && scienceLab.isConnected()) { - analyze_button.setClickable(false); - - // Change all variables to default value - currentChannel = 0; - dataSets.clear(); - digitalChannelArray.clear(); - channelNames.clear(); - edgesNames.clear(); - logicLinesChart.clear(); - logicLinesChart.invalidate(); - - switch (channelMode) { - case 1: - channelNames.add(channelSelectSpinner1.getSelectedItem().toString()); - edgesNames.add(edgeSelectSpinner1.getSelectedItem().toString()); - break; - case 2: - channelNames.add(channelSelectSpinner1.getSelectedItem().toString()); - channelNames.add(channelSelectSpinner2.getSelectedItem().toString()); - edgesNames.add(edgeSelectSpinner1.getSelectedItem().toString()); - edgesNames.add(edgeSelectSpinner2.getSelectedItem().toString()); - break; - case 3: - channelNames.add(channelSelectSpinner1.getSelectedItem().toString()); - channelNames.add(channelSelectSpinner2.getSelectedItem().toString()); - channelNames.add(channelSelectSpinner3.getSelectedItem().toString()); - edgesNames.add(edgeSelectSpinner1.getSelectedItem().toString()); - edgesNames.add(edgeSelectSpinner2.getSelectedItem().toString()); - edgesNames.add(edgeSelectSpinner3.getSelectedItem().toString()); - break; - case 4: - channelNames.add(channelSelectSpinner1.getSelectedItem().toString()); - channelNames.add(channelSelectSpinner2.getSelectedItem().toString()); - channelNames.add(channelSelectSpinner3.getSelectedItem().toString()); - channelNames.add(channelSelectSpinner4.getSelectedItem().toString()); - edgesNames.add(edgeSelectSpinner1.getSelectedItem().toString()); - edgesNames.add(edgeSelectSpinner2.getSelectedItem().toString()); - edgesNames.add(edgeSelectSpinner3.getSelectedItem().toString()); - edgesNames.add(edgeSelectSpinner4.getSelectedItem().toString()); - break; - default: - channelNames.add(channelSelectSpinner1.getSelectedItem().toString()); - edgesNames.add(edgeSelectSpinner1.getSelectedItem().toString()); - break; - } - Thread monitor; - switch (channelMode) { - case 1: - progressBar.setVisibility(View.VISIBLE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(true); - monitor = new Thread(new Runnable() { - @Override - public void run() { - captureOne = new CaptureOne(); - captureOne.execute(channelNames.get(0), edgesNames.get(0)); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - }); - monitor.start(); - break; - case 2: - progressBar.setVisibility(View.VISIBLE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(true); - monitor = new Thread(new Runnable() { - @Override - public void run() { - captureTwo = new CaptureTwo(); - ArrayList channels = new ArrayList<>(); - channels.add(channelNames.get(0)); - channels.add(channelNames.get(1)); - ArrayList edges = new ArrayList<>(); - edges.add(edgesNames.get(0)); - edges.add(edgesNames.get(1)); - captureTwo.execute(channels, edges); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - }); - monitor.start(); - break; - case 3: - progressBar.setVisibility(View.VISIBLE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(true); - monitor = new Thread(new Runnable() { - @Override - public void run() { - captureThree = new CaptureThree(); - ArrayList channels = new ArrayList<>(); - channels.add(channelNames.get(0)); - channels.add(channelNames.get(1)); - channels.add(channelNames.get(2)); - ArrayList edges = new ArrayList<>(); - edges.add(edgesNames.get(0)); - edges.add(edgesNames.get(1)); - edges.add(edgesNames.get(2)); - captureThree.execute(channels, edges); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - }); - monitor.start(); - break; - case 4: - progressBar.setVisibility(View.VISIBLE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(true); - monitor = new Thread(new Runnable() { - @Override - public void run() { - captureFour = new CaptureFour(); - ArrayList channels = new ArrayList<>(); - channels.add(channelNames.get(0)); - channels.add(channelNames.get(1)); - channels.add(channelNames.get(2)); - channels.add(channelNames.get(3)); - ArrayList edges = new ArrayList<>(); - edges.add(edgesNames.get(0)); - edges.add(edgesNames.get(1)); - edges.add(edgesNames.get(2)); - edges.add(edgesNames.get(3)); - captureFour.execute(channels, edges); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - }); - monitor.start(); - break; - default: - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.needs_implementation), null, null, Snackbar.LENGTH_SHORT); - break; - } - - // Setting cursor to display time at highlighted points - listener = new OnChartValueSelectedListener() { - @Override - public void onValueSelected(Entry e, Highlight h) { - double result = Math.round(e.getX() * 100.0) / 100.0; - xCoordinateText.setText("Time: " + DataFormatter.formatDouble(result, DataFormatter.LOW_PRECISION_FORMAT) + " mS"); - } - - @Override - public void onNothingSelected() { - - } - }; - logicLinesChart.setOnChartValueSelectedListener(listener); - } else - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.device_not_found), null, null, Snackbar.LENGTH_SHORT); - } - } - }); - } - - private void disableSpinners() { - channelSelectSpinner1.setEnabled(false); - channelSelectSpinner2.setEnabled(false); - channelSelectSpinner3.setEnabled(false); - channelSelectSpinner4.setEnabled(false); - edgeSelectSpinner1.setEnabled(false); - edgeSelectSpinner2.setEnabled(false); - edgeSelectSpinner3.setEnabled(false); - edgeSelectSpinner4.setEnabled(false); - carouselPicker.setEnabled(false); - } - - private void setViewVisibility(int mode) { - switch (mode) { - case 0: - channelMode = 1; - setAdapters(); - llChannel1.setVisibility(View.VISIBLE); - llChannel2.setVisibility(View.GONE); - llChannel3.setVisibility(View.GONE); - llChannel4.setVisibility(View.GONE); - channelSelectSpinner1.setEnabled(true); - break; - case 1: - channelMode = 2; - setAdapterForTwoChannelMode(); - llChannel1.setVisibility(View.VISIBLE); - llChannel2.setVisibility(View.VISIBLE); - llChannel3.setVisibility(View.GONE); - llChannel4.setVisibility(View.GONE); - channelSelectSpinner1.setEnabled(true); - channelSelectSpinner2.setEnabled(true); - break; - case 2: - channelMode = 3; - setAdapters(); - llChannel1.setVisibility(View.VISIBLE); - llChannel2.setVisibility(View.VISIBLE); - llChannel3.setVisibility(View.VISIBLE); - llChannel4.setVisibility(View.GONE); - channelSelectSpinner1.setSelection(0); - channelSelectSpinner2.setSelection(1); - channelSelectSpinner3.setSelection(2); - channelSelectSpinner1.setEnabled(true); - channelSelectSpinner2.setEnabled(true); - channelSelectSpinner3.setEnabled(true); - break; - case 3: - channelMode = 4; - setAdapters(); - llChannel1.setVisibility(View.VISIBLE); - llChannel2.setVisibility(View.VISIBLE); - llChannel3.setVisibility(View.VISIBLE); - llChannel4.setVisibility(View.VISIBLE); - channelSelectSpinner1.setSelection(0); - channelSelectSpinner2.setSelection(1); - channelSelectSpinner3.setSelection(2); - channelSelectSpinner4.setSelection(3); - channelSelectSpinner1.setEnabled(true); - channelSelectSpinner2.setEnabled(true); - channelSelectSpinner3.setEnabled(true); - channelSelectSpinner4.setEnabled(true); - break; - default: - channelMode = 1; - setAdapters(); - llChannel1.setVisibility(View.VISIBLE); - llChannel2.setVisibility(View.GONE); - llChannel3.setVisibility(View.GONE); - llChannel4.setVisibility(View.GONE); - channelSelectSpinner1.setEnabled(true); - break; - } - } - - /** - * Plots every edge of a digital pulse for one channel at a time - * - * @param xData Data points fetched for X-axis - * @param yData Data points fetched for Y-axis - */ - - private void singleChannelEveryEdge(double[] xData, double[] yData) { - tempInput = new ArrayList<>(); - int[] temp = new int[xData.length]; - int[] yAxis = new int[yData.length]; - - for (int i = 0; i < xData.length; i++) { - temp[i] = (int) xData[i]; - yAxis[i] = (int) yData[i]; - } - - ArrayList xaxis = new ArrayList<>(); - ArrayList yaxis = new ArrayList<>(); - xaxis.add(temp[0]); - yaxis.add(yAxis[0]); - - for (int i = 1; i < xData.length; i++) { - if (temp[i] != temp[i - 1]) { - xaxis.add(temp[i]); - yaxis.add(yAxis[i]); - } - } - - // Add data to axis in actual graph - if (yaxis.size() > 1) { - if (yaxis.get(1).equals(yaxis.get(0))) - tempInput.add(new Entry(xaxis.get(0), yaxis.get(0) + 2 * currentChannel)); - else { - tempInput.add(new Entry(xaxis.get(0), yaxis.get(0) + 2 * currentChannel)); - tempInput.add(new Entry(xaxis.get(0), yaxis.get(1) + 2 * currentChannel)); - } - for (int i = 1; i < xaxis.size() - 1; i++) { - if (yaxis.get(i).equals(yaxis.get(i + 1))) - tempInput.add(new Entry(xaxis.get(i), yaxis.get(i) + 2 * currentChannel)); - else { - tempInput.add(new Entry(xaxis.get(i), yaxis.get(i) + 2 * currentChannel)); - tempInput.add(new Entry(xaxis.get(i), yaxis.get(i + 1) + 2 * currentChannel)); - } - } - tempInput.add(new Entry(xaxis.get(xaxis.size() - 1), yaxis.get(xaxis.size() - 1) + 2 * currentChannel)); - } else { - tempInput.add(new Entry(xaxis.get(0), yaxis.get(0) + 2 * currentChannel)); - } - - setLineDataSet(); - } - - /** - * Plots every fourth rising edge of a digital pulse for one channel at a time - * - * @param xData Data points fetched for X-axis - */ - - private void singleChannelFourthRisingEdge(double[] xData) { - tempInput = new ArrayList<>(); - int xaxis = (int) xData[0]; - tempInput.add(new Entry(xaxis, 0 + 2 * currentChannel)); - tempInput.add(new Entry(xaxis, 1 + 2 * currentChannel)); - tempInput.add(new Entry(xaxis, 0 + 2 * currentChannel)); - int check = xaxis; - int count = 0; - - if (xData.length > 1) { - for (int i = 1; i < xData.length; i++) { - xaxis = (int) xData[i]; - if (xaxis != check) { - if (count == 3) { - tempInput.add(new Entry(xaxis, 0 + 2 * currentChannel)); - tempInput.add(new Entry(xaxis, 1 + 2 * currentChannel)); - tempInput.add(new Entry(xaxis, 0 + 2 * currentChannel)); - count = 0; - } else - count++; - check = xaxis; - } - } - } - - setLineDataSet(); - } - - /** - * Plots every rising edges of a digital pulse for one channel at a time - * - * @param xData Data points fetched for X-axis - * @param yData Data points fetched for Y-axis - */ - - private void singleChannelRisingEdges(double[] xData, double[] yData) { - tempInput = new ArrayList<>(); - - for (int i = 1; i < xData.length; i += 6) { - tempInput.add(new Entry((int) xData[i], (int) yData[i] + 2 * currentChannel)); - tempInput.add(new Entry((int) xData[i + 1], (int) yData[i + 1] + 2 * currentChannel)); - tempInput.add(new Entry((int) xData[i + 2], (int) yData[i + 2] + 2 * currentChannel)); - } - - setLineDataSet(); - } - - /** - * Plots every falling edges of a digital pulse for one channel at a time - * - * @param xData Data points fetched for X-axis - * @param yData Data points fetched for Y-axis - */ - - private void singleChannelFallingEdges(double[] xData, double[] yData) { - tempInput = new ArrayList<>(); - - for (int i = 4; i < xData.length; i += 6) { - tempInput.add(new Entry((int) xData[i], (int) yData[i] + 2 * currentChannel)); - tempInput.add(new Entry((int) xData[i + 1], (int) yData[i + 1] + 2 * currentChannel)); - tempInput.add(new Entry((int) xData[i + 2], (int) yData[i + 2] + 2 * currentChannel)); - } - - setLineDataSet(); - } - - /** - * Plots every data point fetched for a digital pulse (default case) - * - * @param xData Data points fetched for X-axis - * @param yData Data points fetched for Y-axis - */ - - private void singleChannelOtherEdges(double[] xData, double[] yData) { - tempInput = new ArrayList<>(); - - for (int i = 0; i < xData.length; i++) { - int xaxis = (int) xData[i]; - int yaxis = (int) yData[i]; - tempInput.add(new Entry(xaxis, yaxis + 2 * currentChannel)); - } - - setLineDataSet(); - } - - /** - * Plot the entries available in tuple (X-axis, Y-axis) on the graph - */ - - private void setLineDataSet() { - LineDataSet lineDataSet = new LineDataSet(tempInput, channelNames.get(currentChannel)); - lineDataSet.setColor(colors[currentChannel]); - lineDataSet.setCircleRadius(1); - lineDataSet.setLineWidth(2); - lineDataSet.setCircleColor(Color.GREEN); - lineDataSet.setDrawValues(false); - lineDataSet.setDrawCircles(false); - lineDataSet.setHighLightColor(getResources().getColor(R.color.golden)); - dataSets.add(lineDataSet); - } - - /** - * Sets adapters to spinners for all modes except for TwoChannel Mode - */ - - private void setAdapters() { - String[] channels = getResources().getStringArray(R.array.channel_choices); - String[] edges = getResources().getStringArray(R.array.edge_choices); - - ArrayAdapter channel_adapter = new ArrayAdapter<>(getContext(), R.layout.modified_spinner_dropdown_list, channels); - ArrayAdapter edges_adapter = new ArrayAdapter<>(getContext(), R.layout.modified_spinner_dropdown_list, edges); - - channelSelectSpinner1.setAdapter(channel_adapter); - channelSelectSpinner2.setAdapter(channel_adapter); - channelSelectSpinner3.setAdapter(channel_adapter); - channelSelectSpinner4.setAdapter(channel_adapter); - - edgeSelectSpinner1.setAdapter(edges_adapter); - edgeSelectSpinner2.setAdapter(edges_adapter); - edgeSelectSpinner3.setAdapter(edges_adapter); - edgeSelectSpinner4.setAdapter(edges_adapter); - - } - - /** - * Sets adapters to spinners for TwoChannel Mode - */ - - private void setAdapterForTwoChannelMode() { - final String[] channels = getResources().getStringArray(R.array.channel_choices); - final String[] edges = getResources().getStringArray(R.array.edge_choices); - - final List channel_one_list = new ArrayList<>(Arrays.asList(channels)); - final List channel_two_list = new ArrayList<>(Arrays.asList(channels)); - - final ArrayAdapter channel_one_adapter = new ArrayAdapter<>(getContext(), R.layout.modified_spinner_dropdown_list, channel_one_list); - final ArrayAdapter channel_two_adapter = new ArrayAdapter<>(getContext(), R.layout.modified_spinner_dropdown_list, channel_two_list); - ArrayAdapter edges_adapter = new ArrayAdapter<>(getContext(), R.layout.modified_spinner_dropdown_list, edges); - - channelSelectSpinner1.setAdapter(channel_one_adapter); - channelSelectSpinner2.setAdapter(channel_two_adapter); - - edgeSelectSpinner1.setAdapter(edges_adapter); - edgeSelectSpinner2.setAdapter(edges_adapter); - - channelSelectSpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - String selection = channelSelectSpinner1.getItemAtPosition(position).toString(); - channel_two_list.clear(); - for (int i = 0; i < channels.length; i++) { - if (!channels[i].equals(selection)) { - channel_two_list.add(channels[i]); - } - } - channel_two_adapter.notifyDataSetChanged(); - } - - @Override - public void onNothingSelected(AdapterView parent) { - // No use - } - }); - - channelSelectSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - String selection = channelSelectSpinner2.getItemAtPosition(position).toString(); - channel_one_list.clear(); - for (int i = 0; i < channels.length; i++) { - if (!channels[i].equals(selection)) { - channel_one_list.add(channels[i]); - } - } - channel_one_adapter.notifyDataSetChanged(); - } - - @Override - public void onNothingSelected(AdapterView parent) { - // No use - } - }); - } - - /** - * Sets the text in Carousel Picker - */ - - private void setCarouselPicker() { - // Calculation made for setting the text size in Carousel Picker for different screens - DisplayMetrics dm = new DisplayMetrics(); - getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm); - int width = dm.widthPixels; - int height = dm.heightPixels; - double wi = (double) width / (double) dm.xdpi; - double hi = (double) height / (double) dm.ydpi; - double x = Math.pow(wi, 2); - double y = Math.pow(hi, 2); - double screenInches = Math.sqrt(x + y) + 0.01; - int textsize; - if (screenInches < 5) - textsize = 11; - else - textsize = 9; - - // Items for Carousel Picker - List channelModes = new ArrayList<>(); - channelModes.add(new CarouselPicker.TextItem("1", textsize)); - channelModes.add(new CarouselPicker.TextItem("2", textsize)); - channelModes.add(new CarouselPicker.TextItem("3", textsize)); - channelModes.add(new CarouselPicker.TextItem("4", textsize)); - - CarouselPicker.CarouselViewAdapter channelAdapter = new CarouselPicker.CarouselViewAdapter(getContext(), channelModes, 0); - carouselPicker.setAdapter(channelAdapter); - carouselPicker.setCurrentItem(0); - } - - @Override - public void onResume() { - super.onResume(); - } - - @Override - public void onStop() { - final ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); - if (actionBar != null) { - actionBar.show(); - } - super.onStop(); - } - - /** - * Used to delay a thread by some given time in milliseconds - * - * @param delay Time to delay in milliseconds - */ - - public void delayThread(long delay) { - try { - Thread.sleep(delay); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - private void storeAxisValues(double[] xaxis, double[] yaxis, int mode) { - StringBuilder stringBuilder1 = new StringBuilder(); - StringBuilder stringBuilder2 = new StringBuilder(); - for (int i = 0; i < xaxis.length; i++) { - stringBuilder1.append(DataFormatter.formatDouble(xaxis[i], DataFormatter.LOW_PRECISION_FORMAT)); - stringBuilder2.append(DataFormatter.formatDouble(yaxis[i], DataFormatter.LOW_PRECISION_FORMAT)); - stringBuilder1.append(" "); - stringBuilder2.append(" "); - } - recordXAxis.add(stringBuilder1.toString()); - recordYAxis.add(stringBuilder2.toString()); - recordChannelMode.add(mode); - } - - public void recordSensorDataBlockID(SensorDataBlock block) { - realm.beginTransaction(); - realm.copyToRealm(block); - realm.commitTransaction(); - } - - public void recordSensorData(RealmObject sensorData) { - realm.beginTransaction(); - realm.copyToRealm((LogicAnalyzerData) sensorData); - realm.commitTransaction(); - } - - private class CaptureOne extends AsyncTask { - private String edgeOption = ""; - private boolean holder; - - @Override - protected Void doInBackground(String... params) { - try { - channels[0] = params[0]; - - int channelNumber = scienceLab.calculateDigitalChannel(params[0]); - digitalChannel = scienceLab.getDigitalChannel(channelNumber); - edgeOption = params[1]; - - switch (edgeOption) { - case "EVERY EDGE": - digitalChannel.mode = EVERY_EDGE; - break; - case "EVERY FALLING EDGE": - digitalChannel.mode = EVERY_FALLING_EDGE; - break; - case "EVERY RISING EDGE": - digitalChannel.mode = EVERY_RISING_EDGE; - break; - case "EVERY FOURTH RISING EDGE": - digitalChannel.mode = EVERY_FOURTH_RISING_EDGE; - break; - case "DISABLED": - digitalChannel.mode = DISABLED; - break; - default: - digitalChannel.mode = EVERY_EDGE; - } - - scienceLab.startOneChannelLA(params[0], digitalChannel.mode, params[0], 3); - delayThread(1000); - LinkedHashMap data = scienceLab.getLAInitialStates(); - delayThread(1000); - holder = scienceLab.fetchLAChannel(channelNumber, data); - - } catch (NullPointerException e) { - cancel(true); - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - - if (holder) { - - double[] xaxis = digitalChannel.getXAxis(); - double[] yaxis = digitalChannel.getYAxis(); - - StringBuilder stringBuilder1 = new StringBuilder(); - StringBuilder stringBuilder2 = new StringBuilder(); - for (int i = 0; i < xaxis.length; i++) { - stringBuilder1.append(DataFormatter.formatDouble(xaxis[i], DataFormatter.LOW_PRECISION_FORMAT)); - stringBuilder2.append(DataFormatter.formatDouble(yaxis[i], DataFormatter.LOW_PRECISION_FORMAT)); - stringBuilder1.append(" "); - stringBuilder2.append(" "); - } - Log.v("x Axis", stringBuilder1.toString()); - Log.v("y Axis", stringBuilder2.toString()); - - recordXAxis.clear(); - recordXAxis.add(stringBuilder1.toString()); - recordYAxis.add(stringBuilder2.toString()); - recordChannelMode.add(digitalChannel.mode); - // Plot the fetched data - switch (edgeOption) { - case "EVERY EDGE": - singleChannelEveryEdge(xaxis, yaxis); - break; - case "EVERY FOURTH RISING EDGE": - singleChannelFourthRisingEdge(xaxis); - break; - case "EVERY RISING EDGE": - singleChannelRisingEdges(xaxis, yaxis); - break; - case "EVERY FALLING EDGE": - singleChannelFallingEdges(xaxis, yaxis); - break; - default: - singleChannelOtherEdges(xaxis, yaxis); - break; - } - progressBar.setVisibility(View.GONE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(false); - - logicLinesChart.setData(new LineData(dataSets)); - logicLinesChart.notifyDataSetChanged(); - logicLinesChart.invalidate(); - - YAxis left = logicLinesChart.getAxisLeft(); - left.setValueFormatter(new LogicAnalyzerAxisFormatter(channelNames)); - left.setTextColor(Color.WHITE); - left.setGranularity(1f); - left.setTextSize(12f); - logicLinesChart.getAxisRight().setDrawLabels(false); - logicLinesChart.getDescription().setEnabled(false); - logicLinesChart.setScaleYEnabled(false); - - synchronized (lock) { - lock.notify(); - } - } else { - progressBar.setVisibility(View.GONE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(false); - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_generated), null, null, Snackbar.LENGTH_SHORT); - analyze_button.setClickable(true); - } - - analyze_button.setClickable(true); - } - } - - private class CaptureTwo extends AsyncTask, ArrayList, Void> { - private String[] edgeOption = new String[channelMode]; - private boolean holder1, holder2; - - @SafeVarargs - @Override - protected final Void doInBackground(ArrayList... arrayLists) { - try { - channels[0] = arrayLists[0].get(0); - channels[1] = arrayLists[0].get(1); - - int channelNumber1 = scienceLab.calculateDigitalChannel(arrayLists[0].get(0)); - int channelNumber2 = scienceLab.calculateDigitalChannel(arrayLists[0].get(1)); - - digitalChannelArray.add(scienceLab.getDigitalChannel(channelNumber1)); - digitalChannelArray.add(scienceLab.getDigitalChannel(channelNumber2)); - edgeOption[0] = arrayLists[1].get(0); - edgeOption[1] = arrayLists[1].get(1); - - ArrayList modes = new ArrayList<>(); - for (int i = 0; i < channelMode; i++) { - switch (edgeOption[i]) { - case "EVERY EDGE": - digitalChannelArray.get(i).mode = EVERY_EDGE; - modes.add(EVERY_EDGE); - break; - case "EVERY FALLING EDGE": - digitalChannelArray.get(i).mode = EVERY_FALLING_EDGE; - modes.add(EVERY_FALLING_EDGE); - break; - case "EVERY RISING EDGE": - digitalChannelArray.get(i).mode = EVERY_RISING_EDGE; - modes.add(EVERY_RISING_EDGE); - break; - case "EVERY FOURTH RISING EDGE": - digitalChannelArray.get(i).mode = EVERY_FOURTH_RISING_EDGE; - modes.add(EVERY_FOURTH_RISING_EDGE); - break; - case "DISABLED": - digitalChannelArray.get(i).mode = DISABLED; - modes.add(DISABLED); - break; - default: - digitalChannelArray.get(i).mode = EVERY_EDGE; - modes.add(EVERY_EDGE); - } - } - - scienceLab.startTwoChannelLA(arrayLists[0], modes, 67, null, null, null); - delayThread(1000); - LinkedHashMap data = scienceLab.getLAInitialStates(); - delayThread(1000); - holder1 = scienceLab.fetchLAChannel(channelNumber1, data); - delayThread(1000); - holder2 = scienceLab.fetchLAChannel(channelNumber2, data); - - } catch (NullPointerException e) { - cancel(true); - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - - if (holder1 && holder2) { - - ArrayList xaxis = new ArrayList<>(); - xaxis.add(digitalChannelArray.get(0).getXAxis()); - xaxis.add(digitalChannelArray.get(1).getXAxis()); - - ArrayList yaxis = new ArrayList<>(); - yaxis.add(digitalChannelArray.get(0).getYAxis()); - yaxis.add(digitalChannelArray.get(1).getYAxis()); - - recordXAxis.clear(); - recordYAxis.clear(); - recordChannelMode.clear(); - // Plot the fetched data - for (int i = 0; i < channelMode; i++) { - storeAxisValues(xaxis.get(i), yaxis.get(i), digitalChannelArray.get(i).mode); - switch (edgeOption[i]) { - case "EVERY EDGE": - singleChannelEveryEdge(xaxis.get(i), yaxis.get(i)); - break; - case "EVERY FOURTH RISING EDGE": - singleChannelFourthRisingEdge(xaxis.get(i)); - break; - case "EVERY RISING EDGE": - singleChannelRisingEdges(xaxis.get(i), yaxis.get(i)); - break; - case "EVERY FALLING EDGE": - singleChannelFallingEdges(xaxis.get(i), yaxis.get(i)); - break; - default: - singleChannelOtherEdges(xaxis.get(i), yaxis.get(i)); - break; - } - currentChannel++; - } - - progressBar.setVisibility(View.GONE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(false); - - logicLinesChart.setData(new LineData(dataSets)); - logicLinesChart.invalidate(); - - YAxis left = logicLinesChart.getAxisLeft(); - left.setValueFormatter(new LogicAnalyzerAxisFormatter(channelNames)); - left.setTextColor(Color.WHITE); - left.setGranularity(1f); - left.setTextSize(12f); - logicLinesChart.getAxisRight().setDrawLabels(false); - logicLinesChart.getDescription().setEnabled(false); - logicLinesChart.setScaleYEnabled(false); - - synchronized (lock) { - lock.notify(); - } - } else { - progressBar.setVisibility(View.GONE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(false); - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_generated), null, null, Snackbar.LENGTH_SHORT); - } - - analyze_button.setClickable(true); - } - } - - private class CaptureThree extends AsyncTask, ArrayList, Void> { - private String[] edgeOption = new String[channelMode]; - private boolean holder1, holder2, holder3; - - @SafeVarargs - @Override - protected final Void doInBackground(ArrayList... arrayLists) { - try { - channels[0] = arrayLists[0].get(0); - channels[1] = arrayLists[0].get(1); - channels[2] = arrayLists[0].get(2); - - int channelNumber1 = scienceLab.calculateDigitalChannel(arrayLists[0].get(0)); - int channelNumber2 = scienceLab.calculateDigitalChannel(arrayLists[0].get(1)); - int channelNumber3 = scienceLab.calculateDigitalChannel(arrayLists[0].get(2)); - - digitalChannelArray.add(scienceLab.getDigitalChannel(channelNumber1)); - digitalChannelArray.add(scienceLab.getDigitalChannel(channelNumber2)); - digitalChannelArray.add(scienceLab.getDigitalChannel(channelNumber3)); - edgeOption[0] = arrayLists[1].get(0); - edgeOption[1] = arrayLists[1].get(1); - edgeOption[2] = arrayLists[1].get(2); - - ArrayList modes = new ArrayList<>(); - for (int i = 0; i < channelMode; i++) { - switch (edgeOption[i]) { - case "EVERY EDGE": - digitalChannelArray.get(i).mode = EVERY_EDGE; - modes.add(EVERY_EDGE); - break; - case "EVERY FALLING EDGE": - digitalChannelArray.get(i).mode = EVERY_FALLING_EDGE; - modes.add(EVERY_FALLING_EDGE); - break; - case "EVERY RISING EDGE": - digitalChannelArray.get(i).mode = EVERY_RISING_EDGE; - modes.add(EVERY_RISING_EDGE); - break; - case "EVERY FOURTH RISING EDGE": - digitalChannelArray.get(i).mode = EVERY_FOURTH_RISING_EDGE; - modes.add(EVERY_FOURTH_RISING_EDGE); - break; - case "DISABLED": - digitalChannelArray.get(i).mode = DISABLED; - modes.add(DISABLED); - break; - default: - digitalChannelArray.get(i).mode = EVERY_EDGE; - modes.add(EVERY_EDGE); - } - } - - scienceLab.startThreeChannelLA(modes, null, null); - delayThread(1000); - LinkedHashMap data = scienceLab.getLAInitialStates(); - delayThread(1000); - holder1 = scienceLab.fetchLAChannel(channelNumber1, data); - delayThread(1000); - holder2 = scienceLab.fetchLAChannel(channelNumber2, data); - delayThread(1000); - holder3 = scienceLab.fetchLAChannel(channelNumber3, data); - - } catch (NullPointerException e) { - cancel(true); - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - - if (holder1 && holder2 && holder3) { - - ArrayList xaxis = new ArrayList<>(); - xaxis.add(digitalChannelArray.get(0).getXAxis()); - xaxis.add(digitalChannelArray.get(1).getXAxis()); - xaxis.add(digitalChannelArray.get(2).getXAxis()); - - ArrayList yaxis = new ArrayList<>(); - yaxis.add(digitalChannelArray.get(0).getYAxis()); - yaxis.add(digitalChannelArray.get(1).getYAxis()); - yaxis.add(digitalChannelArray.get(2).getYAxis()); - - recordXAxis.clear(); - recordYAxis.clear(); - recordChannelMode.clear(); - // Plot the fetched data - for (int i = 0; i < channelMode; i++) { - storeAxisValues(xaxis.get(i), yaxis.get(i), digitalChannelArray.get(i).mode); - switch (edgeOption[i]) { - case "EVERY EDGE": - singleChannelEveryEdge(xaxis.get(i), yaxis.get(i)); - break; - case "EVERY FOURTH RISING EDGE": - singleChannelFourthRisingEdge(xaxis.get(i)); - break; - case "EVERY RISING EDGE": - singleChannelRisingEdges(xaxis.get(i), yaxis.get(i)); - break; - case "EVERY FALLING EDGE": - singleChannelFallingEdges(xaxis.get(i), yaxis.get(i)); - break; - default: - singleChannelOtherEdges(xaxis.get(i), yaxis.get(i)); - break; - } - currentChannel++; - } - - progressBar.setVisibility(View.GONE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(false); - - logicLinesChart.setData(new LineData(dataSets)); - logicLinesChart.invalidate(); - - YAxis left = logicLinesChart.getAxisLeft(); - left.setValueFormatter(new LogicAnalyzerAxisFormatter(channelNames)); - left.setTextColor(Color.WHITE); - left.setGranularity(1f); - left.setTextSize(12f); - logicLinesChart.getAxisRight().setDrawLabels(false); - logicLinesChart.getDescription().setEnabled(false); - logicLinesChart.setScaleYEnabled(false); - - synchronized (lock) { - lock.notify(); - } - } else { - progressBar.setVisibility(View.GONE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(false); - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_generated), null, null, Snackbar.LENGTH_SHORT); - } - - analyze_button.setClickable(true); - } - } - - private class CaptureFour extends AsyncTask, ArrayList, Void> { - private String[] edgeOption = new String[channelMode]; - private boolean holder1, holder2, holder3, holder4; - - @Override - protected Void doInBackground(ArrayList... arrayLists) { - try { - channels[0] = arrayLists[0].get(0); - channels[1] = arrayLists[0].get(1); - channels[2] = arrayLists[0].get(2); - channels[3] = arrayLists[0].get(3); - - int channelNumber1 = scienceLab.calculateDigitalChannel(arrayLists[0].get(0)); - int channelNumber2 = scienceLab.calculateDigitalChannel(arrayLists[0].get(1)); - int channelNumber3 = scienceLab.calculateDigitalChannel(arrayLists[0].get(2)); - int channelNumber4 = scienceLab.calculateDigitalChannel(arrayLists[0].get(3)); - - digitalChannelArray.add(scienceLab.getDigitalChannel(channelNumber1)); - digitalChannelArray.add(scienceLab.getDigitalChannel(channelNumber2)); - digitalChannelArray.add(scienceLab.getDigitalChannel(channelNumber3)); - digitalChannelArray.add(scienceLab.getDigitalChannel(channelNumber4)); - edgeOption[0] = arrayLists[1].get(0); - edgeOption[1] = arrayLists[1].get(1); - edgeOption[2] = arrayLists[1].get(2); - edgeOption[3] = arrayLists[1].get(3); - - ArrayList modes = new ArrayList<>(); - for (int i = 0; i < channelMode; i++) { - switch (edgeOption[i]) { - case "EVERY EDGE": - digitalChannelArray.get(i).mode = EVERY_EDGE; - modes.add(EVERY_EDGE); - break; - case "EVERY FALLING EDGE": - digitalChannelArray.get(i).mode = EVERY_FALLING_EDGE; - modes.add(EVERY_FALLING_EDGE); - break; - case "EVERY RISING EDGE": - digitalChannelArray.get(i).mode = EVERY_RISING_EDGE; - modes.add(EVERY_RISING_EDGE); - break; - case "EVERY FOURTH RISING EDGE": - digitalChannelArray.get(i).mode = EVERY_FOURTH_RISING_EDGE; - modes.add(EVERY_FOURTH_RISING_EDGE); - break; - case "DISABLED": - digitalChannelArray.get(i).mode = DISABLED; - modes.add(DISABLED); - break; - default: - digitalChannelArray.get(i).mode = EVERY_EDGE; - modes.add(EVERY_EDGE); - } - } - ArrayList triggerChannel = new ArrayList<>(); - triggerChannel.add(true); - triggerChannel.add(true); - triggerChannel.add(true); - - scienceLab.startFourChannelLA(null, null, modes, null, triggerChannel); - delayThread(1000); - LinkedHashMap data = scienceLab.getLAInitialStates(); - delayThread(1000); - holder1 = scienceLab.fetchLAChannel(channelNumber1, data); - delayThread(1000); - holder2 = scienceLab.fetchLAChannel(channelNumber2, data); - delayThread(1000); - holder3 = scienceLab.fetchLAChannel(channelNumber3, data); - delayThread(1000); - holder4 = scienceLab.fetchLAChannel(channelNumber4, data); - - } catch (NullPointerException e) { - cancel(true); - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - - if (holder1 && holder2 && holder3 && holder4) { - - ArrayList xaxis = new ArrayList<>(); - xaxis.add(digitalChannelArray.get(0).getXAxis()); - xaxis.add(digitalChannelArray.get(1).getXAxis()); - xaxis.add(digitalChannelArray.get(2).getXAxis()); - xaxis.add(digitalChannelArray.get(3).getXAxis()); - - ArrayList yaxis = new ArrayList<>(); - yaxis.add(digitalChannelArray.get(0).getYAxis()); - yaxis.add(digitalChannelArray.get(1).getYAxis()); - yaxis.add(digitalChannelArray.get(2).getYAxis()); - yaxis.add(digitalChannelArray.get(3).getYAxis()); - - recordXAxis.clear(); - recordYAxis.clear(); - recordChannelMode.clear(); - // Plot the fetched data - for (int i = 0; i < channelMode; i++) { - storeAxisValues(xaxis.get(i), yaxis.get(i), digitalChannelArray.get(i).mode); - switch (edgeOption[i]) { - case "EVERY EDGE": - singleChannelEveryEdge(xaxis.get(i), yaxis.get(i)); - break; - case "EVERY FOURTH RISING EDGE": - singleChannelFourthRisingEdge(xaxis.get(i)); - break; - case "EVERY RISING EDGE": - singleChannelRisingEdges(xaxis.get(i), yaxis.get(i)); - break; - case "EVERY FALLING EDGE": - singleChannelFallingEdges(xaxis.get(i), yaxis.get(i)); - break; - default: - singleChannelOtherEdges(xaxis.get(i), yaxis.get(i)); - break; - } - currentChannel++; - } - - progressBar.setVisibility(View.GONE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(false); - - logicLinesChart.setData(new LineData(dataSets)); - logicLinesChart.invalidate(); - - YAxis left = logicLinesChart.getAxisLeft(); - left.setValueFormatter(new LogicAnalyzerAxisFormatter(channelNames)); - left.setTextColor(Color.WHITE); - left.setGranularity(1f); - left.setTextSize(12f); - logicLinesChart.getAxisRight().setDrawLabels(false); - logicLinesChart.getDescription().setEnabled(false); - logicLinesChart.setScaleYEnabled(false); - - synchronized (lock) { - lock.notify(); - } - } else { - progressBar.setVisibility(View.GONE); - ((LogicalAnalyzerActivity) getActivity()).setStatus(false); - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_generated), null, null, Snackbar.LENGTH_SHORT); - } - - analyze_button.setClickable(true); - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/LuxMeterDataFragment.java b/app/src/main/java/io/pslab/fragment/LuxMeterDataFragment.java deleted file mode 100644 index adcccfe11..000000000 --- a/app/src/main/java/io/pslab/fragment/LuxMeterDataFragment.java +++ /dev/null @@ -1,632 +0,0 @@ -package io.pslab.fragment; - -import android.graphics.Bitmap; -import android.graphics.Color; -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; -import android.location.Location; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import androidx.annotation.NonNull; - -import com.google.android.material.snackbar.Snackbar; -import androidx.fragment.app.Fragment; - -import androidx.preference.PreferenceManager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.github.anastr.speedviewlib.PointerSpeedometer; -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.Locale; -import java.util.Timer; -import java.util.TimerTask; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.activity.LuxMeterActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.BH1750; -import io.pslab.communication.sensors.TSL2561; -import io.pslab.interfaces.OperationCallback; -import io.pslab.models.LuxData; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.ScienceLabCommon; - -import static android.content.Context.SENSOR_SERVICE; -import static io.pslab.others.CSVLogger.CSV_DIRECTORY; - -/** - * Created by Padmal on 11/2/18. - */ - -public class LuxMeterDataFragment extends Fragment implements OperationCallback { - - private static final CSVDataLine CSV_HEADER = - new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("Readings") - .add("Latitude") - .add("Longitude"); - - private static int sensorType = 0; - private static int highLimit = 2000; - private static int updatePeriod = 100; - private static int gain = 1; - private long timeElapsed; - private int count = 0, turns = 0; - private float sum = 0; - private boolean returningFromPause = false; - - private float luxValue = -1; - - private enum LUX_SENSOR {INBUILT_SENSOR, BH1750_SENSOR, TSL2561_SENSOR} - - @BindView(R.id.lux_max) - TextView statMax; - @BindView(R.id.lux_min) - TextView statMin; - @BindView(R.id.lux_avg) - TextView statMean; - @BindView(R.id.label_lux_sensor) - TextView sensorLabel; - @BindView(R.id.chart_lux_meter) - LineChart mChart; - @BindView(R.id.light_meter) - PointerSpeedometer lightMeter; - - private Timer graphTimer; - private SensorManager sensorManager; - private Sensor sensor; - private long startTime, block; - private ArrayList entries; - private ArrayList recordedLuxArray; - private LuxData sensorData; - private float currentMin = 10000; - private float currentMax = 0; - private YAxis y; - private Unbinder unbinder; - private long previousTimeElapsed = (System.currentTimeMillis() - startTime) / updatePeriod; - private LuxMeterActivity luxSensor; - private View rootView; - - public static LuxMeterDataFragment newInstance() { - return new LuxMeterDataFragment(); - } - - public static void setParameters(int highLimit, int updatePeriod, String type, String gain) { - LuxMeterDataFragment.highLimit = highLimit; - LuxMeterDataFragment.updatePeriod = updatePeriod; - LuxMeterDataFragment.sensorType = Integer.valueOf(type); - LuxMeterDataFragment.gain = Integer.valueOf(gain); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - startTime = System.currentTimeMillis(); - entries = new ArrayList<>(); - luxSensor = (LuxMeterActivity) getActivity(); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_lux_meter_data, container, false); - unbinder = ButterKnife.bind(this, rootView); - setupInstruments(); - return rootView; - } - - @Override - public void onResume() { - super.onResume(); - if (luxSensor.playingData) { - sensorLabel.setText(getResources().getString(R.string.lux_meter)); - recordedLuxArray = new ArrayList<>(); - resetInstrumentData(); - playRecordedData(); - } else if (luxSensor.viewingData) { - sensorLabel.setText(getResources().getString(R.string.lux_meter)); - recordedLuxArray = new ArrayList<>(); - resetInstrumentData(); - plotAllRecordedData(); - } else if (!luxSensor.isRecording) { - updateGraphs(); - sum = 0; - count = 0; - currentMin = 10000; - currentMax = 0; - entries.clear(); - mChart.clear(); - mChart.invalidate(); - initiateLuxSensor(sensorType); - } else if (returningFromPause) { - updateGraphs(); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - if (graphTimer != null) { - graphTimer.cancel(); - } - if (sensorManager != null) { - sensorManager.unregisterListener(lightSensorEventListener); - } - unbinder.unbind(); - } - - private void plotAllRecordedData() { - recordedLuxArray.addAll(luxSensor.recordedLuxData); - if (recordedLuxArray.size() != 0) { - for (LuxData d : recordedLuxArray) { - if (currentMax < d.getLux()) { - currentMax = d.getLux(); - } - if (currentMin > d.getLux()) { - currentMin = d.getLux(); - } - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getLux()); - entries.add(entry); - lightMeter.setWithTremble(false); - lightMeter.setSpeedAt(d.getLux()); - sum += entry.getY(); - } - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setLabelCount(10); - statMax.setText(String.format(Locale.getDefault(), PSLabSensor.LUXMETER_DATA_FORMAT, currentMax)); - statMin.setText(String.format(Locale.getDefault(), PSLabSensor.LUXMETER_DATA_FORMAT, currentMin)); - statMean.setText(String.format(Locale.getDefault(), PSLabSensor.LUXMETER_DATA_FORMAT, (sum / recordedLuxArray.size()))); - - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.lux)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } - } - - private void playRecordedData() { - recordedLuxArray.addAll(luxSensor.recordedLuxData); - try { - if (recordedLuxArray.size() > 1) { - LuxData i = recordedLuxArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - private void processRecordedData(long timeGap) { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } else { - graphTimer = new Timer(); - } - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - if (luxSensor.playingData) { - try { - LuxData d = recordedLuxArray.get(turns); - turns++; - if (currentMax < d.getLux()) { - currentMax = d.getLux(); - statMax.setText(String.format(Locale.getDefault(), PSLabSensor.LUXMETER_DATA_FORMAT, d.getLux())); - } - if (currentMin > d.getLux()) { - currentMin = d.getLux(); - statMin.setText(String.format(Locale.getDefault(), PSLabSensor.LUXMETER_DATA_FORMAT, d.getLux())); - } - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setLabelCount(10); - lightMeter.setWithTremble(false); - lightMeter.setSpeedAt(d.getLux()); - - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getLux()); - entries.add(entry); - count++; - sum += entry.getY(); - statMean.setText(DataFormatter.formatDouble((sum / count), PSLabSensor.LUXMETER_DATA_FORMAT)); - - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.lux)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } catch (IndexOutOfBoundsException e) { - graphTimer.cancel(); - graphTimer = null; - turns = 0; - luxSensor.playingData = false; - luxSensor.startedPlay = false; - luxSensor.invalidateOptionsMenu(); - } - } - } - }); - } - }, 0, timeGap); - } - - @Override - public void stopData() { - if (graphTimer != null) { - graphTimer.cancel(); - graphTimer = null; - } - recordedLuxArray.clear(); - entries.clear(); - plotAllRecordedData(); - luxSensor.startedPlay = false; - luxSensor.playingData = false; - turns = 0; - luxSensor.invalidateOptionsMenu(); - } - - @Override - public void playData() { - resetInstrumentData(); - luxSensor.startedPlay = true; - try { - if (recordedLuxArray.size() > 1) { - LuxData i = recordedLuxArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - @Override - public void saveGraph() { - luxSensor.csvLogger.prepareLogFile(); - luxSensor.csvLogger.writeMetaData(getResources().getString(R.string.lux_meter)); - luxSensor.csvLogger.writeCSVFile(CSV_HEADER); - for (LuxData luxData : luxSensor.recordedLuxData) { - luxSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(luxData.getTime()) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(luxData.getTime()))) - .add(luxData.getLux()) - .add(luxData.getLat()) - .add(luxData.getLon()) - ); - } - View view = rootView.findViewById(R.id.luxmeter_linearlayout); - view.setDrawingCacheEnabled(true); - Bitmap b = view.getDrawingCache(); - try { - b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + luxSensor.getSensorName() + - File.separator + CSVLogger.FILE_NAME_FORMAT.format(new Date()) + "_graph.jpg")); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - - private void setupInstruments() { - lightMeter.setMaxSpeed(PreferenceManager.getDefaultSharedPreferences(getActivity()).getFloat(luxSensor.LUXMETER_LIMIT, 10000)); - - XAxis x = mChart.getXAxis(); - this.y = mChart.getAxisLeft(); - YAxis y2 = mChart.getAxisRight(); - - mChart.setTouchEnabled(true); - mChart.setHighlightPerDragEnabled(true); - mChart.setDragEnabled(true); - mChart.setScaleEnabled(true); - mChart.setDrawGridBackground(false); - mChart.setPinchZoom(true); - mChart.setScaleYEnabled(true); - mChart.setBackgroundColor(Color.BLACK); - mChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - mChart.setData(data); - - Legend l = mChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setDrawGridLines(true); - y.setLabelCount(10); - - y2.setDrawGridLines(false); - } - - @Override - public void onPause() { - super.onPause(); - if (graphTimer != null) { - returningFromPause = true; - graphTimer.cancel(); - graphTimer = null; - if (luxSensor.playingData) { - luxSensor.finish(); - } - } - } - - private void updateGraphs() { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } - graphTimer = new Timer(); - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - try { - visualizeData(); - } catch (NullPointerException e) { - /* Pass for another refresh round */ - } - } - }); - } - }, 0, updatePeriod); - } - - private void writeLogToFile(long timestamp, float sensorReading) { - if (getActivity() != null && luxSensor.isRecording) { - if (luxSensor.writeHeaderToFile) { - luxSensor.csvLogger.prepareLogFile(); - luxSensor.csvLogger.writeMetaData(getResources().getString(R.string.lux_meter)); - luxSensor.csvLogger.writeCSVFile(CSV_HEADER); - block = timestamp; - luxSensor.recordSensorDataBlockID(new SensorDataBlock(timestamp, luxSensor.getSensorName())); - luxSensor.writeHeaderToFile = !luxSensor.writeHeaderToFile; - } - if (luxSensor.addLocation && luxSensor.gpsLogger.isGPSEnabled()) { - Location location = luxSensor.gpsLogger.getDeviceLocation(); - luxSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(sensorReading) - .add(location.getLatitude()) - .add(location.getLongitude()) - ); - sensorData = new LuxData(timestamp, block, luxValue, location.getLatitude(), location.getLongitude()); - } else { - luxSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(sensorReading) - .add(0.0) - .add(0.0) - ); - sensorData = new LuxData(timestamp, block, luxValue, 0.0, 0.0); - } - luxSensor.recordSensorData(sensorData); - } else { - luxSensor.writeHeaderToFile = true; - } - } - - private void visualizeData() { - if (currentMax < luxValue) { - currentMax = luxValue; - statMax.setText(String.format(Locale.getDefault(), PSLabSensor.LUXMETER_DATA_FORMAT, luxValue)); - } - if (currentMin > luxValue) { - currentMin = luxValue; - statMin.setText(String.format(Locale.getDefault(), PSLabSensor.LUXMETER_DATA_FORMAT, luxValue)); - } - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setLabelCount(10); - if (luxValue >= 0) { - lightMeter.setWithTremble(false); - lightMeter.setSpeedAt(luxValue); - if (luxValue > highLimit) - lightMeter.setPointerColor(Color.RED); - else - lightMeter.setPointerColor(Color.WHITE); - - timeElapsed = ((System.currentTimeMillis() - startTime) / updatePeriod); - if (timeElapsed != previousTimeElapsed) { - previousTimeElapsed = timeElapsed; - Entry entry = new Entry((float) timeElapsed, luxValue); - Long currentTime = System.currentTimeMillis(); - writeLogToFile(currentTime, luxValue); - entries.add(entry); - - count++; - sum += entry.getY(); - statMean.setText(String.format(Locale.getDefault(), PSLabSensor.LUXMETER_DATA_FORMAT, (sum / count))); - - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.lux)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(80); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } - } - } - - private SensorEventListener lightSensorEventListener = new SensorEventListener() { - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) {/**/} - - @Override - public void onSensorChanged(SensorEvent event) { - if (event.sensor.getType() == Sensor.TYPE_LIGHT) { - luxValue = event.values[0]; - } - } - }; - - private void resetInstrumentData() { - luxValue = 0; - count = 0; - currentMin = 10000; - currentMax = 0; - sum = 0; - sensor = null; - if (sensorManager != null) { - sensorManager.unregisterListener(lightSensorEventListener); - } - startTime = System.currentTimeMillis(); - statMax.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - statMin.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - statMean.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - lightMeter.setSpeedAt(0); - lightMeter.setWithTremble(false); - entries.clear(); - } - - private void initiateLuxSensor(int type) { - LUX_SENSOR s = LUX_SENSOR.values()[type]; - resetInstrumentData(); - ScienceLab scienceLab; - switch (s) { - case INBUILT_SENSOR: - sensorLabel.setText(getResources().getStringArray(R.array.lux_sensors)[0]); - sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE); - sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); - if (sensor == null) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_lux_sensor), null, null, Snackbar.LENGTH_LONG); - } else { - float max = sensor.getMaximumRange() * 10000; - PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putFloat(luxSensor.LUXMETER_LIMIT, max).apply(); - lightMeter.setMaxSpeed(max); - sensorManager.registerListener(lightSensorEventListener, - sensor, SensorManager.SENSOR_DELAY_FASTEST); - } - break; - case BH1750_SENSOR: - sensorLabel.setText(getResources().getStringArray(R.array.lux_sensors)[1]); - scienceLab = ScienceLabCommon.scienceLab; - if (scienceLab.isConnected()) { - ArrayList data; - try { - I2C i2c = scienceLab.i2c; - data = i2c.scan(null); - if (data.contains(0x23)) { - BH1750 sensorBH1750 = new BH1750(i2c); - sensorBH1750.setRange(String.valueOf(gain)); - sensorType = 0; - } else { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.sensor_not_connected_tls), null, null, Snackbar.LENGTH_SHORT); - sensorType = 0; - } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - } else { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.device_not_found), null, null, Snackbar.LENGTH_SHORT); - sensorType = 0; - } - - break; - case TSL2561_SENSOR: - sensorLabel.setText(getResources().getStringArray(R.array.lux_sensors)[2]); - scienceLab = ScienceLabCommon.scienceLab; - if (scienceLab.isConnected()) { - try { - I2C i2c = scienceLab.i2c; - ArrayList data; - data = i2c.scan(null); - if (data.contains(0x39)) { - TSL2561 sensorTSL2561 = new TSL2561(i2c, scienceLab); - sensorTSL2561.setGain(String.valueOf(gain)); - sensorType = 2; - } else { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.sensor_not_connected_tls), null, null, Snackbar.LENGTH_SHORT); - sensorType = 0; - } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - } else { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.device_not_found), null, null, Snackbar.LENGTH_SHORT); - sensorType = 0; - } - break; - default: - break; - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/LuxMeterSettingFragment.java b/app/src/main/java/io/pslab/fragment/LuxMeterSettingFragment.java deleted file mode 100644 index 57e23eea3..000000000 --- a/app/src/main/java/io/pslab/fragment/LuxMeterSettingFragment.java +++ /dev/null @@ -1,136 +0,0 @@ -package io.pslab.fragment; - -import android.annotation.SuppressLint; -import android.content.SharedPreferences; -import android.os.Bundle; - -import androidx.preference.CheckBoxPreference; -import androidx.preference.EditTextPreference; -import androidx.preference.ListPreference; -import androidx.preference.PreferenceFragmentCompat; -import androidx.preference.PreferenceManager; - -import com.google.android.material.snackbar.Snackbar; - -import io.pslab.R; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.PSLabPermission; - -public class LuxMeterSettingFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { - - public static final String KEY_INCLUDE_LOCATION = "include_location_sensor_data"; - public static final String KEY_UPDATE_PERIOD = "setting_lux_update_period"; - public static final String KEY_HIGH_LIMIT = "setting_lux_high_limit"; - public static final String KEY_LUX_SENSOR_TYPE = "setting_lux_sensor_type"; - public static final String KEY_LUX_SENSOR_GAIN = "setting_lux_sensor_gain"; - - private PSLabPermission psLabPermission; - - private EditTextPreference updatePeriodPref; - private EditTextPreference higLimitPref; - private EditTextPreference sensorGainPref; - private CheckBoxPreference locationPreference; - private ListPreference sensorTypePreference; - private SharedPreferences sharedPref; - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - setPreferencesFromResource(R.xml.lux_meter_settings, rootKey); - updatePeriodPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_UPDATE_PERIOD); - higLimitPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_HIGH_LIMIT); - sensorGainPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_LUX_SENSOR_GAIN); - locationPreference = (CheckBoxPreference) getPreferenceScreen().findPreference(KEY_INCLUDE_LOCATION); - sensorTypePreference = (ListPreference) getPreferenceScreen().findPreference(KEY_LUX_SENSOR_TYPE); - sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); - - psLabPermission = PSLabPermission.getInstance(); - if (!psLabPermission.checkPermissions(getActivity(), PSLabPermission.MAP_PERMISSION)) { - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putBoolean(LuxMeterSettingFragment.KEY_INCLUDE_LOCATION, true); - editor.apply(); - } - } - - @Override - public void onResume() { - super.onResume(); - locationPreference.setChecked(sharedPref.getBoolean(KEY_INCLUDE_LOCATION, true)); - updatePeriodPref.setSummary(updatePeriodPref.getText() + " ms"); - higLimitPref.setSummary(higLimitPref.getText() + " Lx"); - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - sensorGainPref.setSummary(sensorGainPref.getText()); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); - } - - @SuppressLint("ApplySharedPref") - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { - switch (s) { - case KEY_INCLUDE_LOCATION: - if (locationPreference.isChecked()) { - psLabPermission.checkPermissions( - getActivity(), PSLabPermission.MAP_PERMISSION); - } - break; - case KEY_UPDATE_PERIOD: - try { - Integer updatePeriod = Integer.parseInt(updatePeriodPref.getText()); - if (updatePeriod > 1000 || updatePeriod < 100) { - throw new NumberFormatException(); - } else { - updatePeriodPref.setSummary(updatePeriod + " ms"); - } - } catch (NumberFormatException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.update_period_msg),null,null, Snackbar.LENGTH_SHORT); - updatePeriodPref.setSummary("1000 ms"); - updatePeriodPref.setText("1000"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(s, "1000"); - editor.commit(); - } - break; - case KEY_LUX_SENSOR_GAIN: - try { - Integer gain = Integer.parseInt(sensorGainPref.getText()); - sensorGainPref.setSummary(String.valueOf(gain)); - } catch (NumberFormatException e) { - sensorGainPref.setSummary("1"); - sensorGainPref.setText("1"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(KEY_LUX_SENSOR_GAIN, "1"); - editor.commit(); - } - break; - case KEY_HIGH_LIMIT: - try { - Integer highLimit = Integer.parseInt(higLimitPref.getText()); - if (highLimit > 10000 || highLimit < 10) { - throw new NumberFormatException(); - } else { - higLimitPref.setSummary(String.valueOf(highLimit) + " Lx"); - } - } catch (NumberFormatException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.high_limit_msg),null,null, Snackbar.LENGTH_SHORT); - higLimitPref.setSummary("2000 Lx"); - higLimitPref.setText("2000"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(KEY_HIGH_LIMIT, "2000"); - editor.commit(); - } - break; - case KEY_LUX_SENSOR_TYPE: - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - break; - default: - break; - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/MultimeterSettingsFragment.java b/app/src/main/java/io/pslab/fragment/MultimeterSettingsFragment.java deleted file mode 100644 index d1c656e8b..000000000 --- a/app/src/main/java/io/pslab/fragment/MultimeterSettingsFragment.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.pslab.fragment; - -import android.annotation.SuppressLint; -import android.content.SharedPreferences; -import android.os.Bundle; -import com.google.android.material.snackbar.Snackbar; -import androidx.preference.CheckBoxPreference; -import androidx.preference.EditTextPreference; -import androidx.preference.PreferenceFragmentCompat; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.PSLabPermission; - -public class MultimeterSettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { - - public static final String KEY_INCLUDE_LOCATION = "include_location_sensor_data"; - public static final String KEY_UPDATE_PERIOD = "setting_multimeter_update_period"; - - private PSLabPermission psLabPermission; - - private EditTextPreference updatePeriodPref; - private CheckBoxPreference locationPreference; - private SharedPreferences sharedPref; - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - setPreferencesFromResource(R.xml.multimeter_settings, rootKey); - updatePeriodPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_UPDATE_PERIOD); - locationPreference = (CheckBoxPreference) getPreferenceScreen().findPreference(KEY_INCLUDE_LOCATION); - sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); - - psLabPermission = PSLabPermission.getInstance(); - if (!psLabPermission.checkPermissions(getActivity(), PSLabPermission.MAP_PERMISSION)) { - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putBoolean(MultimeterSettingsFragment.KEY_INCLUDE_LOCATION, true); - editor.apply(); - } - } - - @Override - public void onResume() { - super.onResume(); - locationPreference.setChecked(sharedPref.getBoolean(KEY_INCLUDE_LOCATION, true)); - updatePeriodPref.setSummary(updatePeriodPref.getText() + " ms"); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); - } - - @SuppressLint("ApplySharedPref") - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { - switch (s) { - case KEY_INCLUDE_LOCATION: - if (locationPreference.isChecked()) { - psLabPermission.checkPermissions( - getActivity(), PSLabPermission.MAP_PERMISSION); - } - break; - case KEY_UPDATE_PERIOD: - try { - Integer updatePeriod = Integer.parseInt(updatePeriodPref.getText()); - if (updatePeriod > 2000 || updatePeriod < 100) { - throw new NumberFormatException(); - } else { - updatePeriodPref.setSummary(String.valueOf(updatePeriod) + " ms"); - } - } catch (NumberFormatException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.update_period_msg),null,null, Snackbar.LENGTH_SHORT); - updatePeriodPref.setSummary("1000 ms"); - updatePeriodPref.setText("1000"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(s, "1000"); - editor.commit(); - } - break; - default: - break; - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/OscilloscopePlaybackFragment.java b/app/src/main/java/io/pslab/fragment/OscilloscopePlaybackFragment.java deleted file mode 100644 index bac1ba91f..000000000 --- a/app/src/main/java/io/pslab/fragment/OscilloscopePlaybackFragment.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.pslab.fragment; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; - -import io.pslab.R; -import io.pslab.activity.OscilloscopeActivity; - -public class OscilloscopePlaybackFragment extends Fragment { - - private OscilloscopeActivity oscilloscopeActivity; - private TextView timebaseTextView; - - public static OscilloscopePlaybackFragment newInstance() { - return new OscilloscopePlaybackFragment(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_oscilloscope_playback, container, false); - timebaseTextView = rootView.findViewById(R.id.timebase_data); - CheckBox fourierCheckBox = rootView.findViewById(R.id.fourier_checkbox); - - fourierCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - oscilloscopeActivity.isPlaybackFourierChecked = isChecked; - } - }); - return rootView; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - oscilloscopeActivity = (OscilloscopeActivity) getActivity(); - } - - public void setTimeBase(String timeBase) { - timebaseTextView.setText(timeBase); - } -} - diff --git a/app/src/main/java/io/pslab/fragment/PSLabPinLayoutFragment.java b/app/src/main/java/io/pslab/fragment/PSLabPinLayoutFragment.java deleted file mode 100644 index 570a3a76c..000000000 --- a/app/src/main/java/io/pslab/fragment/PSLabPinLayoutFragment.java +++ /dev/null @@ -1,250 +0,0 @@ -package io.pslab.fragment; - -import android.annotation.SuppressLint; -import android.app.Activity; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Color; -import android.graphics.Matrix; -import android.graphics.PointF; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.ImageView; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.AlertDialog; -import androidx.core.content.res.ResourcesCompat; -import androidx.fragment.app.Fragment; - -import java.util.ArrayList; -import java.util.List; - -import io.pslab.R; -import io.pslab.items.PinDetails; - -public class PSLabPinLayoutFragment extends Fragment implements View.OnTouchListener { - - private final List pinDetails = new ArrayList<>(); - - private final Matrix matrix = new Matrix(); - private final Matrix savedMatrix = new Matrix(); - - public static boolean frontSide = true; - - private static final int NONE = 0; - private static final int DRAG = 1; - private static final int ZOOM = 2; - private int mode = NONE; - - private final PointF start = new PointF(); - private final PointF mid = new PointF(); - private float oldDist = 1f; - - private ImageView colorMap; - - private ImageView imgLayout; - - public static PSLabPinLayoutFragment newInstance() { - return new PSLabPinLayoutFragment(); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_pin_layout, container, false); - imgLayout = view.findViewById(R.id.img_pslab_pin_layout); - colorMap = view.findViewById(R.id.img_pslab_color_map); - return view; - } - - @Override - public void onResume() { - super.onResume(); - imgLayout.setImageDrawable(ResourcesCompat.getDrawable(getResources(), - frontSide ? R.drawable.pslab_v5_front_layout : R.drawable.pslab_v5_back_layout, null)); - colorMap.setImageDrawable(ResourcesCompat.getDrawable(getResources(), - frontSide ? R.drawable.pslab_v5_front_colormap : R.drawable.pslab_v5_back_colormap, null)); - imgLayout.setOnTouchListener(this); - populatePinDetails(); - } - - @Override - public void onPause() { - super.onPause(); - imgLayout.setImageDrawable(null); - colorMap.setImageDrawable(null); - // Force garbage collection to avoid OOM on older devices. - System.gc(); - } - - private void populatePinDetails() { - pinDetails.add(new PinDetails(getString(R.string.pin_esp_name), getString(R.string.pin_esp_description), getColor(R.color.category_usb), getColor(R.color.pin_esp))); - pinDetails.add(new PinDetails(getString(R.string.pin_rxd_name), getString(R.string.pin_rxd_description), getColor(R.color.category_communication), getColor(R.color.pin_rxd))); - pinDetails.add(new PinDetails(getString(R.string.pin_txd_name), getString(R.string.pin_txd_description), getColor(R.color.category_communication), getColor(R.color.pin_txd))); - pinDetails.add(new PinDetails(getString(R.string.pin_gnd_name), getString(R.string.pin_gnd_description), getColor(R.color.category_voltage), getColor(R.color.pin_gnd))); - pinDetails.add(new PinDetails(getString(R.string.pin_si1_name), getString(R.string.pin_si1_description), getColor(R.color.category_wavegen), getColor(R.color.pin_si1))); - pinDetails.add(new PinDetails(getString(R.string.pin_si2_name), getString(R.string.pin_si2_description), getColor(R.color.category_wavegen), getColor(R.color.pin_si2))); - pinDetails.add(new PinDetails(getString(R.string.pin_sq1_name), getString(R.string.pin_sq1_description), getColor(R.color.category_wavegen), getColor(R.color.pin_sq1))); - pinDetails.add(new PinDetails(getString(R.string.pin_sq2_name), getString(R.string.pin_sq2_description), getColor(R.color.category_wavegen), getColor(R.color.pin_sq2))); - pinDetails.add(new PinDetails(getString(R.string.pin_sq3_name), getString(R.string.pin_sq3_description), getColor(R.color.category_wavegen), getColor(R.color.pin_sq3))); - pinDetails.add(new PinDetails(getString(R.string.pin_sq4_name), getString(R.string.pin_sq4_description), getColor(R.color.category_wavegen), getColor(R.color.pin_sq4))); - pinDetails.add(new PinDetails(getString(R.string.pin_la1_name), getString(R.string.pin_la1_description), getColor(R.color.category_wavegen), getColor(R.color.pin_la1))); - pinDetails.add(new PinDetails(getString(R.string.pin_la2_name), getString(R.string.pin_la2_description), getColor(R.color.category_wavegen), getColor(R.color.pin_la2))); - pinDetails.add(new PinDetails(getString(R.string.pin_la3_name), getString(R.string.pin_la3_description), getColor(R.color.category_wavegen), getColor(R.color.pin_la3))); - pinDetails.add(new PinDetails(getString(R.string.pin_la4_name), getString(R.string.pin_la4_description), getColor(R.color.category_wavegen), getColor(R.color.pin_la4))); - pinDetails.add(new PinDetails(getString(R.string.pin_ac1_name), getString(R.string.pin_ac1_description), getColor(R.color.category_oscilloscope), getColor(R.color.pin_ac1))); - pinDetails.add(new PinDetails(getString(R.string.pin_ch1_name), getString(R.string.pin_ch1_description), getColor(R.color.category_oscilloscope), getColor(R.color.pin_ch1))); - pinDetails.add(new PinDetails(getString(R.string.pin_ch2_name), getString(R.string.pin_ch2_description), getColor(R.color.category_oscilloscope), getColor(R.color.pin_ch2))); - pinDetails.add(new PinDetails(getString(R.string.pin_ch3_name), getString(R.string.pin_ch3_description), getColor(R.color.category_oscilloscope), getColor(R.color.pin_ch3))); - pinDetails.add(new PinDetails(getString(R.string.pin_chg_name), getString(R.string.pin_chg_description), getColor(R.color.category_oscilloscope), getColor(R.color.pin_chg))); - pinDetails.add(new PinDetails(getString(R.string.pin_mic_name), getString(R.string.pin_mic_description), getColor(R.color.category_measurement), getColor(R.color.pin_mic))); - pinDetails.add(new PinDetails(getString(R.string.pin_frq_name), getString(R.string.pin_frq_description), getColor(R.color.category_measurement), getColor(R.color.pin_frq))); - pinDetails.add(new PinDetails(getString(R.string.pin_cap_name), getString(R.string.pin_cap_description), getColor(R.color.category_measurement), getColor(R.color.pin_cap))); - pinDetails.add(new PinDetails(getString(R.string.pin_res_name), getString(R.string.pin_res_description), getColor(R.color.category_measurement), getColor(R.color.pin_res))); - pinDetails.add(new PinDetails(getString(R.string.pin_vol_name), getString(R.string.pin_vol_description), getColor(R.color.category_measurement), getColor(R.color.pin_vol))); - pinDetails.add(new PinDetails(getString(R.string.pin_pcs_name), getString(R.string.pin_pcs_description), getColor(R.color.category_power_source), getColor(R.color.pin_pcs))); - pinDetails.add(new PinDetails(getString(R.string.pin_pv3_name), getString(R.string.pin_pv3_description), getColor(R.color.category_power_source), getColor(R.color.pin_pv3))); - pinDetails.add(new PinDetails(getString(R.string.pin_pv2_name), getString(R.string.pin_pv2_description), getColor(R.color.category_power_source), getColor(R.color.pin_pv2))); - pinDetails.add(new PinDetails(getString(R.string.pin_pv1_name), getString(R.string.pin_pv1_description), getColor(R.color.category_power_source), getColor(R.color.pin_pv1))); - pinDetails.add(new PinDetails(getString(R.string.pin_scl_name), getString(R.string.pin_scl_description), getColor(R.color.category_communication), getColor(R.color.pin_scl))); - pinDetails.add(new PinDetails(getString(R.string.pin_sda_name), getString(R.string.pin_sda_description), getColor(R.color.category_communication), getColor(R.color.pin_sda))); - pinDetails.add(new PinDetails(getString(R.string.pin_vdd_name), getString(R.string.pin_vdd_description), getColor(R.color.category_voltage), getColor(R.color.pin_vdd))); - pinDetails.add(new PinDetails(getString(R.string.pin_sta_name), getString(R.string.pin_sta_description), getColor(R.color.category_communication), getColor(R.color.pin_sta))); - pinDetails.add(new PinDetails(getString(R.string.pin_vpl_name), getString(R.string.pin_vpl_description), getColor(R.color.category_voltage), getColor(R.color.pin_vpl))); - pinDetails.add(new PinDetails(getString(R.string.pin_ena_name), getString(R.string.pin_ena_description), getColor(R.color.category_communication), getColor(R.color.pin_ena))); - pinDetails.add(new PinDetails(getString(R.string.pin_vmi_name), getString(R.string.pin_vmi_description), getColor(R.color.category_voltage), getColor(R.color.pin_vmi))); - pinDetails.add(new PinDetails(getString(R.string.pin_mcl_name), getString(R.string.pin_mcl_description), getColor(R.color.category_communication), getColor(R.color.pin_mcl))); - pinDetails.add(new PinDetails(getString(R.string.pin_pgm_name), getString(R.string.pin_pgm_description), getColor(R.color.category_communication), getColor(R.color.pin_pgm))); - pinDetails.add(new PinDetails(getString(R.string.pin_pgc_name), getString(R.string.pin_pgc_description), getColor(R.color.category_communication), getColor(R.color.pin_pgc))); - pinDetails.add(new PinDetails(getString(R.string.pin_pgd_name), getString(R.string.pin_pgd_description), getColor(R.color.category_communication), getColor(R.color.pin_pgd))); - pinDetails.add(new PinDetails(getString(R.string.pin_nrf_name), getString(R.string.pin_nrf_description), getColor(R.color.category_usb), getColor(R.color.pin_nrf))); - pinDetails.add(new PinDetails(getString(R.string.pin_usb_name), getString(R.string.pin_usb_description), getColor(R.color.category_usb), getColor(R.color.pin_usb))); - pinDetails.add(new PinDetails(getString(R.string.pin_vcc_name), getString(R.string.pin_vcc_description), getColor(R.color.category_voltage), getColor(R.color.pin_vcc))); - pinDetails.add(new PinDetails(getString(R.string.pin_pl5_name), getString(R.string.pin_pl5_description), getColor(R.color.category_voltage), getColor(R.color.pin_pl5))); - pinDetails.add(new PinDetails(getString(R.string.pin_dpl_name), getString(R.string.pin_dpl_description), getColor(R.color.category_usb), getColor(R.color.pin_dpl))); - pinDetails.add(new PinDetails(getString(R.string.pin_dmi_name), getString(R.string.pin_dmi_description), getColor(R.color.category_usb), getColor(R.color.pin_dmi))); - } - - private int getColor(int colorId) { - final Context context = getContext(); - return context == null ? 0 : context.getColor(colorId); - } - - @SuppressLint("ClickableViewAccessibility") - @Override - public boolean onTouch(View v, MotionEvent event) { - ImageView view = (ImageView) v; - view.setScaleType(ImageView.ScaleType.MATRIX); - colorMap.setScaleType(ImageView.ScaleType.MATRIX); - float scale; - - switch (event.getAction() & MotionEvent.ACTION_MASK) { - case MotionEvent.ACTION_DOWN: - matrix.set(view.getImageMatrix()); - savedMatrix.set(matrix); - start.set(event.getX(), event.getY()); - mode = DRAG; - break; - - case MotionEvent.ACTION_UP: - colorMap.setDrawingCacheEnabled(true); - Bitmap clickSpot = Bitmap.createBitmap(colorMap.getDrawingCache()); - colorMap.setDrawingCacheEnabled(false); - try { - int pixel = clickSpot.getPixel((int) event.getX(), (int) event.getY()); - for (PinDetails pin : pinDetails) { - if (pin.getColorID() == Color.rgb(Color.red(pixel), Color.green(pixel), Color.blue(pixel))) { - displayPinDescription(pin); - } - } - } catch (IllegalArgumentException e) {/**/} - break; - - case MotionEvent.ACTION_POINTER_DOWN: - oldDist = spacing(event); - if (oldDist > 5f) { - savedMatrix.set(matrix); - midPoint(mid, event); - mode = ZOOM; - } - break; - - case MotionEvent.ACTION_MOVE: - if (mode == DRAG) { - matrix.set(savedMatrix); - matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); - } else if (mode == ZOOM) { - float newDist = spacing(event); - if (newDist > 5f) { - matrix.set(savedMatrix); - scale = newDist / oldDist; - matrix.postScale(scale, scale, mid.x, mid.y); - } - } - break; - - default: - break; - } - - view.setImageMatrix(matrix); - colorMap.setImageMatrix(matrix); - - return true; - } - - private void displayPinDescription(PinDetails pin) { - final Activity activity = getActivity(); - - if (activity == null) { - return; - } - - final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); - LayoutInflater inflater = getActivity().getLayoutInflater(); - View view = inflater.inflate(R.layout.pin_description_dialog, null); - builder.setView(view); - - ImageView pinColor = view.findViewById(R.id.pin_category_color); - pinColor.setBackgroundColor(pin.getCategoryColor()); - TextView pinTitle = view.findViewById(R.id.pin_description_title); - pinTitle.setText(pin.getName()); - TextView pinDescription = view.findViewById(R.id.pin_description); - pinDescription.setText(pin.getDescription()); - Button dialogButton = view.findViewById(R.id.pin_description_dismiss); - - builder.create(); - final AlertDialog dialog = builder.show(); - - dialogButton.setOnTouchListener((v, event) -> { - view.performClick(); - dialog.dismiss(); - return true; - }); - } - - private float spacing(MotionEvent event) { - float x = 0; - float y = 0; - try { - x = event.getX(0) - event.getX(1); - y = event.getY(0) - event.getY(1); - } catch (Exception e) {/**/} - return (float) Math.sqrt(x * x + y * y); - } - - private void midPoint(PointF point, MotionEvent event) { - float x = 0; - float y = 0; - try { - x = event.getX(0) + event.getX(1); - y = event.getY(0) + event.getY(1); - } catch (Exception e) {/**/} - point.set(x / 2, y / 2); - } -} diff --git a/app/src/main/java/io/pslab/fragment/SettingsFragment.java b/app/src/main/java/io/pslab/fragment/SettingsFragment.java deleted file mode 100644 index 81660737a..000000000 --- a/app/src/main/java/io/pslab/fragment/SettingsFragment.java +++ /dev/null @@ -1,51 +0,0 @@ -package io.pslab.fragment; - -import android.content.SharedPreferences; -import android.os.Bundle; -import androidx.preference.ListPreference; -import androidx.preference.PreferenceFragmentCompat; - -import io.pslab.R; - -/** - * Created by viveksb007 on 15/3/17. - */ - -public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { - - public static final String KEY_EXPORT_DATA_FORMAT_LIST = "export_data_format_list"; - private ListPreference listPreference; - - public static SettingsFragment newInstance() { - return new SettingsFragment(); - } - - public SettingsFragment() { - } - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - setPreferencesFromResource(R.xml.settings_preference_fragment, rootKey); - listPreference = (ListPreference) getPreferenceScreen().findPreference(KEY_EXPORT_DATA_FORMAT_LIST); - } - - @Override - public void onResume() { - super.onResume(); - listPreference.setSummary("Current format is " + listPreference.getEntry().toString()); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - if (KEY_EXPORT_DATA_FORMAT_LIST.equals(key)) { - listPreference.setSummary("Current format is " + listPreference.getEntry().toString()); - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/SoundMeterDataFragment.java b/app/src/main/java/io/pslab/fragment/SoundMeterDataFragment.java deleted file mode 100644 index 0759487eb..000000000 --- a/app/src/main/java/io/pslab/fragment/SoundMeterDataFragment.java +++ /dev/null @@ -1,606 +0,0 @@ -package io.pslab.fragment; - -import android.graphics.Bitmap; -import android.graphics.Color; -import android.location.Location; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import android.os.HandlerThread; -import android.os.Message; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; - -import com.github.anastr.speedviewlib.PointerSpeedometer; -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.LimitLine; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Date; -import java.util.Deque; -import java.util.List; -import java.util.Locale; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import io.pslab.R; -import io.pslab.activity.SoundMeterActivity; -import io.pslab.interfaces.OperationCallback; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.models.SoundData; -import io.pslab.others.AudioJack; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; - -import static io.pslab.others.CSVLogger.CSV_DIRECTORY; - -public class SoundMeterDataFragment extends Fragment implements OperationCallback { - - public static final String TAG = "SoundMeterFragment"; - private static final CSVDataLine CSV_HEADER = - new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("Readings") - .add("Latitude") - .add("Longitude"); - private static final String KEY_LOUDNESS = "key loudness"; - private static final String KEY_MAX_LOUDNESS = "key max loudness"; - private static final String KEY_MIN_LOUDNESS = "key min loudness"; - private static final String KEY_AVG_LOUDNESS = "key average loudness"; - private static final int ANIMATION_BUFFER_SIZE = 500; - - private static double refIntensity; - private static int movingAvgWindowSize; - - @BindView(R.id.sound_max) - TextView statMax; - @BindView(R.id.sound_min) - TextView statMin; - @BindView(R.id.sound_avg) - TextView statMean; - @BindView(R.id.label_sound_sensor) - TextView sensorLabel; - @BindView(R.id.chart_sound_meter) - LineChart mChart; - @BindView(R.id.sound_meter) - PointerSpeedometer decibelMeter; - - private SoundMeterActivity soundMeter; - private View rootView; - private Unbinder unbinder; - private AudioJack audioJack; - private List recordedSoundData; - private int counter; - - /** - * Thread to handle processing in background - */ - private HandlerThread bgThread; - - /** - * Handler for the background Thread - */ - private Handler bgThreadHandler; - - /** - * Handler for the UI Thread, so that background thread could communicate with it - */ - private Handler uiHandler; - - /** - * Scheduled executor to view recorded data - */ - private ScheduledExecutorService scheduledExecutorService; - - /** - * Recorded data player handle to cancel the scheduled task created by scheduledExecutorService - */ - ScheduledFuture dataPlayerHandle; - - private boolean isProcessing; - - /** - * variable to store the starting time of recording - */ - private long recordStartTime; - - /** - * variable to store resume time to calculate offset - */ - private long resumeTime; - - /** - * variable to store the current time when playing is paused - */ - private long pauseTime; - - /** - * offset to keep record of time that has already been played before pausing - */ - private long offset; - - private long block; - - /* - Variables to store values during processing - */ - private double maxRmsAmp; - private double minRmsAmp; - private double rmsSum; - - /** - * Double ended queue to how chart entries for current window - */ - private Deque chartQ; - - /** - * Window to calculate the moving average - */ - private Deque movingAvgWindow; - - public static SoundMeterDataFragment newInstance() { - return new SoundMeterDataFragment(); - } - - public static void setParameters(double refIntensity, int movingAvgWindowSize) { - SoundMeterDataFragment.refIntensity = refIntensity; - SoundMeterDataFragment.movingAvgWindowSize = movingAvgWindowSize; - } - - /* ******************************************************************************************** - * Fragment Lifecycle Methods - * ******************************************************************************************** - */ - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - soundMeter = (SoundMeterActivity) getActivity(); - scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); - chartQ = new ArrayDeque<>(); - counter = 0; - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_sound_meter_data, container, false); - unbinder = ButterKnife.bind(this, rootView); - setupInstruments(); - return rootView; - } - - @Override - public void onResume() { - super.onResume(); - startBackgroundThread(); - if(soundMeter.viewingData) { - /* - * reset counter to 0 - */ - recordedSoundData = new ArrayList<>(); - recordedSoundData.addAll(soundMeter.recordedSoundData); - } else { - /* - * Start processing the sound from the environment - */ - startProcessing(); - } - } - - @Override - public void onSaveInstanceState(@NonNull Bundle outState) { - super.onSaveInstanceState(outState); - } - - @Override - public void onPause() { - super.onPause(); - if(soundMeter.playingData) { - pausePlaying(); - } else if (isProcessing) { - stopProcessing(); - } - stopBackgroundThread(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Override - public void onDestroy() { - super.onDestroy(); - soundMeter = null; - scheduledExecutorService = null; - chartQ.clear(); - chartQ = null; - } - - /* ******************************************************************************************** - * Initializer methods - * ******************************************************************************************** - */ - private void setupInstruments() { - decibelMeter.setMaxSpeed(200.0f); - decibelMeter.setMinSpeed(0.0f); - decibelMeter.setWithTremble(false); - - YAxis yAxis = mChart.getAxisLeft(); - - yAxis.setAxisMaximum(200); - yAxis.setAxisMinimum(0); - yAxis.setLabelCount(40); - yAxis.setDrawGridLines(false); - yAxis.setTextColor(Color.WHITE); - LimitLine dangerLine = new LimitLine(100, getString(R.string.limit_dangerous)); - dangerLine.setLineColor(Color.RED); - dangerLine.setTextColor(Color.RED); - yAxis.addLimitLine(dangerLine); - - XAxis x = mChart.getXAxis(); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - - - mChart.setTouchEnabled(true); - mChart.setHighlightPerDragEnabled(true); - mChart.setDragEnabled(true); - mChart.setScaleEnabled(true); - mChart.setDrawGridBackground(false); - mChart.setPinchZoom(true); - mChart.setScaleYEnabled(true); - mChart.setBackgroundColor(Color.BLACK); - mChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - mChart.setData(data); - - Legend l = mChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - } - - /* ******************************************************************************************** - * Members related to handling Background Thread - * ******************************************************************************************** - */ - private void startBackgroundThread() { - Log.i(TAG, "starting background thread"); - bgThread = new HandlerThread("Audio Recorder Thread"); - bgThread.start(); - bgThreadHandler = new Handler(bgThread.getLooper()); - uiHandler = new UIHandler(this); - Log.i(TAG, "background Thread started"); - } - - private void stopBackgroundThread() { - Log.i(TAG, "stopping background thread"); - if (bgThread != null) { - bgThread.quitSafely(); - bgThread = null; - } - bgThreadHandler = null; - uiHandler = null; - Log.i(TAG, "Background Thread Stopped"); - } - - /* ******************************************************************************************** - * Methods related to sound processing - * ******************************************************************************************** - */ - private void startProcessing() { - isProcessing = true; - audioJack = new AudioJack("input"); - recordStartTime = System.currentTimeMillis(); - movingAvgWindow = new ArrayDeque<>(); - bgThreadHandler.post(() -> { - while (isProcessing) { - /* - * read the audio samples from the hardware device - */ - short[] buffer = audioJack.read(); - - /* - * Calculate the root mean square amplitude of the values in the buffer. - */ - double sqrsum = 0.0; - for (short val : buffer) { - sqrsum += Math.pow(val, 2); - } - double rmsamp = Math.sqrt((sqrsum / buffer.length)); - - /* - * update the moving average window - */ - if ((movingAvgWindow.size() >= movingAvgWindowSize)) { - rmsSum -= movingAvgWindow.removeFirst(); - } - movingAvgWindow.addLast(rmsamp); - rmsSum += rmsamp; - - /* - * Calculate average, max and min root-mean-square(rms) amplitude - */ - double avgRmsAmp = rmsSum / movingAvgWindow.size(); - maxRmsAmp = Math.max(rmsamp, maxRmsAmp); - minRmsAmp = Math.min(rmsamp, minRmsAmp); - - /* - * Calculate the current, max, min and average loudness for the current instant - */ - double loudness = rmsamp > 0 ? (10 * Math.log10(rmsamp / refIntensity)) : 1; - double maxLoudness = maxRmsAmp > 0 ? (10 * Math.log10(maxRmsAmp / refIntensity)) : 1; - double minLoudness = minRmsAmp > 0 ? (10 * Math.log10(minRmsAmp / refIntensity)) : 1; - double avgLoudness = avgRmsAmp > 0 ? (10 * Math.log10(avgRmsAmp / refIntensity)) : 1; - - /* - * Bundle the values to be sent to the ui handler - */ - Bundle bundle = new Bundle(); - bundle.putDouble(KEY_LOUDNESS, loudness); - bundle.putDouble(KEY_MAX_LOUDNESS, maxLoudness); - bundle.putDouble(KEY_MIN_LOUDNESS, minLoudness); - bundle.putDouble(KEY_AVG_LOUDNESS, avgLoudness); - Message msg = new Message(); - msg.setData(bundle); - uiHandler.sendMessage(msg); - } - }); - } - - private void stopProcessing() { - isProcessing = false; - audioJack.release(); - audioJack = null; - resetViews(); - } - - /* ******************************************************************************************** - * Methods related to data visualization - * ******************************************************************************************** - */ - private void updateMeter(double loudness, double avgLoudness, double maxLoudness, double minLoudness) { - decibelMeter.setSpeedAt((float) loudness); - statMax.setText(String.format(Locale.getDefault(), PSLabSensor.SOUNDMETER_DATA_FORMAT, maxLoudness)); - statMin.setText(String.format(Locale.getDefault(), PSLabSensor.SOUNDMETER_DATA_FORMAT, minLoudness)); - statMean.setText(String.format(Locale.getDefault(), PSLabSensor.SOUNDMETER_DATA_FORMAT, avgLoudness)); - } - - private void updateChart(double loudness, double avgLoudness, double maxLoudness, double minLoudness, long startTime, long offset) { - float x = (offset + (System.currentTimeMillis() - startTime)) / 1000f; - chartQ.addLast(new Entry(x, (float)loudness)); - if(chartQ.size() > ANIMATION_BUFFER_SIZE) - chartQ.removeFirst(); - List entries = new ArrayList<>(chartQ); - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.sound_chart_label)); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(true); - dataSet.setLineWidth(0.5f); - mChart.setData(new LineData(dataSet)); - mChart.notifyDataSetChanged(); - mChart.invalidate(); - } - - private void resetViews() { - chartQ.clear(); - mChart.clear(); - decibelMeter.setSpeedAt(0.0f); - Log.i(TAG,"view reset complete"); - } - - /* ******************************************************************************************** - * Methods related to view previously recorded data - * ******************************************************************************************** - */ - - private void playRecordedData(long startTime, long offset) { - long period = ( recordedSoundData.get(recordedSoundData.size()-1).getTime() - - recordedSoundData.get(0).getTime() ) / recordedSoundData.size(); - dataPlayerHandle = scheduledExecutorService.scheduleWithFixedDelay(()-> { - SoundData soundData = recordedSoundData.get(counter); - uiHandler.post(() -> { - if(soundMeter.playingData) { - updateChart(soundData.getdB(), soundData.getAvgLoudness(), - soundData.getMaxLoudness(), soundData.getMinLoudness(), startTime, offset); - updateMeter(soundData.getdB(), soundData.getAvgLoudness(), - soundData.getMaxLoudness(), soundData.getMinLoudness()); - } - }); - counter ++; - if(counter == recordedSoundData.size()) { - stopPlaying(); - } - }, 0, period, TimeUnit.MILLISECONDS); - } - - private void startPlaying() { - soundMeter.startedPlay = true; - resumeTime = System.currentTimeMillis(); - playRecordedData(resumeTime, 0); - } - - private void stopPlaying() { - uiHandler.post(()-> { - dataPlayerHandle.cancel(false); - soundMeter.playingData = false; - soundMeter.startedPlay = false; - soundMeter.invalidateOptionsMenu(); - resetViews(); - counter = 0; - resumeTime = 0; - offset = 0; - pauseTime = 0; - }); - } - - private void resumePlaying() { - offset += pauseTime - resumeTime; - resumeTime = System.currentTimeMillis(); - playRecordedData(resumeTime, offset); - } - - private void pausePlaying() { - uiHandler.post(()-> { - dataPlayerHandle.cancel(false); - pauseTime = System.currentTimeMillis(); - soundMeter.playingData = false; - soundMeter.invalidateOptionsMenu(); - }); - } - - /** - * Method to play data which was previously recorded - */ - @Override - public void playData() { - startPlaying(); - } - - /** - * Method to pause playing - */ - public void pause() { - pausePlaying(); - } - - /** - * Method to resume playing - */ - public void resume() { - resumePlaying(); - } - - /** - * Method to stop playing the previously recorded data - */ - @Override - public void stopData() { - stopPlaying(); - } - - /* ******************************************************************************************** - * Method Related to saving sound data - * ******************************************************************************************** - */ - private void writeLog(long timestamp, float dB, float avgLoudness, float maxLoudness, float minLoudness) { - SoundData soundData; - if (getActivity() != null && soundMeter.isRecording) { - if (soundMeter.writeHeaderToFile) { - soundMeter.csvLogger.prepareLogFile(); - soundMeter.csvLogger.writeMetaData(getResources().getString(R.string.lux_meter)); - soundMeter.csvLogger.writeCSVFile(CSV_HEADER); - block = timestamp; - soundMeter.recordSensorDataBlockID(new SensorDataBlock(timestamp, soundMeter.getSensorName())); - soundMeter.writeHeaderToFile = !soundMeter.writeHeaderToFile; - } - if (soundMeter.addLocation && soundMeter.gpsLogger.isGPSEnabled()) { - String dateTime = CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp)); - Location location = soundMeter.gpsLogger.getDeviceLocation(); - soundMeter.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(dateTime) - .add(dB) - .add((location != null)?location.getLatitude():0.0d) - .add((location != null)?location.getLongitude():0.0d)); - soundData = new SoundData(timestamp, block, dB, avgLoudness, maxLoudness, minLoudness, - (location!=null)?location.getLatitude():0.0d, (location!=null)?location.getLongitude():0.0d); - } else { - String dateTime = CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp)); - soundMeter.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(dateTime) - .add(dB) - .add(0.0) - .add(0.0)); - soundData = new SoundData(timestamp, block, dB, avgLoudness, maxLoudness, minLoudness, - 0.0, 0.0); - } - soundMeter.recordSensorData(soundData); - } else { - soundMeter.writeHeaderToFile = true; - } - } - - @Override - public void saveGraph() { - soundMeter.csvLogger.prepareLogFile(); - soundMeter.csvLogger.writeMetaData(getResources().getString(R.string.lux_meter)); - soundMeter.csvLogger.writeCSVFile(CSV_HEADER); - for (SoundData soundData : soundMeter.recordedSoundData) { - soundMeter.csvLogger.writeCSVFile( - new CSVDataLine() - .add(soundData.getTime()) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(soundData.getTime()))) - .add(soundData.getdB()) - .add(soundData.getLat()) - .add(soundData.getLon())); - } - View view = rootView.findViewById(R.id.soundmeter_linearlayout); - view.setDrawingCacheEnabled(true); - Bitmap b = view.getDrawingCache(); - try { - b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + soundMeter.getSensorName() + - File.separator + CSVLogger.FILE_NAME_FORMAT.format(new Date()) + "_graph.jpg")); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - /** - * The implementation of Handler class for the UI Thread - */ - private static class UIHandler extends Handler { - private SoundMeterDataFragment soundMeterDataFragment; - - UIHandler(SoundMeterDataFragment fragment) { - this.soundMeterDataFragment = fragment; - } - - @Override - public void handleMessage(Message msg) { //handle the message passed by the background thread which is processing the audio - if (soundMeterDataFragment.isResumed()) { - Bundle bundle = msg.getData(); - double loudness = bundle.getDouble(KEY_LOUDNESS); - double maxLoudness = bundle.getDouble(KEY_MAX_LOUDNESS); - double minLoudness = bundle.getDouble(KEY_MIN_LOUDNESS); - double avgLoudness = bundle.getDouble(KEY_AVG_LOUDNESS); - soundMeterDataFragment.updateMeter(loudness, avgLoudness, maxLoudness, minLoudness); - soundMeterDataFragment.updateChart(loudness, avgLoudness, maxLoudness, minLoudness, soundMeterDataFragment.recordStartTime, 0); - soundMeterDataFragment.writeLog(System.currentTimeMillis(), (float) loudness, (float)avgLoudness, (float)maxLoudness, (float)minLoudness); - } - } - } - -} diff --git a/app/src/main/java/io/pslab/fragment/SoundmeterSettingsFragment.java b/app/src/main/java/io/pslab/fragment/SoundmeterSettingsFragment.java deleted file mode 100644 index fdf3a30f4..000000000 --- a/app/src/main/java/io/pslab/fragment/SoundmeterSettingsFragment.java +++ /dev/null @@ -1,64 +0,0 @@ -package io.pslab.fragment; - -import android.content.SharedPreferences; -import android.os.Bundle; -import androidx.preference.CheckBoxPreference; -import androidx.preference.PreferenceFragmentCompat; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.others.PSLabPermission; - -/** - * @author reckoner1429 - */ -public class SoundmeterSettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { - - - public static final String KEY_INCLUDE_LOCATION = "include_location_sensor_data"; - - private CheckBoxPreference locationPreference; - private PSLabPermission psLabPermission; - private SharedPreferences sharedPref; - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - setPreferencesFromResource(R.xml.sound_meter_settings,rootKey); - locationPreference = (CheckBoxPreference) getPreferenceScreen().findPreference(KEY_INCLUDE_LOCATION); - - sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); - psLabPermission = PSLabPermission.getInstance(); - if (!psLabPermission.checkPermissions(getActivity(), PSLabPermission.MAP_PERMISSION)) { - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putBoolean(LuxMeterSettingFragment.KEY_INCLUDE_LOCATION, true); - editor.apply(); - } - } - @Override - public void onResume() { - super.onResume(); - locationPreference.setChecked(sharedPref.getBoolean(KEY_INCLUDE_LOCATION, true)); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); - } - - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { - switch (s) { - case KEY_INCLUDE_LOCATION: - if (locationPreference.isChecked()) { - psLabPermission.checkPermissions( - getActivity(), PSLabPermission.MAP_PERMISSION); - } - break; - default: - break; - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/ThermometerDataFragment.java b/app/src/main/java/io/pslab/fragment/ThermometerDataFragment.java deleted file mode 100644 index 7005352a0..000000000 --- a/app/src/main/java/io/pslab/fragment/ThermometerDataFragment.java +++ /dev/null @@ -1,627 +0,0 @@ -package io.pslab.fragment; - -import android.graphics.Bitmap; -import android.graphics.Color; -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; -import android.location.Location; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import androidx.annotation.NonNull; - -import com.google.android.material.snackbar.Snackbar; -import androidx.fragment.app.Fragment; - -import androidx.preference.PreferenceManager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.github.anastr.speedviewlib.PointerSpeedometer; -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.Locale; -import java.util.Timer; -import java.util.TimerTask; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.activity.ThermometerActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.SHT21; -import io.pslab.interfaces.OperationCallback; -import io.pslab.models.PSLabSensor; -import io.pslab.models.SensorDataBlock; -import io.pslab.models.ThermometerData; -import io.pslab.others.CSVDataLine; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.ScienceLabCommon; - -import static android.content.Context.SENSOR_SERVICE; -import static io.pslab.others.CSVLogger.CSV_DIRECTORY; - -public class ThermometerDataFragment extends Fragment implements OperationCallback { - - private static final String TEMPERATURE = "temperature"; - private static final CSVDataLine CSV_HEADER = new CSVDataLine() - .add("Timestamp") - .add("DateTime") - .add("Readings") - .add("Latitude") - .add("Longitude"); - private static int sensorType = 0; - private static int highLimit = 50; - private static int updatePeriod = 1000; - private long timeElapsed; - private int count = 0, turns = 0; - private float sum = 0; - private boolean returningFromPause = false; - private static String unit = "°C"; - private float tempValue = -1; - - private enum THERMOMETER_SENSOR {INBUILT_SENSOR, SHT21_SENSOR} - - @BindView(R.id.thermo_max) - TextView statMax; - @BindView(R.id.thermo_min) - TextView statMin; - @BindView(R.id.thermo_avg) - TextView statMean; - @BindView(R.id.label_thermo_sensor) - TextView sensorLabel; - @BindView(R.id.chart_thermo_meter) - LineChart mChart; - @BindView(R.id.thermo_meter) - PointerSpeedometer thermometer; - @BindView(R.id.label_thermo_stat_min) - TextView label_statMin; - @BindView(R.id.label_thermo_stat_avg) - TextView label_statAvg; - @BindView(R.id.label_thermo_stat_max) - TextView label_statMax; - - private Timer graphTimer; - private SensorManager sensorManager; - private Sensor sensor; - private long startTime, block; - private ArrayList entries; - private ArrayList recordedThermoArray; - private ThermometerData sensorData; - private float currentMin = 125; - private float currentMax = -40; - private YAxis y; - private Unbinder unbinder; - private long previousTimeElapsed = (System.currentTimeMillis() - startTime) / updatePeriod; - private ThermometerActivity thermoSensor; - private ThermometerSettingsFragment thermoSettings; - private View rootView; - - public static ThermometerDataFragment newInstance() { - return new ThermometerDataFragment(); - } - - public static void setParameters(int updatePeriod, String type, String unit) { - ThermometerDataFragment.updatePeriod = updatePeriod; - ThermometerDataFragment.sensorType = Integer.valueOf(type); - ThermometerDataFragment.unit = unit; - - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - startTime = System.currentTimeMillis(); - entries = new ArrayList<>(); - thermoSensor = (ThermometerActivity) getActivity(); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.activity_thermometer, container, false); - unbinder = ButterKnife.bind(this, rootView); - setupInstruments(); - return rootView; - } - - @Override - public void onResume() { - super.onResume(); - if (thermoSensor.playingData) { - sensorLabel.setText(getResources().getString(R.string.thermometer)); - recordedThermoArray = new ArrayList<>(); - resetInstrumentData(); - playRecordedData(); - } else if (thermoSensor.viewingData) { - sensorLabel.setText(getResources().getString(R.string.thermometer)); - recordedThermoArray = new ArrayList<>(); - resetInstrumentData(); - plotAllRecordedData(); - } else if (!thermoSensor.isRecording) { - updateGraphs(); - sum = 0; - count = 0; - setUnit(); - entries.clear(); - mChart.clear(); - mChart.invalidate(); - initiateThermoSensor(sensorType); - } else if (returningFromPause) { - updateGraphs(); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - if (graphTimer != null) { - graphTimer.cancel(); - } - if (sensorManager != null) { - sensorManager.unregisterListener(thermoSensorEventListener); - } - unbinder.unbind(); - } - - private void plotAllRecordedData() { - recordedThermoArray.addAll(thermoSensor.recordedThermometerData); - if (recordedThermoArray.size() != 0) { - for (ThermometerData d : recordedThermoArray) { - if (currentMax < d.getTemp()) { - currentMax = d.getTemp(); - } - if (currentMin > d.getTemp()) { - currentMin = d.getTemp(); - } - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getTemp()); - entries.add(entry); - thermometer.setWithTremble(false); - thermometer.setSpeedAt(d.getTemp()); - sum += entry.getY(); - } - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setLabelCount(10); - statMax.setText(String.format(Locale.getDefault(), PSLabSensor.THERMOMETER_DATA_FORMAT, currentMax)); - statMin.setText(String.format(Locale.getDefault(), PSLabSensor.THERMOMETER_DATA_FORMAT, currentMin)); - statMean.setText(String.format(Locale.getDefault(), PSLabSensor.THERMOMETER_DATA_FORMAT, (sum / recordedThermoArray.size()))); - - LineDataSet dataSet = new LineDataSet(entries, PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(thermoSettings.KEY_THERMO_UNIT, "°C")); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(800); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } - } - - private void playRecordedData() { - recordedThermoArray.addAll(thermoSensor.recordedThermometerData); - try { - if (recordedThermoArray.size() > 1) { - ThermometerData i = recordedThermoArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - private void processRecordedData(long timeGap) { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } else { - graphTimer = new Timer(); - } - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - if (thermoSensor.playingData) { - try { - ThermometerData d = recordedThermoArray.get(turns); - turns++; - if (currentMax < d.getTemp()) { - currentMax = d.getTemp(); - statMax.setText(String.format(Locale.getDefault(), PSLabSensor.THERMOMETER_DATA_FORMAT, d.getTemp())); - } - if (currentMin > d.getTemp()) { - currentMin = d.getTemp(); - statMin.setText(String.format(Locale.getDefault(), PSLabSensor.THERMOMETER_DATA_FORMAT, d.getTemp())); - } - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setLabelCount(10); - thermometer.setWithTremble(false); - thermometer.setSpeedAt(d.getTemp()); - - Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getTemp()); - entries.add(entry); - count++; - sum += entry.getY(); - statMean.setText(DataFormatter.formatDouble((sum / count), PSLabSensor.THERMOMETER_DATA_FORMAT)); - - LineDataSet dataSet = new LineDataSet(entries, PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(thermoSettings.KEY_THERMO_UNIT.toString(), "°C")); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(800); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } catch (IndexOutOfBoundsException e) { - graphTimer.cancel(); - graphTimer = null; - turns = 0; - thermoSensor.playingData = false; - thermoSensor.startedPlay = false; - thermoSensor.invalidateOptionsMenu(); - } - } - } - }); - } - }, 0, timeGap); - } - - @Override - public void stopData() { - if (graphTimer != null) { - graphTimer.cancel(); - graphTimer = null; - } - recordedThermoArray.clear(); - entries.clear(); - plotAllRecordedData(); - thermoSensor.startedPlay = false; - thermoSensor.playingData = false; - turns = 0; - thermoSensor.invalidateOptionsMenu(); - } - - @Override - public void playData() { - resetInstrumentData(); - thermoSensor.startedPlay = true; - try { - if (recordedThermoArray.size() > 1) { - ThermometerData i = recordedThermoArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_SHORT); - } - } - - @Override - public void saveGraph() { - thermoSensor.csvLogger.prepareLogFile(); - thermoSensor.csvLogger.writeMetaData(getResources().getString(R.string.thermometer)); - thermoSensor.csvLogger.writeCSVFile(CSV_HEADER); - for (ThermometerData thermometerData : thermoSensor.recordedThermometerData) { - thermoSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(thermometerData.getTime()) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(thermometerData.getTime()))) - .add(thermometerData.getTemp()) - .add(thermometerData.getLat()) - .add(thermometerData.getLon()) - ); - } - View view = rootView.findViewById(R.id.thermometer_linearlayout); - view.setDrawingCacheEnabled(true); - Bitmap b = view.getDrawingCache(); - try { - b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + thermoSensor.getSensorName() + - File.separator + CSVLogger.FILE_NAME_FORMAT.format(new Date()) + "_graph.jpg")); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - - private void setupInstruments() { - setUnit(); - XAxis x = mChart.getXAxis(); - this.y = mChart.getAxisLeft(); - YAxis y2 = mChart.getAxisRight(); - - mChart.setTouchEnabled(true); - mChart.setHighlightPerDragEnabled(true); - mChart.setDragEnabled(true); - mChart.setScaleEnabled(true); - mChart.setDrawGridBackground(false); - mChart.setPinchZoom(true); - mChart.setScaleYEnabled(true); - mChart.setBackgroundColor(Color.BLACK); - mChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - mChart.setData(data); - - Legend l = mChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setDrawGridLines(true); - y.setLabelCount(10); - - y2.setDrawGridLines(false); - y2.setMaxWidth(0); - } - - @Override - public void onPause() { - super.onPause(); - if (graphTimer != null) { - returningFromPause = true; - graphTimer.cancel(); - graphTimer = null; - if (thermoSensor.playingData) { - thermoSensor.finish(); - } - } - } - - private void updateGraphs() { - final Handler handler = new Handler(); - if (graphTimer != null) { - graphTimer.cancel(); - } - graphTimer = new Timer(); - graphTimer.schedule(new TimerTask() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - try { - visualizeData(); - } catch (NullPointerException e) { - /* Pass for another refresh round */ - } - } - }); - } - }, 0, updatePeriod); - } - - private void writeLogToFile(long timestamp, float sensorReading) { - if (getActivity() != null && thermoSensor.isRecording) { - if (thermoSensor.writeHeaderToFile) { - thermoSensor.csvLogger.prepareLogFile(); - thermoSensor.csvLogger.writeMetaData(getResources().getString(R.string.thermometer)); - thermoSensor.csvLogger.writeCSVFile(CSV_HEADER); - block = timestamp; - thermoSensor.recordSensorDataBlockID(new SensorDataBlock(timestamp, thermoSensor.getSensorName())); - thermoSensor.writeHeaderToFile = !thermoSensor.writeHeaderToFile; - } - if (thermoSensor.addLocation && thermoSensor.gpsLogger.isGPSEnabled()) { - String dateTime = CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp)); - Location location = thermoSensor.gpsLogger.getDeviceLocation(); - thermoSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(dateTime) - .add(sensorReading) - .add(location.getLatitude()) - .add(location.getLongitude()) - ); - sensorData = new ThermometerData(timestamp, block, tempValue, location.getLatitude(), location.getLongitude()); - } else { - thermoSensor.csvLogger.writeCSVFile( - new CSVDataLine() - .add(timestamp) - .add(CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp))) - .add(sensorReading) - .add(0.0) - .add(0.0) - ); - sensorData = new ThermometerData(timestamp, block, tempValue, 0.0, 0.0); - } - thermoSensor.recordSensorData(sensorData); - } else { - thermoSensor.writeHeaderToFile = true; - } - } - - private void visualizeData() { - if (currentMax < tempValue) { - currentMax = tempValue; - statMax.setText(String.format(Locale.getDefault(), PSLabSensor.THERMOMETER_DATA_FORMAT, tempValue)); - } - if (currentMin > tempValue) { - currentMin = tempValue; - statMin.setText(String.format(Locale.getDefault(), PSLabSensor.THERMOMETER_DATA_FORMAT, tempValue)); - } - y.setAxisMaximum(currentMax); - y.setAxisMinimum(currentMin); - y.setLabelCount(10); - if (tempValue >= 0) { - thermometer.setWithTremble(false); - thermometer.setSpeedAt(tempValue); - if (tempValue > highLimit) - thermometer.setBackgroundCircleColor(Color.RED); - else { - thermometer.setBackgroundCircleColor(getResources().getColor(R.color.primaryBlue)); - } - - timeElapsed = ((System.currentTimeMillis() - startTime) / updatePeriod); - if (timeElapsed != previousTimeElapsed) { - previousTimeElapsed = timeElapsed; - Entry entry = new Entry((float) timeElapsed, tempValue); - Long currentTime = System.currentTimeMillis(); - writeLogToFile(currentTime, tempValue); - entries.add(entry); - - count++; - sum += entry.getY(); - statMean.setText(String.format(Locale.getDefault(), PSLabSensor.THERMOMETER_DATA_FORMAT, (sum / count))); - - LineDataSet dataSet = new LineDataSet(entries, PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(thermoSettings.KEY_THERMO_UNIT, "°C")); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setLineWidth(2); - LineData data = new LineData(dataSet); - - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(800); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - } - } - } - - private SensorEventListener thermoSensorEventListener = new SensorEventListener() { - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) {/**/} - - @Override - public void onSensorChanged(SensorEvent event) { - if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE) { - tempValue = event.values[0]; - } - } - }; - - private void resetInstrumentData() { - tempValue = 0; - count = 0; - setUnit(); - sum = 0; - sensor = null; - if (sensorManager != null) { - sensorManager.unregisterListener(thermoSensorEventListener); - } - startTime = System.currentTimeMillis(); - statMax.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - statMin.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - statMean.setText(DataFormatter.formatDouble(0, DataFormatter.LOW_PRECISION_FORMAT)); - thermometer.setSpeedAt(0); - thermometer.setWithTremble(false); - entries.clear(); - } - - private void initiateThermoSensor(int type) { - THERMOMETER_SENSOR s = THERMOMETER_SENSOR.values()[type]; - resetInstrumentData(); - ScienceLab scienceLab; - switch (s) { - case INBUILT_SENSOR: - sensorLabel.setText(getResources().getStringArray(R.array.thermo_sensors)[0]); - sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE); - sensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); - if (sensor == null) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.no_thermometer_sensor), null, null, Snackbar.LENGTH_LONG); - } else { - float max = sensor.getMaximumRange(); - PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putFloat(thermoSensor.THERMOMETER_MAX_LIMIT, max).apply(); - thermometer.setMaxSpeed(max); - sensorManager.registerListener(thermoSensorEventListener, - sensor, SensorManager.SENSOR_DELAY_FASTEST); - } - break; - case SHT21_SENSOR: - sensorLabel.setText(getResources().getStringArray(R.array.thermo_sensors)[1]); - scienceLab = ScienceLabCommon.scienceLab; - if (scienceLab.isConnected()) { - try { - I2C i2c = scienceLab.i2c; - ArrayList data; - data = i2c.scan(null); - if (data.contains(0x39)) { - SHT21 sensorSHT21 = new SHT21(i2c, scienceLab); - sensorSHT21.selectParameter(TEMPERATURE); - sensorType = 1; - } else { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.sensor_not_connected_tls), null, null, Snackbar.LENGTH_SHORT); - sensorType = 0; - } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - } else { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.device_not_found), null, null, Snackbar.LENGTH_SHORT); - sensorType = 0; - } - break; - default: - break; - } - } - - public void setUnit() { - if ("°F".equals(ThermometerDataFragment.unit)) { - currentMax = 257; - currentMin = -40; - thermometer.setMaxSpeed(PreferenceManager.getDefaultSharedPreferences(getActivity()).getFloat(thermoSensor.THERMOMETER_MAX_LIMIT, 257)); - thermometer.setMinSpeed(PreferenceManager.getDefaultSharedPreferences(getActivity()).getFloat(thermoSensor.THERMOMETER_MIN_LIMIT, -40)); - label_statAvg.setText(R.string.avg_thermo_fahrenheit); - label_statMax.setText(R.string.max_thermo_fahrenheit); - label_statMin.setText(R.string.min_thermo_fahrenheit); - thermometer.setUnit("°F"); - } else { - currentMax = 125; - currentMin = -40; - thermometer.setMaxSpeed(PreferenceManager.getDefaultSharedPreferences(getActivity()).getFloat(thermoSensor.THERMOMETER_MAX_LIMIT, 125)); - thermometer.setMinSpeed(PreferenceManager.getDefaultSharedPreferences(getActivity()).getFloat(thermoSensor.THERMOMETER_MIN_LIMIT, -40)); - label_statAvg.setText(R.string.avg_thermo_celcius); - label_statMax.setText(R.string.max_thermo_celcius); - label_statMin.setText(R.string.min_thermo_celcius); - thermometer.setUnit("°C"); - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/ThermometerSettingsFragment.java b/app/src/main/java/io/pslab/fragment/ThermometerSettingsFragment.java deleted file mode 100644 index 04b2dacbc..000000000 --- a/app/src/main/java/io/pslab/fragment/ThermometerSettingsFragment.java +++ /dev/null @@ -1,103 +0,0 @@ -package io.pslab.fragment; - -import android.annotation.SuppressLint; -import android.content.SharedPreferences; -import android.os.Bundle; -import com.google.android.material.snackbar.Snackbar; -import androidx.preference.CheckBoxPreference; -import androidx.preference.EditTextPreference; -import androidx.preference.ListPreference; -import androidx.preference.PreferenceFragmentCompat; -import androidx.preference.PreferenceManager; - -import io.pslab.R; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.PSLabPermission; - -public class ThermometerSettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { - - public static final String KEY_INCLUDE_LOCATION = "include_location_sensor_data"; - public static final String KEY_UPDATE_PERIOD = "setting_thermo_update_period"; - public static final String KEY_THERMO_SENSOR_TYPE = "setting_thermo_sensor_type"; - public static final String KEY_THERMO_UNIT = "select_temp_unit"; - - private PSLabPermission psLabPermission; - - private EditTextPreference updatePeriodPref; - private CheckBoxPreference locationPreference; - private ListPreference sensorTypePreference; - private SharedPreferences sharedPref; - private ListPreference unitPref; - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - setPreferencesFromResource(R.xml.thermometer_settings, rootKey); - updatePeriodPref = (EditTextPreference) getPreferenceScreen().findPreference(KEY_UPDATE_PERIOD); - locationPreference = (CheckBoxPreference) getPreferenceScreen().findPreference(KEY_INCLUDE_LOCATION); - sensorTypePreference = (ListPreference) getPreferenceScreen().findPreference(KEY_THERMO_SENSOR_TYPE); - unitPref = (ListPreference) getPreferenceScreen().findPreference(KEY_THERMO_UNIT); - sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); - - psLabPermission = PSLabPermission.getInstance(); - if (!psLabPermission.checkPermissions(getActivity(), PSLabPermission.MAP_PERMISSION)) { - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putBoolean(ThermometerSettingsFragment.KEY_INCLUDE_LOCATION, true); - editor.apply(); - } - } - - @Override - public void onResume() { - super.onResume(); - locationPreference.setChecked(sharedPref.getBoolean(KEY_INCLUDE_LOCATION, true)); - updatePeriodPref.setSummary(updatePeriodPref.getText() + " ms"); - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - unitPref.setSummary(unitPref.getEntry()); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); - } - - @SuppressLint("ApplySharedPref") - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { - switch (s) { - case KEY_INCLUDE_LOCATION: - if (locationPreference.isChecked()) { - psLabPermission.checkPermissions( - getActivity(), PSLabPermission.MAP_PERMISSION); - } - break; - case KEY_UPDATE_PERIOD: - try { - Integer updatePeriod = Integer.parseInt(updatePeriodPref.getText()); - if (updatePeriod > 1000 || updatePeriod < 100) { - throw new NumberFormatException(); - } else { - updatePeriodPref.setSummary(updatePeriod + " ms"); - } - } catch (NumberFormatException e) { - CustomSnackBar.showSnackBar(getActivity().findViewById(android.R.id.content), - getString(R.string.update_period_msg),null,null, Snackbar.LENGTH_SHORT); - updatePeriodPref.setSummary("1000 ms"); - updatePeriodPref.setText("1000"); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString(s, "1000"); - editor.commit(); - } - break; - case KEY_THERMO_SENSOR_TYPE: - sensorTypePreference.setSummary(sensorTypePreference.getEntry()); - break; - case KEY_THERMO_UNIT: - unitPref.setSummary(unitPref.getEntry()); - break; - default: - break; - } - } -} diff --git a/app/src/main/java/io/pslab/fragment/TimebaseTriggerFragment.java b/app/src/main/java/io/pslab/fragment/TimebaseTriggerFragment.java deleted file mode 100644 index ca00baeb5..000000000 --- a/app/src/main/java/io/pslab/fragment/TimebaseTriggerFragment.java +++ /dev/null @@ -1,375 +0,0 @@ -package io.pslab.fragment; - -import android.os.Bundle; -import android.util.TypedValue; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.inputmethod.EditorInfo; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.SeekBar; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.fragment.app.Fragment; - -import org.apache.commons.lang3.math.NumberUtils; - -import io.pslab.R; -import io.pslab.activity.OscilloscopeActivity; -import io.pslab.others.FloatSeekBar; - -public class TimebaseTriggerFragment extends Fragment { - - private Spinner spinnerTriggerChannelSelect; - private Spinner spinnerTriggerModeSelect; - private FloatSeekBar seekBarTimebase; - private FloatSeekBar seekBarTrigger; - private TextView textViewTimeBase; - private EditText editTextTrigger; - private CheckBox checkBoxTrigger; - boolean _ignore = false; - - - public static TimebaseTriggerFragment newInstance() { - return new TimebaseTriggerFragment(); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - View v = inflater.inflate(R.layout.fragment_timebase_tigger, container, false); - - //seekBarTimebase = (SeekBar) v.findViewById(R.id.seekBar_timebase_tt); - seekBarTimebase = v.findViewById(R.id.seekBar_timebase_tt); - seekBarTrigger = v.findViewById(R.id.seekBar_trigger); - textViewTimeBase = v.findViewById(R.id.tv_timebase_values_tt); - editTextTrigger = v.findViewById(R.id.tv_trigger_values_tt); - spinnerTriggerChannelSelect = v.findViewById(R.id.spinner_trigger_channel_tt); - spinnerTriggerModeSelect = v.findViewById(R.id.spinner_trigger_mode_tt); - checkBoxTrigger = v.findViewById(R.id.checkbox_trigger_tt); - seekBarTimebase.setSaveEnabled(false); - - boolean tabletSize = getResources().getBoolean(R.bool.isTablet); - - if (tabletSize) { - editTextTrigger.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); - textViewTimeBase.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); - } - - if (OscilloscopeActivity.isInBuiltMicSelected) { - seekBarTimebase.setMax(6); - seekBarTimebase.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - //samples are in the power of 2 so that sinefit can be applied - switch (progress) { - case 0: - textViewTimeBase.setText(getString(R.string.timebase_microsec, 875f)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 0.875; - ((OscilloscopeActivity) getActivity()).setXAxisScale(0.875); - ((OscilloscopeActivity) getActivity()).timebase = 875; - ((OscilloscopeActivity) getActivity()).samples = 512; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 1: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 1f)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 1; - ((OscilloscopeActivity) getActivity()).setXAxisScale(1); - ((OscilloscopeActivity) getActivity()).timebase = 1000; - ((OscilloscopeActivity) getActivity()).samples = 512; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 2: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 2f)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 2; - ((OscilloscopeActivity) getActivity()).setXAxisScale(2); - ((OscilloscopeActivity) getActivity()).timebase = 2000; - ((OscilloscopeActivity) getActivity()).samples = 512; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 3: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 4f)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 4; - ((OscilloscopeActivity) getActivity()).setXAxisScale(4); - ((OscilloscopeActivity) getActivity()).timebase = 4000; - ((OscilloscopeActivity) getActivity()).samples = 512; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 4: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 8f)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 8; - ((OscilloscopeActivity) getActivity()).setXAxisScale(8); - ((OscilloscopeActivity) getActivity()).timebase = 8000; - ((OscilloscopeActivity) getActivity()).samples = 1024; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 5: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 25.60)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 25.60; - ((OscilloscopeActivity) getActivity()).setXAxisScale(25.60); - ((OscilloscopeActivity) getActivity()).timebase = 25600; - ((OscilloscopeActivity) getActivity()).samples = 1024; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 6: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 38.40)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 38.40; - ((OscilloscopeActivity) getActivity()).setXAxisScale(38.40); - ((OscilloscopeActivity) getActivity()).timebase = 38400; - ((OscilloscopeActivity) getActivity()).samples = 1024; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - default: - break; - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - seekBarTimebase.setProgress(0); - } else { - seekBarTimebase.setMax(8); - seekBarTimebase.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - //samples are in the power of 2 so that sinefit can be applied - switch (progress) { - case 0: - textViewTimeBase.setText(getString(R.string.timebase_microsec, 875f)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 0.875; - ((OscilloscopeActivity) getActivity()).setXAxisScale(0.875); - ((OscilloscopeActivity) getActivity()).timebase = 875; - ((OscilloscopeActivity) getActivity()).samples = 512; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 1: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 1f)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 1; - ((OscilloscopeActivity) getActivity()).setXAxisScale(1); - ((OscilloscopeActivity) getActivity()).timebase = 1000; - ((OscilloscopeActivity) getActivity()).samples = 512; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 2: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 2f)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 2; - ((OscilloscopeActivity) getActivity()).setXAxisScale(2); - ((OscilloscopeActivity) getActivity()).timebase = 2000; - ((OscilloscopeActivity) getActivity()).samples = 512; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 3: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 4f)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 4; - ((OscilloscopeActivity) getActivity()).setXAxisScale(4); - ((OscilloscopeActivity) getActivity()).timebase = 4000; - ((OscilloscopeActivity) getActivity()).samples = 512; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 4: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 8f)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 8; - ((OscilloscopeActivity) getActivity()).setXAxisScale(8); - ((OscilloscopeActivity) getActivity()).timebase = 8000; - ((OscilloscopeActivity) getActivity()).samples = 1024; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 5: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 25.60)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 25.60; - ((OscilloscopeActivity) getActivity()).setXAxisScale(25.60); - ((OscilloscopeActivity) getActivity()).timebase = 25600; - ((OscilloscopeActivity) getActivity()).samples = 1024; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 6: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 38.40)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 38.40; - ((OscilloscopeActivity) getActivity()).setXAxisScale(38.40); - ((OscilloscopeActivity) getActivity()).timebase = 38400; - ((OscilloscopeActivity) getActivity()).samples = 1024; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 7: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 51.20)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 51.20; - ((OscilloscopeActivity) getActivity()).setXAxisScale(51.20); - ((OscilloscopeActivity) getActivity()).timebase = 51200; - ((OscilloscopeActivity) getActivity()).samples = 1024; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - case 8: - textViewTimeBase.setText(getString(R.string.timebase_milisec, 102.40)); - ((OscilloscopeActivity) getActivity()).xAxisScale = 102.40; - ((OscilloscopeActivity) getActivity()).setXAxisScale(102.40); - ((OscilloscopeActivity) getActivity()).timebase = 102400; - ((OscilloscopeActivity) getActivity()).samples = 1024; - ((OscilloscopeActivity) getActivity()).timeGap = (2 * ((OscilloscopeActivity) getActivity()).timebase) / ((OscilloscopeActivity) getActivity()).samples; - break; - default: - break; - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - seekBarTimebase.setProgress(0); - } - seekBarTrigger.setters(-1 * ((OscilloscopeActivity) getActivity()).yAxisScale, ((OscilloscopeActivity) getActivity()).yAxisScale); - seekBarTrigger.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (!_ignore) { - editTextTrigger.setText(String.format("%s V", seekBarTrigger.getValue())); - ((OscilloscopeActivity) getActivity()).trigger = seekBarTrigger.getValue(); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - seekBarTrigger.setProgress(50); - - String[] channels = {"CH1", "CH2", "CH3", "MIC"}; - ArrayAdapter channelsAdapter; - if (tabletSize) { - channelsAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner_tablet, channels); - } else { - channelsAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner, channels); - } - - channelsAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); - - spinnerTriggerChannelSelect.setAdapter(channelsAdapter); - spinnerTriggerChannelSelect.setSelection(channelsAdapter.getPosition("CH1"), true); - spinnerTriggerChannelSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - ((OscilloscopeActivity) getActivity()).triggerChannel = spinnerTriggerChannelSelect.getItemAtPosition(position).toString(); - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - String[] modes = {"Rising Edge", "Falling Edge", "Dual Edge"}; - ArrayAdapter modesAdapter; - if (tabletSize) { - modesAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner_tablet, modes); - } else { - modesAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner, modes); - } - - modesAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); - - spinnerTriggerModeSelect.setAdapter(modesAdapter); - spinnerTriggerModeSelect.setSelection(modesAdapter.getPosition("Rising Edge"), true); - ((OscilloscopeActivity) getActivity()).triggerMode = "RISING"; - spinnerTriggerModeSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - switch (spinnerTriggerModeSelect.getItemAtPosition(position).toString()) { - case "Rising Edge": - ((OscilloscopeActivity) getActivity()).triggerMode = "RISING"; - break; - case "Falling Edge": - ((OscilloscopeActivity) getActivity()).triggerMode = "FALLING"; - break; - case "Dual Edge": - ((OscilloscopeActivity) getActivity()).triggerMode = "DUAL"; - break; - default: - break; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - // Do nothing - } - }); - - editTextTrigger.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - editTextTrigger.setCursorVisible(true); - return false; - } - }); - - editTextTrigger.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_DONE) { - String voltageValue = editTextTrigger.getText().toString().replace("V", ""); - voltageValue = voltageValue.replace(" ", ""); - if (NumberUtils.isCreatable(voltageValue)) { - _ignore = true; - if (Double.parseDouble(voltageValue) > ((OscilloscopeActivity) getActivity()).yAxisScale) { - editTextTrigger.setText(String.format("%s V", ((OscilloscopeActivity) getActivity()).yAxisScale)); - seekBarTrigger.setValue(((OscilloscopeActivity) getActivity()).yAxisScale); - ((OscilloscopeActivity) getActivity()).trigger = seekBarTrigger.getValue(); - _ignore = false; - } else if (Double.parseDouble(voltageValue) < -((OscilloscopeActivity) getActivity()).yAxisScale) { - editTextTrigger.setText(String.format("%s V", -((OscilloscopeActivity) getActivity()).yAxisScale)); - seekBarTrigger.setValue(-((OscilloscopeActivity) getActivity()).yAxisScale); - ((OscilloscopeActivity) getActivity()).trigger = seekBarTrigger.getValue(); - _ignore = false; - } else { - seekBarTrigger.setValue(Double.parseDouble(voltageValue)); - editTextTrigger.setText(String.format("%s V", Double.parseDouble(voltageValue))); - ((OscilloscopeActivity) getActivity()).trigger = seekBarTrigger.getValue(); - _ignore = false; - } - } else { - seekBarTrigger.setProgress(50); - } - } - editTextTrigger.setCursorVisible(false); - return false; - } - }); - - checkBoxTrigger.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - ((OscilloscopeActivity) getActivity()).isTriggerSelected = isChecked; - } - }); - - return v; - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/fragment/XYPlotFragment.java b/app/src/main/java/io/pslab/fragment/XYPlotFragment.java deleted file mode 100644 index 3383d92f3..000000000 --- a/app/src/main/java/io/pslab/fragment/XYPlotFragment.java +++ /dev/null @@ -1,115 +0,0 @@ -package io.pslab.fragment; - -import android.os.Bundle; -import androidx.fragment.app.Fragment; - -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import io.pslab.R; -import io.pslab.activity.OscilloscopeActivity; -import io.pslab.others.ViewGroupUtils; - -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.Spinner; - -public class XYPlotFragment extends Fragment { - - private Spinner spinnerChannelSelect1; - private Spinner spinnerChannelSelect2; - private CheckBox checkBoxXYPlot; - - public static XYPlotFragment newInstance() { - return new XYPlotFragment(); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View v = inflater.inflate(R.layout.fragment_xyplot, container, false); - final String[] channels = {"CH1", "CH2", "CH3", "MIC"}; - spinnerChannelSelect1 = v.findViewById(R.id.spinner_channel_select_xy1); - spinnerChannelSelect2 = v.findViewById(R.id.spinner_channel_select_xy2); - checkBoxXYPlot = v.findViewById(R.id.checkBox_enable_xy_xy); - spinnerChannelSelect1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView adapterView, View view, int position, long l) { - ((OscilloscopeActivity) getActivity()).xyPlotAxis1 = channels[position]; - if (((OscilloscopeActivity) getActivity()).isXYPlotSelected) { - ((OscilloscopeActivity) getActivity()).setXAxisLabel(channels[position]); - ((OscilloscopeActivity) getActivity()).xAxisLabelUnit.setText("(V)"); - } - - } - - @Override - public void onNothingSelected(AdapterView adapterView) { - - } - }); - spinnerChannelSelect2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView adapterView, View view, int position, long l) { - ((OscilloscopeActivity) getActivity()).xyPlotAxis2 = channels[position]; - if (((OscilloscopeActivity) getActivity()).isXYPlotSelected) { - ((OscilloscopeActivity) getActivity()).setLeftYAxisLabel(channels[position]); - } - } - - @Override - public void onNothingSelected(AdapterView adapterView) { - - } - }); - boolean tabletSize = getResources().getBoolean(R.bool.isTablet); - ArrayAdapter channelsAdapter; - - if (tabletSize) { - channelsAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner_tablet, channels); - } else { - channelsAdapter = new ArrayAdapter<>(this.getActivity(), R.layout.custom_spinner, channels); - } - - channelsAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); - - spinnerChannelSelect1.setAdapter(channelsAdapter); - spinnerChannelSelect2.setAdapter(channelsAdapter); - - spinnerChannelSelect1.setSelection(channelsAdapter.getPosition("CH1"), true); - spinnerChannelSelect2.setSelection(channelsAdapter.getPosition("CH2"), true); - - checkBoxXYPlot.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - ((OscilloscopeActivity) getActivity()).isXYPlotSelected = isChecked; - if (isChecked) { - ViewGroupUtils.replaceView(((OscilloscopeActivity) getActivity()).mChart, - ((OscilloscopeActivity) getActivity()).graph); - ((OscilloscopeActivity) getActivity()).setXAxisLabel(spinnerChannelSelect1.getSelectedItem().toString()); - ((OscilloscopeActivity) getActivity()).setLeftYAxisLabel(spinnerChannelSelect2.getSelectedItem().toString()); - ((OscilloscopeActivity) getActivity()).xAxisLabelUnit.setText("(V)"); - ((OscilloscopeActivity) getActivity()).rightYAxisLabel.setVisibility(View.INVISIBLE); - ((OscilloscopeActivity) getActivity()).rightYAxisLabelUnit.setVisibility(View.INVISIBLE); - - - } else { - ViewGroupUtils.replaceView(((OscilloscopeActivity) getActivity()).graph, - ((OscilloscopeActivity) getActivity()).mChart); - ((OscilloscopeActivity) getActivity()).rightYAxisLabel.setVisibility(View.VISIBLE); - ((OscilloscopeActivity) getActivity()).rightYAxisLabelUnit.setVisibility(View.VISIBLE); - ((OscilloscopeActivity) getActivity()).setXAxisLabel("time"); - ((OscilloscopeActivity) getActivity()).setXAxisScale(((OscilloscopeActivity) getActivity()).timebase); - - } - - } - }); - - return v; - } -} diff --git a/app/src/main/java/io/pslab/interfaces/HttpCallback.java b/app/src/main/java/io/pslab/interfaces/HttpCallback.java deleted file mode 100644 index 3bcdd62e8..000000000 --- a/app/src/main/java/io/pslab/interfaces/HttpCallback.java +++ /dev/null @@ -1,6 +0,0 @@ -package io.pslab.interfaces; - -public interface HttpCallback { - void success(T t1); - void error(Exception e); -} diff --git a/app/src/main/java/io/pslab/interfaces/OperationCallback.java b/app/src/main/java/io/pslab/interfaces/OperationCallback.java deleted file mode 100644 index b9f584425..000000000 --- a/app/src/main/java/io/pslab/interfaces/OperationCallback.java +++ /dev/null @@ -1,10 +0,0 @@ -package io.pslab.interfaces; - -/** - * created by VIKAS9899 on 14/05/2020 - */ -public interface OperationCallback { - void playData(); - void stopData(); - void saveGraph(); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/AccelerometerRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/AccelerometerRecordables.java deleted file mode 100644 index e1043368e..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/AccelerometerRecordables.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.AccelerometerData; -import io.realm.RealmResults; - -public interface AccelerometerRecordables { - - AccelerometerData getAccelerometerData(long timeStamp); - - void clearAllAccelerometerRecords(); - - void clearBlockOfAccelerometerRecords(long block); - - RealmResults getAllAccelerometerRecords(); - - RealmResults getBlockOfAccelerometerRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/BaroMeterRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/BaroMeterRecordables.java deleted file mode 100644 index d8ced963c..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/BaroMeterRecordables.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.BaroData; -import io.realm.RealmResults; - -/** - * Created by Padmal on 12/13/18. - */ - -public interface BaroMeterRecordables { - - BaroData getBaroData(long timeStamp); - - void clearAllBaroRecords(); - - void clearBlockOfBaroRecords(long block); - - RealmResults getAllBaroRecords(); - - RealmResults getBlockOfBaroRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/CompassRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/CompassRecordables.java deleted file mode 100644 index a99dfedfb..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/CompassRecordables.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.CompassData; -import io.realm.RealmResults; - -public interface CompassRecordables { - CompassData getCompassData(long timeStamp); - - void clearAllCompassRecords(); - - void clearBlockOfCompassRecords(long block); - - RealmResults getAllCompassRecords(); - - RealmResults getBlockOfCompassRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/DustSensorRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/DustSensorRecordables.java deleted file mode 100644 index d4bbbe4c5..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/DustSensorRecordables.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.DustSensorData; -import io.realm.RealmResults; - -public interface DustSensorRecordables { - - DustSensorData getDustSensorData(long timeStamp); - void clearAllDustSensorRecords(); - void clearBlockOfDustSensorRecords(long block); - RealmResults getAllDustSensorRecords(); - RealmResults getBlockOfDustSensorRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/GasSensorRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/GasSensorRecordables.java deleted file mode 100644 index 5ceb00a89..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/GasSensorRecordables.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.GasSensorData; -import io.realm.RealmResults; - -public interface GasSensorRecordables { - GasSensorData getGasSensorData(long timeStamp); - void clearAllGasSensorRecords(); - void clearBlockOfGasSensorRecords(long block); - RealmResults getAllGasSensorRecords(); - RealmResults getBlockOfGasSensorRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/GyroscopeRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/GyroscopeRecordables.java deleted file mode 100644 index 578243e9d..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/GyroscopeRecordables.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.GyroData; -import io.realm.RealmResults; - -public interface GyroscopeRecordables { - GyroData getGyroData(long timeStamp); - - void clearAllGyroRecords(); - - void clearBlockOfGyroRecords(long block); - - RealmResults getAllGyroRecords(); - - RealmResults getBlockOfGyroRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/LogicAnalyzerRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/LogicAnalyzerRecordables.java deleted file mode 100644 index 266e68af1..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/LogicAnalyzerRecordables.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.LogicAnalyzerData; -import io.realm.RealmResults; - -public interface LogicAnalyzerRecordables { - LogicAnalyzerData getLAData(long timeStamp); - void clearAllLARecords(); - void clearBlockOfLARecords(long block); - RealmResults getAllLARecords(); - RealmResults getBlockOfLARecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/LuxMeterRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/LuxMeterRecordables.java deleted file mode 100644 index bfa0c9249..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/LuxMeterRecordables.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.LuxData; -import io.realm.RealmResults; - -/** - * Created by Padmal on 11/5/18. - */ - -public interface LuxMeterRecordables { - - LuxData getLuxData(long timeStamp); - - void clearAllLuxRecords(); - - void clearBlockOfLuxRecords(long block); - - RealmResults getAllLuxRecords(); - - RealmResults getBlockOfLuxRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/MultimeterRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/MultimeterRecordables.java deleted file mode 100644 index 0b859db4c..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/MultimeterRecordables.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.MultimeterData; -import io.realm.RealmResults; - -public interface MultimeterRecordables { - MultimeterData getMultimeterData(long timeStamp); - void clearAllMultimeterRecords(); - void clearBlockOfMultimeterRecords(long block); - RealmResults getAllMultimeterRecords(); - RealmResults getBlockOfMultimeterRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/OscilloscopeRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/OscilloscopeRecordables.java deleted file mode 100644 index c68f14632..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/OscilloscopeRecordables.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.OscilloscopeData; -import io.realm.RealmResults; - -public interface OscilloscopeRecordables { - OscilloscopeData getOscilloscopeData(long timeStamp); - - void clearAllOscilloscopeRecords(); - - void clearBlockOfOscilloscopeRecords(long block); - - RealmResults getAllOscilloscopeRecords(); - - RealmResults getBlockOfOscilloscopeRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/PowerSourceRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/PowerSourceRecordables.java deleted file mode 100644 index d912e52d3..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/PowerSourceRecordables.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.PowerSourceData; -import io.realm.RealmResults; - -public interface PowerSourceRecordables { - PowerSourceData getPowerData(long timeStamp); - void clearAllPowerRecords(); - void clearBlockOfPowerRecords(long block); - RealmResults getAllPowerRecords(); - RealmResults getBlockOfPowerRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/SensorRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/SensorRecordables.java deleted file mode 100644 index 93e8019e2..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/SensorRecordables.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.SensorDataBlock; -import io.realm.RealmResults; - -/** - * Created by Padmal on 11/5/18. - */ - -public interface SensorRecordables { - - SensorDataBlock getSensorBlock(long block); - - void clearAllSensorBlocks(); - - void clearTypeOfSensorBlock(String type); - - void clearSensorBlock(long block); - - RealmResults getAllSensorBlocks(); - - RealmResults getTypeOfSensorBlocks(String type); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/ServoRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/ServoRecordables.java deleted file mode 100644 index 7ce53c65b..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/ServoRecordables.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.ServoData; -import io.realm.RealmResults; - -public interface ServoRecordables { - ServoData getServoData(long timeStamp); - - void clearAllServoRecords(); - - void clearBlockOfServoRecords(long block); - - RealmResults getAllServoRecords(); - - RealmResults getBlockOfServoRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/SoundMeterRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/SoundMeterRecordables.java deleted file mode 100644 index 2748c7168..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/SoundMeterRecordables.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.SoundData; -import io.realm.RealmResults; - -/** - * @author reckoner1429 - * - */ -public interface SoundMeterRecordables { - - SoundData getSoundMeterData(long timeStamp); - - void clearAllSoundRecords(); - - void clearBlockOfSoundRecords(long block); - - RealmResults getAllSoundRecords(); - - RealmResults getBlockOfSoundRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/ThermometerRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/ThermometerRecordables.java deleted file mode 100644 index 5a8a2c85b..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/ThermometerRecordables.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.ThermometerData; -import io.realm.RealmResults; - -public interface ThermometerRecordables { - ThermometerData getThermometerData(long timeStamp); - - void clearAllThermometerRecords(); - - void clearBlockOfThermometerRecords(long block); - - RealmResults getAllThermometerRecords(); - - RealmResults getBlockOfThermometerRecords(long block); -} diff --git a/app/src/main/java/io/pslab/interfaces/sensorloggers/WaveGeneratorRecordables.java b/app/src/main/java/io/pslab/interfaces/sensorloggers/WaveGeneratorRecordables.java deleted file mode 100644 index 5458b9c41..000000000 --- a/app/src/main/java/io/pslab/interfaces/sensorloggers/WaveGeneratorRecordables.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.pslab.interfaces.sensorloggers; - -import io.pslab.models.WaveGeneratorData; -import io.realm.RealmResults; - -public interface WaveGeneratorRecordables { - WaveGeneratorData getWaveData(long timeStamp); - - void clearAllWaveRecords(); - - void clearBlockOfWaveRecords(long block); - - RealmResults getAllWaveRecords(); - - RealmResults getBlockOfWaveRecords(long block); -} diff --git a/app/src/main/java/io/pslab/items/ApplicationItem.java b/app/src/main/java/io/pslab/items/ApplicationItem.java deleted file mode 100644 index 0bf19666b..000000000 --- a/app/src/main/java/io/pslab/items/ApplicationItem.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.pslab.items; - -/** - * Created by Padmal on 5/7/17. - */ - -public class ApplicationItem { - - private String applicationName; - private int applicationIcon; - private String applicationDescription; - - public ApplicationItem() {} - - public ApplicationItem(String applicationName, int applicationIcon, String applicationDescription) { - this.applicationName = applicationName; - this.applicationDescription = applicationDescription; - this.applicationIcon = applicationIcon; - } - - public String getApplicationName() { - return applicationName; - } - - public String getApplicationDescription(){ return applicationDescription; } - - public int getApplicationIcon() { - return applicationIcon; - } - - public void setApplicationName(String applicationName) { - this.applicationName = applicationName; - } - - public void setApplicationDescription(String applicationDescription){ - this.applicationDescription = applicationDescription; - } - - public void setApplicationIcon(int applicationIcon) { - this.applicationIcon = applicationIcon; - } - -} diff --git a/app/src/main/java/io/pslab/items/PinDetails.java b/app/src/main/java/io/pslab/items/PinDetails.java deleted file mode 100644 index c5029fc74..000000000 --- a/app/src/main/java/io/pslab/items/PinDetails.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.pslab.items; - -/** - * Created by Padmal on 5/22/18. - */ - -public class PinDetails { - - private final String name; - private final String description; - private final int categoryColor; - private final int colorID; - - public PinDetails(String name, String description, int categoryColor, int colorID) { - this.name = name; - this.description = description; - this.categoryColor = categoryColor; - this.colorID = colorID; - } - - public String getName() { - return name; - } - - public String getDescription() { - return description; - } - - public int getCategoryColor() { - return categoryColor; - } - - public int getColorID() { - return colorID; - } -} diff --git a/app/src/main/java/io/pslab/items/SquareImageButton.java b/app/src/main/java/io/pslab/items/SquareImageButton.java deleted file mode 100644 index 399ead486..000000000 --- a/app/src/main/java/io/pslab/items/SquareImageButton.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.pslab.items; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.util.AttributeSet; -import android.widget.ImageButton; - -@SuppressLint("AppCompatCustomView") -public class SquareImageButton extends ImageButton { - - public SquareImageButton(Context context) { - super(context); - } - - public SquareImageButton(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public SquareImageButton(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - - int width = getMeasuredWidth(); - setMeasuredDimension(width, width); - } - - @Override - public boolean performClick() { - return super.performClick(); - } -} diff --git a/app/src/main/java/io/pslab/items/SquareLinearLayout.java b/app/src/main/java/io/pslab/items/SquareLinearLayout.java deleted file mode 100644 index b03f087d7..000000000 --- a/app/src/main/java/io/pslab/items/SquareLinearLayout.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.pslab.items; - -import android.content.Context; -import androidx.annotation.Nullable; -import android.util.AttributeSet; -import android.widget.LinearLayout; - -/** - * Created by Your name on 25-07-2018. - */ -public class SquareLinearLayout extends LinearLayout { - public SquareLinearLayout(Context context) { - super(context); - } - - public SquareLinearLayout(Context context, @Nullable AttributeSet attrs) { - super(context, attrs); - } - - public SquareLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - - int width = getMeasuredWidth(); - setMeasuredDimension(width, width); - } -} diff --git a/app/src/main/java/io/pslab/models/AccelerometerData.java b/app/src/main/java/io/pslab/models/AccelerometerData.java deleted file mode 100644 index 9320cbcc0..000000000 --- a/app/src/main/java/io/pslab/models/AccelerometerData.java +++ /dev/null @@ -1,96 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -/** - * Created by Kunal on 18-12-2018. - */ - -public class AccelerometerData extends RealmObject { - - @PrimaryKey - private long time; - private long block; - private float accelerometerX; - private float accelerometerY; - private float accelerometerZ; - private double lat, lon; - - public AccelerometerData() {/**/} - - public AccelerometerData(long time, long block, float accelerometerX, float accelerometerY, float accelerometerZ, double lat, double lon) { - this.time = time; - this.block = block; - this.accelerometerX = accelerometerX; - this.accelerometerY = accelerometerY; - this.accelerometerZ = accelerometerZ; - this.lat = lat; - this.lon = lon; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public float getAccelerometerX() { - return accelerometerX; - } - - public void setAccelerometerX(float accelerometerX) { - this.accelerometerX = accelerometerX; - } - - public float getAccelerometerY() { - return accelerometerY; - } - - public void setAccelerometerY(float accelerometerY) { - this.accelerometerY = accelerometerY; - } - - public float getAccelerometerZ() { - return accelerometerZ; - } - - public void setAccelerometerZ(float accelerometerZ) { - this.accelerometerZ = accelerometerZ; - } - - public float[] getAccelerometer() { - return new float[]{this.accelerometerX, this.accelerometerY, this.accelerometerZ}; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", Accelerometer_X - " + accelerometerX + ", Accelerometer_Y - " + accelerometerY + ", Accelerometer_Z - " + accelerometerZ + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/BaroData.java b/app/src/main/java/io/pslab/models/BaroData.java deleted file mode 100644 index d8b5e69a1..000000000 --- a/app/src/main/java/io/pslab/models/BaroData.java +++ /dev/null @@ -1,82 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -/** - * Created by Padmal on 12/13/18. - */ - -public class BaroData extends RealmObject { - - @PrimaryKey - private long time; - private long block; - private float baro; - private float altitude; - private double lat, lon; - - public BaroData() {/**/} - - public BaroData(long time, long block, float baro, float altitude, double lat, double lon) { - this.time = time; - this.block = block; - this.baro = baro; - this.altitude = altitude; - this.lat = lat; - this.lon = lon; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public float getBaro() { - return baro; - } - - public void setBaro(float baro) { - this.baro = baro; - } - - public float getAltitude() { - return altitude; - } - - public void setAltitude(float altitude) { - this.altitude = altitude; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", Baro - " + baro + ", Altitude - " + altitude + ", Lat - " + lat + ", Lon - " + lon; - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/models/CompassData.java b/app/src/main/java/io/pslab/models/CompassData.java deleted file mode 100644 index eb41bf592..000000000 --- a/app/src/main/java/io/pslab/models/CompassData.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; - -public class CompassData extends RealmObject { - private Float Bx; - private Float By; - private Float Bz; - private String Axis = "X-axis"; - private long time; - private long block; - private double lat,lon; - - public CompassData() {/**/} - - public CompassData(long time, long block, float Bx, float By, float Bz, String axis, double lat, double lon) { - this.Bx = Bx; - this.By = By; - this.Bz = Bz; - this.time = time; - this.block = block; - this.lat = lat; - this.lon = lon; - this.Axis = axis; - } - - public Float getBx() { - return Bx; - } - - public void setBx(Float Bx) { - this.Bx = Bx; - } - - public Float getBy() { - return By; - } - - public void setBy(Float By) { - this.By = By; - } - - public Float getBz() { - return Bz; - } - - public void setBz(Float Bz) { - this.Bz = Bz; - } - - public void setAxis(String axis) { - Axis = axis; - } - - public String getAxis() { - return Axis; - } - - public void setBlock(long block) { - this.block = block; - } - - public long getBlock() { - return block; - } - - public void setTime(long time) { - this.time = time; - } - - public long getTime() { - return time; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLat() { - return lat; - } - - public void setLon(double lon) { - this.lon = lon; - } - - public double getLon() { - return lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", Compass_X - " + Bx + ", Compass_Y - " + By + ", Compass_Z - " + Bz + ", Compass_axis" + Axis + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/DataMPU6050.java b/app/src/main/java/io/pslab/models/DataMPU6050.java deleted file mode 100644 index f37051fd8..000000000 --- a/app/src/main/java/io/pslab/models/DataMPU6050.java +++ /dev/null @@ -1,102 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; - -/** - * Created by viveksb007 on 4/8/17. - */ - -public class DataMPU6050 extends RealmObject { - - private long trial; - private long id; - private double ax, ay, az; - private double gx, gy, gz; - private double temperature; - - public DataMPU6050() { - - } - - public DataMPU6050(double ax, double ay, double az, double gx, double gy, double gz, double temperature) { - this.ax = ax; - this.ay = ay; - this.az = az; - this.gx = gx; - this.gy = gy; - this.gz = gz; - this.temperature = temperature; - } - - public double getAx() { - return ax; - } - - public void setAx(double ax) { - this.ax = ax; - } - - public double getAy() { - return ay; - } - - public void setAy(double ay) { - this.ay = ay; - } - - public double getAz() { - return az; - } - - public void setAz(double az) { - this.az = az; - } - - public double getGx() { - return gx; - } - - public void setGx(double gx) { - this.gx = gx; - } - - public double getGy() { - return gy; - } - - public void setGy(double gy) { - this.gy = gy; - } - - public double getGz() { - return gz; - } - - public void setGz(double gz) { - this.gz = gz; - } - - public double getTemperature() { - return temperature; - } - - public void setTemperature(double temperature) { - this.temperature = temperature; - } - - public long getTrial() { - return trial; - } - - public void setTrial(long trial) { - this.trial = trial; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } -} diff --git a/app/src/main/java/io/pslab/models/DustSensorData.java b/app/src/main/java/io/pslab/models/DustSensorData.java deleted file mode 100644 index b337d8b52..000000000 --- a/app/src/main/java/io/pslab/models/DustSensorData.java +++ /dev/null @@ -1,68 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -public class DustSensorData extends RealmObject { - - @PrimaryKey - private long time; - private long block; - private float ppmValue; - private double lat, lon; - - public DustSensorData() { /**/ } - - public DustSensorData(long time, long block, float ppmValue, double lat, double lon) { - this.time = time; - this.block = block; - this.ppmValue = ppmValue; - this.lat = lat; - this.lon = lon; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public float getPpmValue() { - return ppmValue; - } - - public void setPpmValue(float ppmValue) { - this.ppmValue = ppmValue; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", PPM value - " + ppmValue + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/GasSensorData.java b/app/src/main/java/io/pslab/models/GasSensorData.java deleted file mode 100644 index 7613d23ce..000000000 --- a/app/src/main/java/io/pslab/models/GasSensorData.java +++ /dev/null @@ -1,68 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -public class GasSensorData extends RealmObject { - - @PrimaryKey - private long time; - private long block; - private float ppmValue; - private double lat, lon; - - public GasSensorData() {/**/} - - public GasSensorData(long time, long block, float ppmValue, double lat, double lon) { - this.time = time; - this.block = block; - this.ppmValue = ppmValue; - this.lat = lat; - this.lon = lon; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public float getPpmValue() { - return ppmValue; - } - - public void setPpmValue(float ppmValue) { - this.ppmValue = ppmValue; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", PPM value - " + ppmValue + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/GyroData.java b/app/src/main/java/io/pslab/models/GyroData.java deleted file mode 100644 index e76d43274..000000000 --- a/app/src/main/java/io/pslab/models/GyroData.java +++ /dev/null @@ -1,91 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -public class GyroData extends RealmObject { - - @PrimaryKey - private long time; - private long block; - private float gyro_x; - private float gyro_y; - private float gyro_z; - private double lat, lon; - - public GyroData() {/**/} - - public GyroData(long time, long block, float gyro_x, float gyro_y, float gyro_z, double lat, double lon) { - this.time = time; - this.block = block; - this.gyro_x = gyro_x; - this.gyro_y = gyro_y; - this.gyro_z = gyro_z; - this.lat = lat; - this.lon = lon; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public float getGyroX() { - return gyro_x; - } - - public void setGyroX(float gyro_x) { - this.gyro_x = gyro_x; - } - - public float getGyroY() { - return gyro_y; - } - - public void setGyroY(float gyro_y) { - this.gyro_y = gyro_y; - } - - public float getGyroZ() { - return gyro_z; - } - - public void setGyroZ(float gyro_z) { - this.gyro_z = gyro_z; - } - - public float[] getGyro(){ - return new float[]{this.gyro_x, this.gyro_y, this.gyro_z}; - } - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", Gyroscope_X - " + gyro_x + ", Gyroscope_Y - " + gyro_y + ", Gyroscope_Y - " + gyro_z + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/LogicAnalyzerData.java b/app/src/main/java/io/pslab/models/LogicAnalyzerData.java deleted file mode 100644 index 7f00bdf11..000000000 --- a/app/src/main/java/io/pslab/models/LogicAnalyzerData.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -public class LogicAnalyzerData extends RealmObject { - @PrimaryKey - private long time; - private long block; - private String dataX, dataY, channel; - private double lat, lon; - private int channelMode; - - public LogicAnalyzerData() {/**/} - - public LogicAnalyzerData(long time, long block, String channel, int channelMode, String dataX, String dataY, double lat, double lon) { - this.time = time; - this.block = block; - this.channel = channel; - this.channelMode = channelMode; - this.dataX = dataX; - this.dataY = dataY; - this.lat = lat; - this.lon = lon; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public String getChannel() { - return channel; - } - - public void setChannel(String channel) { - this.channel = channel; - } - - public int getChannelMode() { - return channelMode; - } - - public void setChannelMode(int channelMode) { - this.channelMode = channelMode; - } - - public String getDataY() { - return dataY; - } - - public void setDataY(String dataY) { - this.dataY = dataY; - } - - public String getDataX() { - return dataX; - } - - public void setDataX(String dataX) { - this.dataX = dataX; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", Channel - " + channel + ", ChannelMode - " + channelMode + ", dataX - " + dataX + ", dataY - " + dataY + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/LuxData.java b/app/src/main/java/io/pslab/models/LuxData.java deleted file mode 100644 index a596c5898..000000000 --- a/app/src/main/java/io/pslab/models/LuxData.java +++ /dev/null @@ -1,72 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -/** - * Created by Avjeet on 31-07-2018. - */ - -public class LuxData extends RealmObject { - - @PrimaryKey - private long time; - private long block; - private float lux; - private double lat, lon; - - public LuxData() {/**/} - - public LuxData(long time, long block, float lux, double lat, double lon) { - this.time = time; - this.block = block; - this.lux = lux; - this.lat = lat; - this.lon = lon; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public float getLux() { - return lux; - } - - public void setLux(float lux) { - this.lux = lux; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", Lux - " + lux + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/MultimeterData.java b/app/src/main/java/io/pslab/models/MultimeterData.java deleted file mode 100644 index f5c51b0a0..000000000 --- a/app/src/main/java/io/pslab/models/MultimeterData.java +++ /dev/null @@ -1,78 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -public class MultimeterData extends RealmObject { - @PrimaryKey - private long time; - private long block; - private String data; - private String value; - private double lat; - private double lon; - - public MultimeterData() {/**/} - - public MultimeterData(long time, long block, String data, String value, double lat, double lon) { - this.time = time; - this.block = block; - this.data = data; - this.value = value; - this.lat = lat; - this.lon = lon; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", Data - " + data + ", Value - " + value + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/OscilloscopeData.java b/app/src/main/java/io/pslab/models/OscilloscopeData.java deleted file mode 100644 index 74b835636..000000000 --- a/app/src/main/java/io/pslab/models/OscilloscopeData.java +++ /dev/null @@ -1,105 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -public class OscilloscopeData extends RealmObject { - - @PrimaryKey - private long time; - private long block; - private String dataX, dataY, channel; - private double lat, lon, timebase; - private int mode; - - public OscilloscopeData() {/**/} - - public OscilloscopeData(long time, long block, int mode, String channel, String dataX, String dataY, double timebase, double lat, double lon) { - this.time = time; - this.block = block; - this.mode = mode; - this.channel = channel; - this.dataX = dataX; - this.dataY = dataY; - this.timebase = timebase; - this.lat = lat; - this.lon = lon; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public String getDataX() { - return dataX; - } - - public void setDataX(String dataX) { - this.dataX = dataX; - } - - public String getChannel() { - return channel; - } - - public void setChannel(String channel) { - this.channel = channel; - } - - public int getMode() { - return mode; - } - - public void setMode(int mode) { - this.mode = mode; - } - - public String getDataY() { - return dataY; - } - - public void setDataY(String dataY) { - this.dataY = dataY; - } - - public double getTimebase() { - return timebase; - } - - public void setTimebase(double timebase) { - this.timebase = timebase; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", Channel - " + channel + ", Mode - " + mode + ", dataX - " + dataX + ", dataY - " + dataY + ", timebase - " + timebase + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/PSLabSensor.java b/app/src/main/java/io/pslab/models/PSLabSensor.java deleted file mode 100644 index c1cf246b3..000000000 --- a/app/src/main/java/io/pslab/models/PSLabSensor.java +++ /dev/null @@ -1,535 +0,0 @@ -package io.pslab.models; - -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.pm.PackageManager; -import android.location.LocationManager; -import android.os.Bundle; -import android.os.Environment; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.widget.Toolbar; -import androidx.coordinatorlayout.widget.CoordinatorLayout; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentTransaction; - -import com.google.android.material.snackbar.Snackbar; - -import org.json.JSONArray; - -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Locale; - -import butterknife.BindView; -import butterknife.ButterKnife; -import io.pslab.R; -import io.pslab.activity.DataLoggerActivity; -import io.pslab.activity.MapsActivity; -import io.pslab.activity.SettingsActivity; -import io.pslab.activity.guide.GuideActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.fragment.SoundMeterDataFragment; -import io.pslab.interfaces.OperationCallback; -import io.pslab.others.CSVLogger; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.GPSLogger; -import io.pslab.others.LocalDataLog; -import io.pslab.others.PSLabPermission; -import io.pslab.others.ScienceLabCommon; -import io.realm.Realm; -import io.realm.RealmObject; - -public abstract class PSLabSensor extends GuideActivity { - - public boolean isRecording = false; - public boolean locationEnabled = true; - public boolean addLocation = true; - public boolean checkGPSOnResume = false; - public boolean writeHeaderToFile = true; - public boolean playingData = false; - public boolean viewingData = false; - public boolean startedPlay = false; - - public CoordinatorLayout sensorParentView; - public ScienceLab scienceLab; - - public JSONArray markers; - - public Fragment sensorFragment; - public PSLabPermission psLabPermission; - public GPSLogger gpsLogger; - public CSVLogger csvLogger; - public Realm realm; - private Intent map; - - public SimpleDateFormat titleFormat; - public final String KEY_LOG = "has_log"; - public final String DATA_BLOCK = "data_block"; - - public static final String LUXMETER = "Lux Meter"; - public static final String LUXMETER_CONFIGURATIONS = "Lux Meter Configurations"; - public static final String LUXMETER_DATA_FORMAT = "%.2f"; - public static final String BAROMETER = "Barometer"; - public static final String BAROMETER_CONFIGURATIONS = "Barometer Configurations"; - public static final String BAROMETER_DATA_FORMAT = "%.2f"; - public static final String GYROSCOPE = "Gyroscope"; - public static final String GYROSCOPE_DATA_FORMAT = "%.2f"; - public static final String GYROSCOPE_CONFIGURATIONS = "Gyroscope Configurations"; - public static final String COMPASS = "Compass"; - public static final String COMPASS_CONFIGURATIONS = "Compass Configurations"; - public static final String ACCELEROMETER = "Accelerometer"; - public static final String ACCELEROMETER_CONFIGURATIONS = "Accelerometer Configurations"; - public static final String THERMOMETER = "Thermometer"; - public static final String THERMOMETER_CONFIGURATIONS = "Thermometer Configurations"; - public static final String THERMOMETER_DATA_FORMAT = "%.2f"; - public static final String DUSTSENSOR_CONFIGURATIONS = "Dust Sensor Configurations"; - public static final String ROBOTIC_ARM = "Robotic Arm"; - public static final String WAVE_GENERATOR = "Wave Generator"; - public static final String OSCILLOSCOPE = "Oscilloscope"; - public static final String POWER_SOURCE = "Power Source"; - public static final String MULTIMETER = "Multimeter"; - public static final String LOGIC_ANALYZER = "Logic Analyzer"; - public static final String GAS_SENSOR = "Gas Sensor"; - public static final String SOUND_METER = "Sound Meter"; - public static final String SOUNDMETER_CONFIGURATIONS = "Sound Meter Configurations"; - public static final String SOUNDMETER_DATA_FORMAT = "%.2f"; - - @BindView(R.id.sensor_toolbar) - Toolbar sensorToolBar; - @BindView(R.id.sensor_cl) - CoordinatorLayout coordinatorLayout; - - @BindView(R.id.guide_title) - TextView bottomSheetGuideTitle; - @BindView(R.id.custom_dialog_text) - TextView bottomSheetText; - @BindView(R.id.custom_dialog_schematic) - ImageView bottomSheetSchematic; - @BindView(R.id.custom_dialog_desc) - TextView bottomSheetDesc; - @BindView(R.id.custom_dialog_additional_content) - LinearLayout bottomSheetAdditionalContent; - - public PSLabSensor() { - super(R.layout.activity_generic_sensor); - } - - /** - * Getting menu layout distinct to each sensor - * - * @return Menu resource file in 'R.menu.id' format - */ - public abstract int getMenu(); - - /** - * Getting saved setting configurations for dialogs - * - * @return SharedPreferences in Private mode - */ - public abstract SharedPreferences getStateSettings(); - - /** - * Getting ID to fetch first time usage of each sensor - * - * @return String ID of the first time usage ID of sensor - */ - public abstract String getFirstTimeSettingID(); - - /** - * Sensor ID - * - * @return String ID of the sensor - */ - public abstract String getSensorName(); - - /** - * Title of the sensor guide - * - * @return Sensor name as a String resource - */ - public abstract int getGuideTitle(); - - /** - * Abstract of the sensor guide - * - * @return Sensor abstract as a String resource - */ - public abstract int getGuideAbstract(); - - /** - * Circuit diagrams and pin settings for the sensor - * - * @return Schematics as a drawable resource - */ - public abstract int getGuideSchematics(); - - /** - * Description of the sensor guide - * - * @return Sensor guide description as a String resource - */ - public abstract int getGuideDescription(); - - /** - * Extra content for a specific sensor if it is not a generic one - * - * @return Layout id of the content file - */ - public abstract int getGuideExtraContent(); - - /** - * This method will create a new entry in Realm database with a new block - * - * @param block Start timestamp of the recording - */ - public abstract void recordSensorDataBlockID(SensorDataBlock block); - - /** - * This method will be called upon when menu button for recording data has been clicked - */ - public abstract void recordSensorData(RealmObject sensorData); - - /** - * This method will be called upon when menu button for stop recording data has been clicked - */ - public abstract void stopRecordSensorData(); - - /** - * Fragment implementation of each individual sensor - * - * @return Custom fragment instance of the sensor - */ - public abstract Fragment getSensorFragment(); - - /** - * This method will fetch logged data information from the data logger activity - */ - public abstract void getDataFromDataLogger(); - - /** - * This method will check whether the device has in-built sensor or not - **/ - public abstract boolean sensorFound(); - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ButterKnife.bind(this); - setSupportActionBar(sensorToolBar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(getSensorName()); - actionBar.setDisplayHomeAsUpEnabled(true); - } - markers = new JSONArray(); - psLabPermission = PSLabPermission.getInstance(); - gpsLogger = new GPSLogger(this, - (LocationManager) getSystemService(Context.LOCATION_SERVICE)); - map = new Intent(this, MapsActivity.class); - csvLogger = new CSVLogger(getSensorName()); - realm = LocalDataLog.with().getRealm(); - titleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT); - sensorParentView = coordinatorLayout; - setupGuideLayout(); - fillUpFragment(); - invalidateOptionsMenu(); - scienceLab = ScienceLabCommon.scienceLab; - } - - /** - * Fill up the frame with the individual sensor fragment layout - */ - private void fillUpFragment() { - try { - FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); - sensorFragment = getSensorFragment(); - transaction.replace(R.id.sensor_frame, sensorFragment, getSensorName()); - transaction.commit(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void setUpMenu(Menu menu) { - if (playingData || viewingData) { - for (int i = 0; i < menu.size(); i++) { - menu.getItem(i).setVisible(false); - } - } - menu.findItem(R.id.save_graph).setVisible(viewingData || playingData); - menu.findItem(R.id.play_data).setVisible(viewingData || playingData); - menu.findItem(R.id.settings).setTitle(getSensorName() + " Configurations"); - menu.findItem(R.id.stop_data).setVisible(viewingData).setEnabled(startedPlay); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(getMenu(), menu); - setUpMenu(menu); - return true; - } - - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - MenuItem record = menu.findItem(R.id.record_data); - record.setIcon(isRecording ? R.drawable.ic_record_stop_white : R.drawable.ic_record_white); - MenuItem play = menu.findItem(R.id.play_data); - play.setIcon(playingData ? R.drawable.ic_pause_white_24dp : R.drawable.ic_play_arrow_white_24dp); - MenuItem stop = menu.findItem(R.id.stop_data); - stop.setVisible(startedPlay); - return super.onPrepareOptionsMenu(menu); - } - - private void prepareMarkers() { - if (markers.length() > 0) { - map.putExtra("hasMarkers", true); - map.putExtra("markers", markers.toString()); - } else { - map.putExtra("hasMarkers", false); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - - Fragment fragment; - - switch (item.getItemId()) { - /* - When record data button has been pressed, check if the device has write permission - to log and access to location. checkPermission method will prompt user with a dialog - box to allow app to use those features. Upon allowing, onRequestPermissionsResult - will fire up. If user declines to give permission, don't do anything. - */ - case R.id.record_data: - if (!isRecording && (sensorFound() || scienceLab.isConnected())) { - dataRecordingCycle(); - } else if (!isRecording && !sensorFound() && !scienceLab.isConnected()) { - CustomSnackBar.showSnackBar(sensorParentView, getString(R.string.device_not_connected), null, null, Snackbar.LENGTH_SHORT); - } else { - stopRecordSensorData(); - displayLogLocationOnSnackBar(); - isRecording = false; - prepareMarkers(); - } - invalidateOptionsMenu(); - break; - case R.id.play_data: - playingData = !playingData; - if (!startedPlay) { - fragment = getSupportFragmentManager() - .findFragmentByTag(getSensorName()); - - if (fragment instanceof OperationCallback) { - ((OperationCallback) fragment).playData(); - } - } else { - if (getSensorFragment() instanceof SoundMeterDataFragment) { - if (!playingData) { - ((SoundMeterDataFragment) getSupportFragmentManager() - .findFragmentByTag(getSensorName())).pause(); - } else { - ((SoundMeterDataFragment) getSupportFragmentManager() - .findFragmentByTag(getSensorName())).resume(); - } - } - } - invalidateOptionsMenu(); - break; - case R.id.stop_data: - fragment = getSupportFragmentManager() - .findFragmentByTag(getSensorName()); - - if (fragment instanceof OperationCallback) { - ((OperationCallback) fragment).stopData(); - } - break; - case R.id.show_map: - if (psLabPermission.checkPermissions(PSLabSensor.this, - PSLabPermission.MAP_PERMISSION)) { - startActivity(map); - } - break; - case R.id.settings: - Intent settingIntent = new Intent(this, SettingsActivity.class); - settingIntent.putExtra("title", getSensorName() + " Configurations"); - startActivity(settingIntent); - break; - case R.id.show_logged_data: - if (psLabPermission.checkPermissions(PSLabSensor.this, - PSLabPermission.CSV_PERMISSION)) { - Intent intent = new Intent(this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getSensorName()); - startActivity(intent); - } - break; - case R.id.show_guide: - toggleGuide(); - break; - case R.id.save_graph: - displayLogLocationOnSnackBar(); - fragment = getSupportFragmentManager() - .findFragmentByTag(getSensorName()); - - if (fragment instanceof OperationCallback) { - ((OperationCallback) fragment).saveGraph(); - } - break; - case android.R.id.home: - this.finish(); - break; - default: - break; - } - return true; - } - - private void dataRecordingCycle() { - if (psLabPermission.checkPermissions(PSLabSensor.this, PSLabPermission.LOG_PERMISSION)) { - if (locationEnabled) { - if (psLabPermission.checkPermissions(PSLabSensor.this, PSLabPermission.GPS_PERMISSION)) { - gpsRecordingCycle(); - } - } else { - CustomSnackBar.showSnackBar(sensorParentView, - getString(R.string.data_recording_without_location), null, null, Snackbar.LENGTH_LONG); - isRecording = true; - } - } - } - - private void gpsRecordingCycle() { - addLocation = true; - gpsLogger.startCaptureLocation(); - if (gpsLogger.isGPSEnabled()) { - CustomSnackBar.showSnackBar(sensorParentView, - getString(R.string.data_recording_with_location), null, null, Snackbar.LENGTH_LONG); - isRecording = true; - } else { - gpsLogger.gpsAlert.show(); - } - } - - public void displayLogLocationOnSnackBar() { - final File logDirectory = new File( - Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSVLogger.CSV_DIRECTORY + File.separator + getSensorName()); - String logLocation; - try { - logLocation = getString(R.string.log_saved_directory) + logDirectory.getCanonicalPath(); - } catch (IOException e) { - // This message wouldn't appear in usual cases. Added in order to handle ex: - logLocation = getString(R.string.log_saved_failed); - } - CustomSnackBar.showSnackBar(sensorParentView, logLocation, getString(R.string.open), - new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(PSLabSensor.this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getSensorName()); - startActivity(intent); - } - }, Snackbar.LENGTH_INDEFINITE); - } - - private void nogpsRecordingCycle() { - CustomSnackBar.showSnackBar(sensorParentView, - getString(R.string.data_recording_without_location), null, null, Snackbar.LENGTH_LONG); - addLocation = false; - isRecording = true; - } - - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults); - switch (requestCode) { - case PSLabPermission.MAP_PERMISSION: - if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { - Intent map = new Intent(getApplicationContext(), MapsActivity.class); - startActivity(map); - } else { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.no_permission_for_maps), null, null, Snackbar.LENGTH_LONG); - } - break; - case PSLabPermission.LOG_PERMISSION: - if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { - dataRecordingCycle(); - invalidateOptionsMenu(); - } - break; - case PSLabPermission.GPS_PERMISSION: - if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { - gpsRecordingCycle(); - } else { - nogpsRecordingCycle(); - } - invalidateOptionsMenu(); - break; - case PSLabPermission.CSV_PERMISSION: - if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { - Intent intent = new Intent(this, DataLoggerActivity.class); - intent.putExtra(DataLoggerActivity.CALLER_ACTIVITY, getSensorName()); - startActivity(intent); - } - break; - default: - break; - } - } - - /** - * Inflate each individual view with content to fill up the sensor guide - */ - private void setupGuideLayout() { - bottomSheetGuideTitle.setText(getGuideTitle()); - bottomSheetText.setText(getGuideAbstract()); - bottomSheetSchematic.setImageResource(getGuideSchematics()); - bottomSheetDesc.setText(getGuideDescription()); - // if sensor doesn't image in it's guide and hence returns 0 for getGuideSchematics(), hide the visibility of bottomSheetSchematic - if (getGuideSchematics() != 0) { - bottomSheetSchematic.setImageResource(getGuideSchematics()); - } else { - bottomSheetSchematic.setVisibility(View.GONE); - } - // If a sensor has extra content than provided in the standard layout, create a new layout - // and attach the layout id with getGuideExtraContent() - if (getGuideExtraContent() != 0) { - LayoutInflater I = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); - assert I != null; - View childLayout = I.inflate(getGuideExtraContent(), null); - bottomSheetAdditionalContent.addView(childLayout); - } - } - - @Override - protected void onResume() { - super.onResume(); - try { - getDataFromDataLogger(); - } catch (ArrayIndexOutOfBoundsException e) { - CustomSnackBar.showSnackBar(findViewById(android.R.id.content), - getString(R.string.no_data_fetched), null, null, Snackbar.LENGTH_LONG); - } - if (checkGPSOnResume) { - isRecording = true; - checkGPSOnResume = false; - invalidateOptionsMenu(); - } - } -} diff --git a/app/src/main/java/io/pslab/models/PowerSourceData.java b/app/src/main/java/io/pslab/models/PowerSourceData.java deleted file mode 100644 index 971594f75..000000000 --- a/app/src/main/java/io/pslab/models/PowerSourceData.java +++ /dev/null @@ -1,99 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -public class PowerSourceData extends RealmObject { - - @PrimaryKey - private long time; - private long block; - private float pv1; - private float pv2; - private float pv3; - private float pcs; - private double lat; - private double lon; - - public PowerSourceData() {/**/} - - public PowerSourceData(long time, long block, float pv1, float pv2, float pv3, float pcs, double lat, double lon) { - this.time = time; - this.block = block; - this.pv1 = pv1; - this.pv2 = pv2; - this.pv3 = pv3; - this.pcs = pcs; - this.lat = lat; - this.lon = lon; - } - - public float getPv1() { - return pv1; - } - - public void setPv1(float pv1) { - this.pv1 = pv1; - } - - public float getPv2() { - return pv2; - } - - public void setPv2(float pv2) { - this.pv2 = pv2; - } - - public float getPv3() { - return pv3; - } - - public void setPv3(float pv3) { - this.pv3 = pv3; - } - - public float getPcs() { - return pcs; - } - - public void setPcs(float pcs) { - this.pcs = pcs; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", PV1 - " + pv1 + ", PV2 - " + pv2 + ", PV3 - " + pv3 + ", PCS - " + pcs + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/SensorDataBlock.java b/app/src/main/java/io/pslab/models/SensorDataBlock.java deleted file mode 100644 index e25d8a200..000000000 --- a/app/src/main/java/io/pslab/models/SensorDataBlock.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; - -/** - * Created by Padmal on 11/5/18. - */ - -public class SensorDataBlock extends RealmObject { - - private long block; - private String sensorType; - - public SensorDataBlock() {/**/} - - public SensorDataBlock(long block, String sensorType) { - this.block = block; - this.sensorType = sensorType; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public String getSensorType() { - return sensorType; - } - - public void setSensorType(String sensorType) { - this.sensorType = sensorType; - } -} diff --git a/app/src/main/java/io/pslab/models/SensorLogged.java b/app/src/main/java/io/pslab/models/SensorLogged.java deleted file mode 100644 index 26b71f1ff..000000000 --- a/app/src/main/java/io/pslab/models/SensorLogged.java +++ /dev/null @@ -1,86 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -/** - * Created by viveksb007 on 15/8/17. - */ - -public class SensorLogged extends RealmObject { - - private String sensor; - private long dateTimeStart; - @PrimaryKey - private long uniqueRef; - private double latitude; - private double longitude; - private long dateTimeEnd; - private String timeZone; - - - public SensorLogged() { - } - - public SensorLogged(String sensor) { - this.sensor = sensor; - } - - public String getSensor() { - return sensor; - } - - public void setSensor(String sensor) { - this.sensor = sensor; - } - - public long getDateTimeStart() { - return dateTimeStart; - } - - public void setDateTimeStart(long dateTimeStart) { - this.dateTimeStart = dateTimeStart; - } - - public long getUniqueRef() { - return uniqueRef; - } - - public void setUniqueRef(long uniqueRef) { - this.uniqueRef = uniqueRef; - } - - public double getLatitude() { - return latitude; - } - - public void setLatitude(double latitude) { - this.latitude = latitude; - } - - public double getLongitude() { - return longitude; - } - - public void setLongitude(double longitude) { - this.longitude = longitude; - } - - - public long getDateTimeEnd() { - return dateTimeEnd; - } - - public void setDateTimeEnd(long dateTimeEnd) { - this.dateTimeEnd = dateTimeEnd; - } - - - public String getTimeZone() { - return timeZone; - } - - public void setTimeZone(String timeZone) { - this.timeZone = timeZone; - } -} diff --git a/app/src/main/java/io/pslab/models/ServoData.java b/app/src/main/java/io/pslab/models/ServoData.java deleted file mode 100644 index 2ff93d3a3..000000000 --- a/app/src/main/java/io/pslab/models/ServoData.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -public class ServoData extends RealmObject { - - @PrimaryKey - private long time; - private long block; - private String degree1, degree2, degree3, degree4; - private double lat, lon; - - public ServoData() {/**/} - - public ServoData(long time, long block, String degree1, String degree2, String degree3, String degree4, double lat, double lon) { - this.time = time; - this.block = block; - this.degree1 = degree1; - this.degree2 = degree2; - this.degree3 = degree3; - this.degree4 = degree4; - this.lat = lat; - this.lon = lon; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public String getDegree1() { - return degree1; - } - - public void setDegree1(String degree) { - this.degree1 = degree; - } - - public String getDegree2() { - return degree2; - } - - public void setDegree2(String degree) { - this.degree2 = degree; - } - - public String getDegree3() { - return degree3; - } - - public void setDegree3(String degree) { - this.degree3 = degree; - } - - public String getDegree4() { - return degree4; - } - - public void setDegree4(String degree) { - this.degree4 = degree; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", Servo1 - " + degree1 + ", Servo2 - " + degree2 + ", Servo3 - " + degree3 + ", Servo4 - " + degree4 + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/SoundData.java b/app/src/main/java/io/pslab/models/SoundData.java deleted file mode 100644 index ae07b47c7..000000000 --- a/app/src/main/java/io/pslab/models/SoundData.java +++ /dev/null @@ -1,67 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -/** - * @author reckoner1429 - */ -public class SoundData extends RealmObject { - - @PrimaryKey - private long time; - private long block; - private float dB; - private float avgLoudness; - private float maxLoudness; - private float minLoudness; - private double lat; - private double lon; - - public SoundData() { - /* no arg constructor */ - } - - public SoundData(long time, long block, float dB, float avgLoudness, float maxLoudness, - float minLoudness, double lat, double lon) { - this.time = time; - this.block = block; - this.dB = dB; - this.avgLoudness = avgLoudness; - this.minLoudness = minLoudness; - this.maxLoudness = maxLoudness; - this.lat = lat; - this.lon = lon; - } - public long getTime() { - return time; - } - - public long getBlock() { - return block; - } - - public float getdB() { - return dB; - } - - public double getLat() { - return lat; - } - - public double getLon() { - return lon; - } - - public float getAvgLoudness() { - return avgLoudness; - } - - public float getMaxLoudness() { - return maxLoudness; - } - - public float getMinLoudness() { - return minLoudness; - } -} diff --git a/app/src/main/java/io/pslab/models/ThermometerData.java b/app/src/main/java/io/pslab/models/ThermometerData.java deleted file mode 100644 index 56d4e9a1d..000000000 --- a/app/src/main/java/io/pslab/models/ThermometerData.java +++ /dev/null @@ -1,67 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; - -public class ThermometerData extends RealmObject { - private long time; - private long block; - private float temp; - private double lat, lon; - - public ThermometerData() {/**/} - - public ThermometerData(long time, long block,float temp, double lat, double lon) { - - this.time = time; - this.block = block; - this.lat = lat; - this.lon = lon; - this.temp = temp; - - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public float getTemp() { - return temp; - } - - public void setTemp(float temp) { - this.temp = temp; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ",Temperature - " + temp + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/models/WaveGeneratorData.java b/app/src/main/java/io/pslab/models/WaveGeneratorData.java deleted file mode 100644 index 3d3c5d4b8..000000000 --- a/app/src/main/java/io/pslab/models/WaveGeneratorData.java +++ /dev/null @@ -1,113 +0,0 @@ -package io.pslab.models; - -import io.realm.RealmObject; -import io.realm.annotations.PrimaryKey; - -public class WaveGeneratorData extends RealmObject { - - @PrimaryKey - private long time; - private long block; - private String mode, wave, shape, freq, phase, duty; - private double lat, lon; - - public WaveGeneratorData() {/**/} - - public WaveGeneratorData(long time, long block, String mode, String wave, String shape, String freq, String phase, String duty, double lat, double lon) { - this.time = time; - this.block = block; - this.mode = mode; - this.wave = wave; - this.shape = shape; - this.freq = freq; - this.phase = phase; - this.duty = duty; - this.lat = lat; - this.lon = lon; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public long getBlock() { - return block; - } - - public void setBlock(long block) { - this.block = block; - } - - public String getMode() { - return mode; - } - - public void setMode(String mode) { - this.mode = mode; - } - - public String getFreq() { - return freq; - } - - public void setFreq(String freq) { - this.freq = freq; - } - - public String getWave() { - return wave; - } - - public void setWave(String wave) { - this.wave = wave; - } - - public String getShape() { - return shape; - } - - public void setShape(String shape) { - this.shape = shape; - } - - public String getDuty() { - return duty; - } - - public void setDuty(String duty) { - this.duty = duty; - } - - public String getPhase() { - return phase; - } - - public void setPhase(String phase) { - this.phase = phase; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - @Override - public String toString() { - return "Block - " + block + ", Time - " + time + ", Mode - " + mode + ", Wave - " + wave + ", Shape - " + shape + ", Freq - " + freq + ", Phase - " + phase + ", Duty - " + duty + ", Lat - " + lat + ", Lon - " + lon; - } -} diff --git a/app/src/main/java/io/pslab/others/AudioJack.java b/app/src/main/java/io/pslab/others/AudioJack.java deleted file mode 100644 index ac6836aab..000000000 --- a/app/src/main/java/io/pslab/others/AudioJack.java +++ /dev/null @@ -1,122 +0,0 @@ -package io.pslab.others; - -import android.media.AudioFormat; -import android.media.AudioManager; -import android.media.AudioRecord; -import android.media.AudioTrack; -import android.media.MediaRecorder; -import android.util.Log; - -import java.util.Random; - -/** - * Created by viveksb007 on 11/7/17. - */ - -public class AudioJack { - - /* TODO : Output value in buffer would be between -2^16 and 2^16, need to map it too or show its FFT */ - - private static final String TAG = "AudioJack"; - - public static final int SAMPLING_RATE = 44100; - private static final int RECORDING_CHANNEL = AudioFormat.CHANNEL_IN_MONO; - private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT; - - private AudioRecord audioRecord = null; - private AudioTrack audioTrack = null; - private int minRecorderBufferSize; - private int minTrackBufferSize; - private String io; - private Random random; - - public boolean configurationStatus; - - /* - * Context to obtain AudioManager Instance and string io to classify if requested input or output. - * */ - public AudioJack(String io) { - this.io = io; - random = new Random(); - configurationStatus = configure(); - } - - private boolean configure() { - if ("input".equals(io)) { - /* Initialize audioRecord */ - minRecorderBufferSize = AudioRecord.getMinBufferSize(SAMPLING_RATE, RECORDING_CHANNEL, RECORDER_AUDIO_ENCODING); - if (minRecorderBufferSize == AudioRecord.ERROR || minRecorderBufferSize == AudioRecord.ERROR_BAD_VALUE) { - minRecorderBufferSize = SAMPLING_RATE * 2; - } - audioRecord = new AudioRecord( - MediaRecorder.AudioSource.MIC, - SAMPLING_RATE, - RECORDING_CHANNEL, - RECORDER_AUDIO_ENCODING, - minRecorderBufferSize); - if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) { - Log.e(TAG, "Audio Record can't be initialized"); - return false; - } - audioRecord.startRecording(); - } else { - /* Initialize audioTrack */ - minTrackBufferSize = AudioTrack.getMinBufferSize(SAMPLING_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT); - if (minTrackBufferSize == AudioTrack.ERROR || minTrackBufferSize == AudioTrack.ERROR_BAD_VALUE) { - minTrackBufferSize = SAMPLING_RATE * 2; - } - // Using STREAM_MUSIC. So to change amplitude stream music needs to be changed - audioTrack = new AudioTrack( - AudioManager.STREAM_MUSIC, - SAMPLING_RATE, - AudioFormat.CHANNEL_OUT_MONO, - AudioFormat.ENCODING_PCM_16BIT, - minTrackBufferSize, - AudioTrack.MODE_STREAM); - if (audioTrack.getState() != AudioTrack.STATE_INITIALIZED) { - Log.e(TAG, "AudioTrack can't be initialized"); - return false; - } - audioTrack.play(); - } - return true; - } - - public short[] read() { - /* return captured audio buffer */ - short[] audioBuffer = new short[minRecorderBufferSize / 2]; - audioRecord.read(audioBuffer, 0, audioBuffer.length); - return audioBuffer; - } - - public void write(short[] buffer) { - /* write buffer to audioTrack */ - audioTrack.write(buffer, 0, buffer.length); - } - - /* - * Would generate a buffer based on frequency value which would be played by AudioTrack to generate wave - * */ - public short[] createBuffer(int frequency) { - // generating a random buffer for now - short[] buffer = new short[minTrackBufferSize]; - for (int i = 0; i < minTrackBufferSize; i++) { - buffer[i] = (short) (random.nextInt(32767) + (-32768)); - } - return buffer; - } - - public void release() { - Log.v(TAG, "AudioJack object released"); - if (audioRecord != null) { - if (audioRecord.getState() == AudioRecord.RECORDSTATE_RECORDING) - audioRecord.stop(); - audioRecord.release(); - } - if (audioTrack != null) { - if (audioTrack.getState() == AudioTrack.PLAYSTATE_PLAYING) - audioTrack.stop(); - audioTrack.release(); - } - } -} diff --git a/app/src/main/java/io/pslab/others/CSVDataLine.java b/app/src/main/java/io/pslab/others/CSVDataLine.java deleted file mode 100644 index 2ea09f77e..000000000 --- a/app/src/main/java/io/pslab/others/CSVDataLine.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.pslab.others; - -import androidx.annotation.NonNull; - -import androidx.annotation.Nullable; - -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -/** - * Contains data of a single line of a CSV file. - * - * @author Marc Nause, marc.nause@gmx.de - */ -public class CSVDataLine { - - private static final char DELIMITER = ','; - private static final String LINEBREAK = System.lineSeparator(); - private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(Locale.ROOT); - - private final List lineData = new ArrayList<>(); - - public CSVDataLine add(@Nullable final String data) { - lineData.add(data); - return this; - } - - public CSVDataLine add(@Nullable final Number data) { - lineData.add(data == null ? null : NUMBER_FORMAT.format(data)); - return this; - } - - @NonNull - @Override - public String toString() { - final StringBuilder stringBuilder = new StringBuilder(); - - for (int i = 0, len = lineData.size(); i < len; i++) { - if (i > 0) { - stringBuilder.append(DELIMITER); - } - final String data = lineData.get(i); - if (data != null) { - stringBuilder.append(data); - } - } - stringBuilder.append(LINEBREAK); - - return stringBuilder.toString(); - } -} diff --git a/app/src/main/java/io/pslab/others/CSVLogger.java b/app/src/main/java/io/pslab/others/CSVLogger.java deleted file mode 100644 index 92791becb..000000000 --- a/app/src/main/java/io/pslab/others/CSVLogger.java +++ /dev/null @@ -1,114 +0,0 @@ -package io.pslab.others; - -import android.os.Environment; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -/** - * Created by Padmal on 6/24/18. - */ - -public class CSVLogger { - - private File csvFile; - private String category; - - public static final String CSV_DIRECTORY = "PSLab"; - public static final SimpleDateFormat FILE_NAME_FORMAT = new SimpleDateFormat( - "yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT); - - /** - * Constructor initiate logger with a category folder - * - * @param category type of readings - */ - public CSVLogger(String category) { - this.category = category; - setupPath(); - } - - /** - * Create required directories and csv files to record data - */ - private void setupPath() { - File csvDirectory = new File( - Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY); - if (!csvDirectory.exists()) { - try { - csvDirectory.mkdir(); - } catch (Exception e) { - e.printStackTrace(); - } - } - File categoryDirectory = new File( - Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + category); - if (!categoryDirectory.exists()) { - try { - categoryDirectory.mkdir(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void prepareLogFile() { - String uniqueFileName = FILE_NAME_FORMAT.format(new Date()); - csvFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + category + - File.separator + uniqueFileName + ".csv"); - if (!csvFile.exists()) { - try { - csvFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - /** - * Write comma seperated data lines to the file created - * - * @param data comma separated data line ends with a new line character - */ - public void writeCSVFile(CSVDataLine data) { - if (csvFile.exists()) { - try { - PrintWriter out - = new PrintWriter(new BufferedWriter(new FileWriter(csvFile, true))); - out.write(data.toString()); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public String getCurrentFilePath() { - return Environment.getExternalStorageDirectory().getAbsolutePath() + - File.separator + CSV_DIRECTORY + File.separator + category; - } - - public void deleteFile() { - csvFile.delete(); - } - - public void writeMetaData(String instrumentName) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String metaDataTime = sdf.format(System.currentTimeMillis()); - CSVDataLine metaData = new CSVDataLine() - .add(instrumentName) - .add(metaDataTime.split(" ")[0]) - .add(metaDataTime.split(" ")[1]); - writeCSVFile(metaData); - } -} diff --git a/app/src/main/java/io/pslab/others/ChannelAxisFormatter.java b/app/src/main/java/io/pslab/others/ChannelAxisFormatter.java deleted file mode 100644 index 5dc8aa267..000000000 --- a/app/src/main/java/io/pslab/others/ChannelAxisFormatter.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.pslab.others; - -import com.github.mikephil.charting.components.AxisBase; -import com.github.mikephil.charting.formatter.IAxisValueFormatter; - -import java.util.ArrayList; - -/** - * Created by viveksb007 on 14/6/17. - */ - -public class ChannelAxisFormatter implements IAxisValueFormatter { - - private ArrayList laChannelNames; - - public ChannelAxisFormatter(ArrayList channelNames) { - this.laChannelNames = channelNames; - } - - @Override - public String getFormattedValue(float value, AxisBase axis) { - switch ((int) value) { - case 1: - return laChannelNames.get(0); - case 3: - return laChannelNames.get(1); - case 5: - return laChannelNames.get(2); - case 7: - return laChannelNames.get(3); - default: - return ""; - } - } - -} diff --git a/app/src/main/java/io/pslab/others/ControlActivityCommon.java b/app/src/main/java/io/pslab/others/ControlActivityCommon.java deleted file mode 100644 index e04ff5aca..000000000 --- a/app/src/main/java/io/pslab/others/ControlActivityCommon.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.pslab.others; - -import java.util.HashMap; - -/** - * Created by AVJEET on 16-02-2018. - */ - -public class ControlActivityCommon { - public static HashMap editTextValues ; - - public ControlActivityCommon(){ - editTextValues= new HashMap<>(); - } - -} diff --git a/app/src/main/java/io/pslab/others/CustomScrollView.java b/app/src/main/java/io/pslab/others/CustomScrollView.java deleted file mode 100644 index d75c0b0ad..000000000 --- a/app/src/main/java/io/pslab/others/CustomScrollView.java +++ /dev/null @@ -1,42 +0,0 @@ -package io.pslab.others; - -import android.content.Context; -import android.util.AttributeSet; -import android.view.MotionEvent; -import android.view.View; -import android.widget.ScrollView; - -/** - * Created by Avjeet on 20-07-2018. - */ -public class CustomScrollView extends ScrollView { - public CustomScrollView(Context context) { - super(context); - } - - public CustomScrollView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public CustomScrollView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - @Override - public boolean onInterceptTouchEvent(MotionEvent event) { - return super.onInterceptTouchEvent(event); - } - - @Override - public boolean onTouchEvent(MotionEvent event) { - View view = getChildAt(getChildCount() - 1); - int diff = (view.getBottom() - (getHeight() + getScrollY())); - - if (event.getAction() == MotionEvent.ACTION_DOWN) { - if (diff == 0) { - return false; - } - } - return super.onTouchEvent(event); - } -} diff --git a/app/src/main/java/io/pslab/others/CustomSnackBar.java b/app/src/main/java/io/pslab/others/CustomSnackBar.java deleted file mode 100644 index ea526446c..000000000 --- a/app/src/main/java/io/pslab/others/CustomSnackBar.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.pslab.others; - -import android.graphics.Color; - -import androidx.annotation.NonNull; -import androidx.core.content.ContextCompat; -import android.view.View; -import android.widget.TextView; - -import com.google.android.material.snackbar.Snackbar; - -import io.pslab.R; - -/** - * Created by Avjeet on 12-07-2018. - */ -public class CustomSnackBar { - - public static Snackbar snackbar; - - public static void showSnackBar(@NonNull View holderLayout, @NonNull String displayText, - String actionText, View.OnClickListener clickListener, int duration) { - snackbar = Snackbar.make(holderLayout, displayText, duration) - .setAction(actionText, clickListener); - snackbar.setActionTextColor(ContextCompat.getColor(holderLayout.getContext(), R.color.colorPrimary)); - View sbView = snackbar.getView(); - TextView textView = sbView.findViewById(R.id.snackbar_text); - textView.setTextColor(Color.WHITE); - snackbar.show(); - } -} diff --git a/app/src/main/java/io/pslab/others/CustomTabService.java b/app/src/main/java/io/pslab/others/CustomTabService.java deleted file mode 100644 index 9ba84d535..000000000 --- a/app/src/main/java/io/pslab/others/CustomTabService.java +++ /dev/null @@ -1,66 +0,0 @@ -package io.pslab.others; - -import android.app.Activity; -import android.content.ComponentName; -import android.net.Uri; -import androidx.browser.customtabs.CustomTabsClient; -import androidx.browser.customtabs.CustomTabsIntent; -import androidx.browser.customtabs.CustomTabsServiceConnection; -import androidx.browser.customtabs.CustomTabsSession; -import com.google.android.material.snackbar.Snackbar; -import androidx.core.content.ContextCompat; - -import io.pslab.R; - -/** - * Created by nikit on 28/9/17. - */ - -public class CustomTabService { - private CustomTabsClient mCustomTabsClient; - private CustomTabsSession mCustomTabsSession; - private CustomTabsServiceConnection mCustomTabsServiceConnection; - private CustomTabsIntent mCustomTabsIntent; - - private Activity activity; - - public CustomTabService (Activity currentActivity) { - this.activity = currentActivity; - init(); - } - - public CustomTabService (Activity currentActivity, CustomTabsServiceConnection serviceConnection) { - this.activity = currentActivity; - this.mCustomTabsServiceConnection = serviceConnection; - init(); - } - - private void init() { - mCustomTabsServiceConnection = new CustomTabsServiceConnection() { - @Override - public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient customTabsClient) { - mCustomTabsClient = customTabsClient; - mCustomTabsClient.warmup(0L); - mCustomTabsSession = mCustomTabsClient.newSession(null); - } - @Override - public void onServiceDisconnected(ComponentName name) { - mCustomTabsClient= null; - } - }; - CustomTabsClient.bindCustomTabsService(activity, activity.getPackageName(), mCustomTabsServiceConnection); - mCustomTabsIntent = new CustomTabsIntent.Builder(mCustomTabsSession) - .setShowTitle(true) - .setToolbarColor(ContextCompat.getColor(activity, R.color.colorPrimary)) - .build(); - } - - public void launchUrl(String Url){ - try{ - mCustomTabsIntent.launchUrl(activity, Uri.parse(Url)); - }catch (Exception e){ - CustomSnackBar.showSnackBar(activity.findViewById(android.R.id.content), - "Error: "+ e,null,null, Snackbar.LENGTH_SHORT); - } - } -} diff --git a/app/src/main/java/io/pslab/others/EditTextWidget.java b/app/src/main/java/io/pslab/others/EditTextWidget.java deleted file mode 100644 index b522bf075..000000000 --- a/app/src/main/java/io/pslab/others/EditTextWidget.java +++ /dev/null @@ -1,136 +0,0 @@ -package io.pslab.others; - -import android.content.Context; -import android.content.res.TypedArray; -import android.text.Editable; -import android.text.TextWatcher; -import android.util.AttributeSet; -import android.view.View; -import android.widget.Button; -import android.widget.EditText; -import android.widget.LinearLayout; - -import io.pslab.DataFormatter; -import io.pslab.R; - - -/** - * Created by asitava on 22/6/17. - */ - -public class EditTextWidget extends LinearLayout{ - - private EditText editText; - private Button button1; - private Button button2; - private double leastCount; - private double maxima; - private double minima; - - public EditTextWidget(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - applyAttrs(attrs); - } - - public EditTextWidget(Context context, AttributeSet attrs) { - super(context, attrs); - applyAttrs(attrs); - } - - public EditTextWidget(Context context) { - super(context); - } - - public void init(Context context, final double leastCount, final double minima, final double maxima) { - View.inflate(context, R.layout.edittext_control, this); - editText = findViewById(R.id.edittext_control); - editText.setText("0"); - button1 = findViewById(R.id.button_control_plus); - button2 = findViewById(R.id.button_control_minus); - - button1.setEnabled(false); - button2.setEnabled(false); - - editText.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) {} - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - if(!s.toString().equals("")){ - button1.setEnabled(true); - button2.setEnabled(true); - } - } - - @Override - public void afterTextChanged(Editable s) {} - }); - - button1.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - try { - double data = Double.parseDouble(editText.getText().toString()); - data = data - leastCount; - data = Math.round(data*100.0)/100.0; - data = data > maxima ? maxima : data; - data = data < minima ? minima : data; - String editTextValue = DataFormatter.formatDouble(data, DataFormatter.MEDIUM_PRECISION_FORMAT); - editText.setText(editTextValue); - editText.setSelection(editTextValue.length()); - } catch (Exception e) { - editText.setText("0"); - editText.setSelection(1); - } - } - }); - - button2.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - try { - double data = Double.valueOf(editText.getText().toString()); - data = data + leastCount; - data = Math.round(data*100.0)/100.0; - data = data > maxima ? maxima : data; - data = data < minima ? minima : data; - String editTextValue = DataFormatter.formatDouble(data, DataFormatter.MEDIUM_PRECISION_FORMAT); - editText.setText(editTextValue); - editText.setSelection(editTextValue.length()); - } catch (Exception e) { - editText.setText("0"); - editText.setSelection(1); - } - } - }); - } - - private void applyAttrs(AttributeSet attrs) { - TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.EditTextWidget); - final int N = a.getIndexCount(); - for (int i = 0; i < N; ++i) { - int attr = a.getIndex(i); - switch (attr) { - case R.styleable.EditTextWidget_leastcount: - this.leastCount = a.getFloat(attr, 1.0f); - break; - case R.styleable.EditTextWidget_maxima: - this.maxima = a.getFloat(attr, 1.0f); - break; - case R.styleable.EditTextWidget_minima: - this.minima = a.getFloat(attr, 1.0f); - } - } - a.recycle(); - } - - public String getText() { - return editText.getText().toString(); - } - - public void setText(String text) { - editText.setText(text); - editText.setSelection(text.length()); - } -} diff --git a/app/src/main/java/io/pslab/others/FloatSeekBar.java b/app/src/main/java/io/pslab/others/FloatSeekBar.java deleted file mode 100644 index 68ca2e83c..000000000 --- a/app/src/main/java/io/pslab/others/FloatSeekBar.java +++ /dev/null @@ -1,66 +0,0 @@ -package io.pslab.others; - - -import android.content.Context; -import android.content.res.TypedArray; -import android.util.AttributeSet; - -import androidx.appcompat.widget.AppCompatSeekBar; - -import io.pslab.R; - - -/** - * Created by akarshan on 4/10/17. - */ - -public class FloatSeekBar extends AppCompatSeekBar { - private double max = 3.0; - private double min = 0.0; - - public FloatSeekBar(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - applyAttrs(attrs); - } - - public FloatSeekBar(Context context, AttributeSet attrs) { - super(context, attrs); - applyAttrs(attrs); - } - - public FloatSeekBar(Context context) { - super(context); - } - - public double getValue() { - double value = (max - min) * ((float) getProgress() / (float) getMax()) + min; - value = (double) Math.round(value * 100) / 100; - return value; - } - - public void setValue(double value) { - setProgress((int) ((value - min) / (max - min) * getMax())); - } - - private void applyAttrs(AttributeSet attrs) { - TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FloatSeekBar); - final int N = a.getIndexCount(); - for (int i = 0; i < N; ++i) { - int attr = a.getIndex(i); - switch (attr) { - case R.styleable.FloatSeekBar_floatMax: - this.max = a.getFloat(attr, 1.0f); - break; - case R.styleable.FloatSeekBar_floatMin: - this.min = a.getFloat(attr, 0.0f); - break; - } - } - a.recycle(); - } - public void setters(double a, double b) - { - min = a; - max = b; - } -} diff --git a/app/src/main/java/io/pslab/others/GPSLogger.java b/app/src/main/java/io/pslab/others/GPSLogger.java deleted file mode 100644 index a4bbd8d0d..000000000 --- a/app/src/main/java/io/pslab/others/GPSLogger.java +++ /dev/null @@ -1,147 +0,0 @@ -package io.pslab.others; - -import android.annotation.SuppressLint; -import android.app.Activity; -import android.app.AlertDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.location.Location; -import android.location.LocationListener; -import android.location.LocationManager; -import android.os.Bundle; -import android.provider.Settings; -import com.google.android.material.snackbar.Snackbar; - -import io.pslab.R; -import io.pslab.models.PSLabSensor; - -/** - * Created by Padmal on 6/29/18. - */ - -public class GPSLogger { - - public static final int PSLAB_PERMISSION_FOR_MAPS = 102; - private static final int UPDATE_INTERVAL_IN_MILLISECONDS = 400; - private static final int MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; - private LocationManager locationManager; - private Context context; - private Location bestLocation; - private PSLabSensor sensorActivity; - private PSLabPermission psLabPermission; - private String provider = LocationManager.GPS_PROVIDER; - public AlertDialog gpsAlert; - - public GPSLogger(Context context, LocationManager locationManager) { - this.context = context; - this.locationManager = locationManager; - psLabPermission = PSLabPermission.getInstance(); - if (context instanceof PSLabSensor) { - sensorActivity = (PSLabSensor) context; - buildUpGPSAlert(); - } - } - - private void buildUpGPSAlert() { - gpsAlert = new AlertDialog.Builder(sensorActivity, R.style.AlertDialogStyle) - .setTitle(R.string.allow_gps) - .setMessage(R.string.allow_gps_info) - .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); - context.startActivity(intent); - sensorActivity.checkGPSOnResume = true; - } - }) - .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (sensorActivity.isRecording) { - CustomSnackBar.showSnackBar(sensorActivity.sensorParentView, - context.getResources().getString(R.string.data_recording_with_gps_off), - null, null, Snackbar.LENGTH_LONG); - } else { - sensorActivity.isRecording = true; - sensorActivity.invalidateOptionsMenu(); - CustomSnackBar.showSnackBar(sensorActivity.sensorParentView, - context.getResources().getString(R.string.data_recording_with_nogps), - null, null, Snackbar.LENGTH_LONG); - } - } - }) - .create(); - } - - private LocationListener locationListener = new LocationListener() { - @Override - public void onLocationChanged(Location location) { - bestLocation = location; - } - - @Override - public void onStatusChanged(String s, int i, Bundle bundle) {/**/} - - @Override - public void onProviderEnabled(String s) { /**/} - - @Override - public void onProviderDisabled(String s) { - if (sensorActivity.isRecording && !gpsAlert.isShowing()) { - gpsAlert.show(); - } - } - }; - - public boolean isGPSEnabled() { - return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); - } - - /** - * Stop requesting updates - */ - public void removeUpdate() { - locationManager.removeUpdates(locationListener); - } - - /** - * @return the best location fetched - */ - @SuppressLint("MissingPermission") - public Location getDeviceLocation() { - if (bestLocation == null) { - if (psLabPermission.checkPermissions((Activity) context, PSLabPermission.MAP_PERMISSION)) { - locationManager.requestLocationUpdates(provider, - UPDATE_INTERVAL_IN_MILLISECONDS, MIN_DISTANCE_CHANGE_FOR_UPDATES, - locationListener); - return locationManager.getLastKnownLocation(provider); - } else { - return dummyLocation(); - } - } else { - return bestLocation; - } - } - - private Location dummyLocation() { - Location l = new Location(""); - l.setLatitude(0.0); - l.setLongitude(0.0); - return l; - } - - /** - * Set location updates - */ - @SuppressLint("MissingPermission") - public void startCaptureLocation() { - if (psLabPermission.checkPermissions((Activity) context, PSLabPermission.MAP_PERMISSION)) { - locationManager.requestLocationUpdates(provider, UPDATE_INTERVAL_IN_MILLISECONDS, MIN_DISTANCE_CHANGE_FOR_UPDATES, - locationListener); - } else { - CustomSnackBar.showSnackBar(((Activity) context).findViewById(android.R.id.content), - context.getString(R.string.no_permission_for_maps),null,null,Snackbar.LENGTH_LONG); - } - } -} diff --git a/app/src/main/java/io/pslab/others/InitializationVariable.java b/app/src/main/java/io/pslab/others/InitializationVariable.java deleted file mode 100644 index 4593c8d6f..000000000 --- a/app/src/main/java/io/pslab/others/InitializationVariable.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.pslab.others; - -/** - * Created by viveksb007 on 17/6/17. - */ - -public class InitializationVariable { - - private boolean initialised = false; - private onValueChangeListener valueChangeListener; - - public boolean isInitialised() { - return initialised; - } - - public void setVariable(boolean value) { - initialised = value; - if (valueChangeListener != null) valueChangeListener.onChange(); - } - - public onValueChangeListener getValueChangeListener() { - return valueChangeListener; - } - - public void setValueChangeListener(onValueChangeListener valueChangeListener) { - this.valueChangeListener = valueChangeListener; - } - - public interface onValueChangeListener { - void onChange(); - } - -} diff --git a/app/src/main/java/io/pslab/others/LocalDataLog.java b/app/src/main/java/io/pslab/others/LocalDataLog.java deleted file mode 100644 index 61c09cb4c..000000000 --- a/app/src/main/java/io/pslab/others/LocalDataLog.java +++ /dev/null @@ -1,656 +0,0 @@ -package io.pslab.others; - -import io.pslab.interfaces.sensorloggers.AccelerometerRecordables; -import io.pslab.interfaces.sensorloggers.BaroMeterRecordables; -import io.pslab.interfaces.sensorloggers.CompassRecordables; -import io.pslab.interfaces.sensorloggers.DustSensorRecordables; -import io.pslab.interfaces.sensorloggers.GasSensorRecordables; -import io.pslab.interfaces.sensorloggers.GyroscopeRecordables; -import io.pslab.interfaces.sensorloggers.LogicAnalyzerRecordables; -import io.pslab.interfaces.sensorloggers.LuxMeterRecordables; -import io.pslab.interfaces.sensorloggers.MultimeterRecordables; -import io.pslab.interfaces.sensorloggers.OscilloscopeRecordables; -import io.pslab.interfaces.sensorloggers.PowerSourceRecordables; -import io.pslab.interfaces.sensorloggers.SensorRecordables; -import io.pslab.interfaces.sensorloggers.ServoRecordables; -import io.pslab.interfaces.sensorloggers.SoundMeterRecordables; -import io.pslab.interfaces.sensorloggers.ThermometerRecordables; -import io.pslab.interfaces.sensorloggers.WaveGeneratorRecordables; -import io.pslab.models.AccelerometerData; -import io.pslab.models.BaroData; -import io.pslab.models.CompassData; -import io.pslab.models.DustSensorData; -import io.pslab.models.GasSensorData; -import io.pslab.models.GyroData; -import io.pslab.models.LogicAnalyzerData; -import io.pslab.models.LuxData; -import io.pslab.models.MultimeterData; -import io.pslab.models.OscilloscopeData; -import io.pslab.models.PowerSourceData; -import io.pslab.models.SensorDataBlock; -import io.pslab.models.ServoData; -import io.pslab.models.SoundData; -import io.pslab.models.ThermometerData; -import io.pslab.models.WaveGeneratorData; -import io.realm.Realm; -import io.realm.RealmResults; -import io.realm.Sort; - -/** - * Created by Padmal on 11/5/18. - */ - -public class LocalDataLog implements SoundMeterRecordables, DustSensorRecordables, LuxMeterRecordables, BaroMeterRecordables, SensorRecordables, CompassRecordables, AccelerometerRecordables, GyroscopeRecordables, ThermometerRecordables, ServoRecordables, WaveGeneratorRecordables, OscilloscopeRecordables, PowerSourceRecordables, MultimeterRecordables, LogicAnalyzerRecordables, GasSensorRecordables { - - private static LocalDataLog instance; - private final Realm realm; - - private LocalDataLog() { - realm = Realm.getDefaultInstance(); - } - - public static LocalDataLog with() { - if (instance == null) { - instance = new LocalDataLog(); - } - return instance; - } - - public static LocalDataLog getInstance() { - return instance; - } - - public Realm getRealm() { - return realm; - } - - public void refresh() { - realm.refresh(); - } - - /*********************************************************************************************** - * Generic Sensor Section - ***********************************************************************************************/ - @Override - public SensorDataBlock getSensorBlock(long block) { - return realm.where(SensorDataBlock.class).equalTo("block", block).findFirst(); - } - - @Override - public void clearAllSensorBlocks() { - realm.beginTransaction(); - realm.delete(SensorDataBlock.class); - realm.commitTransaction(); - } - - @Override - public void clearTypeOfSensorBlock(String type) { - realm.beginTransaction(); - RealmResults data = getTypeOfSensorBlocks(type); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public void clearSensorBlock(long block) { - realm.beginTransaction(); - SensorDataBlock dataBlock = getSensorBlock(block); - dataBlock.deleteFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllSensorBlocks() { - return realm.where(SensorDataBlock.class) - .findAll().sort("block", Sort.DESCENDING); - } - - @Override - public RealmResults getTypeOfSensorBlocks(String type) { - return realm.where(SensorDataBlock.class) - .equalTo("sensorType", type) - .findAll().sort("block", Sort.DESCENDING); - } - - /*********************************************************************************************** - * Lux Sensor Section - ***********************************************************************************************/ - @Override - public LuxData getLuxData(long timestamp) { - return realm.where(LuxData.class).equalTo("time", timestamp).findFirst(); - } - - @Override - public void clearAllLuxRecords() { - realm.beginTransaction(); - realm.delete(LuxData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfLuxRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfLuxRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllLuxRecords() { - return realm.where(LuxData.class).findAll(); - } - - @Override - public RealmResults getBlockOfLuxRecords(long block) { - return realm.where(LuxData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Accelerometer Sensor Section - ***********************************************************************************************/ - @Override - public AccelerometerData getAccelerometerData(long timestamp) { - return realm.where(AccelerometerData.class).equalTo("time", timestamp).findFirst(); - } - - @Override - public void clearAllAccelerometerRecords() { - realm.beginTransaction(); - realm.delete(AccelerometerData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfAccelerometerRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfAccelerometerRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllAccelerometerRecords() { - return realm.where(AccelerometerData.class).findAll(); - } - - @Override - public RealmResults getBlockOfAccelerometerRecords(long block) { - return realm.where(AccelerometerData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Baro Sensor Section - ***********************************************************************************************/ - @Override - public BaroData getBaroData(long timestamp) { - return realm.where(BaroData.class).equalTo("time", timestamp).findFirst(); - } - - @Override - public void clearAllBaroRecords() { - realm.beginTransaction(); - realm.delete(BaroData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfBaroRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfBaroRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllBaroRecords() { - return realm.where(BaroData.class).findAll(); - } - - @Override - public RealmResults getBlockOfBaroRecords(long block) { - return realm.where(BaroData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Gyroscope Section - ***********************************************************************************************/ - @Override - public GyroData getGyroData(long timeStamp) { - return realm.where(GyroData.class).equalTo("time", timeStamp).findFirst(); - } - - @Override - public void clearAllGyroRecords() { - realm.beginTransaction(); - realm.delete(GyroData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfGyroRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfGyroRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllGyroRecords() { - return realm.where(GyroData.class).findAll(); - } - - @Override - public RealmResults getBlockOfGyroRecords(long block) { - return realm.where(GyroData.class).equalTo("block", block).findAll(); - } - - /*********************************************************************************************** - * Compass Section - ***********************************************************************************************/ - @Override - public CompassData getCompassData(long timeStamp) { - return realm.where(CompassData.class) - .equalTo("time", timeStamp) - .findFirst(); - } - - @Override - public void clearAllCompassRecords() { - realm.beginTransaction(); - realm.delete(CompassData.class); - realm.commitTransaction(); - } - - public void clearBlockOfCompassRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfCompassRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - public RealmResults getAllCompassRecords() { - return realm.where(CompassData.class).findAll(); - } - - @Override - public RealmResults getBlockOfCompassRecords(long block) { - return realm.where(CompassData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Thermometer Section - ***********************************************************************************************/ - @Override - public ThermometerData getThermometerData(long timeStamp) { - return realm.where(ThermometerData.class) - .equalTo("time", timeStamp) - .findFirst(); - } - - @Override - public void clearAllThermometerRecords() { - realm.beginTransaction(); - realm.delete(CompassData.class); - realm.commitTransaction(); - } - - public void clearBlockOfThermometerRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfThermometerRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - public RealmResults getAllThermometerRecords() { - return realm.where(ThermometerData.class).findAll(); - } - - @Override - public RealmResults getBlockOfThermometerRecords(long block) { - return realm.where(ThermometerData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Servo Section - ***********************************************************************************************/ - @Override - public ServoData getServoData(long timeStamp) { - return realm.where(ServoData.class) - .equalTo("time", timeStamp) - .findFirst(); - } - - @Override - public void clearAllServoRecords() { - realm.beginTransaction(); - realm.delete(ServoData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfServoRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfServoRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllServoRecords() { - return realm.where(ServoData.class).findAll(); - } - - @Override - public RealmResults getBlockOfServoRecords(long block) { - return realm.where(ServoData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Wave Generator Section - ***********************************************************************************************/ - @Override - public WaveGeneratorData getWaveData(long timeStamp) { - return realm.where(WaveGeneratorData.class) - .equalTo("time", timeStamp) - .findFirst(); - } - - @Override - public void clearAllWaveRecords() { - realm.beginTransaction(); - realm.delete(WaveGeneratorData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfWaveRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfWaveRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllWaveRecords() { - return realm.where(WaveGeneratorData.class).findAll(); - } - - @Override - public RealmResults getBlockOfWaveRecords(long block) { - return realm.where(WaveGeneratorData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Oscilloscope Section - ***********************************************************************************************/ - - @Override - public OscilloscopeData getOscilloscopeData(long timeStamp) { - return realm.where(OscilloscopeData.class) - .equalTo("time", timeStamp) - .findFirst(); - } - - @Override - public void clearAllOscilloscopeRecords() { - realm.beginTransaction(); - realm.delete(OscilloscopeData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfOscilloscopeRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfOscilloscopeRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllOscilloscopeRecords() { - return realm.where(OscilloscopeData.class).findAll(); - } - - @Override - public RealmResults getBlockOfOscilloscopeRecords(long block) { - return realm.where(OscilloscopeData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Power Source Section - ***********************************************************************************************/ - - @Override - public PowerSourceData getPowerData(long timeStamp) { - return realm.where(PowerSourceData.class) - .equalTo("time", timeStamp) - .findFirst(); - } - - @Override - public void clearAllPowerRecords() { - realm.beginTransaction(); - realm.delete(PowerSourceData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfPowerRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfPowerRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllPowerRecords() { - return realm.where(PowerSourceData.class).findAll(); - } - - @Override - public RealmResults getBlockOfPowerRecords(long block) { - return realm.where(PowerSourceData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Multimeter Section - ***********************************************************************************************/ - - @Override - public MultimeterData getMultimeterData(long timeStamp) { - return realm.where(MultimeterData.class) - .equalTo("time", timeStamp) - .findFirst(); - } - - @Override - public void clearAllMultimeterRecords() { - realm.beginTransaction(); - realm.delete(MultimeterData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfMultimeterRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfMultimeterRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllMultimeterRecords() { - return realm.where(MultimeterData.class).findAll(); - } - - @Override - public RealmResults getBlockOfMultimeterRecords(long block) { - return realm.where(MultimeterData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Logic Analyzer Section - ***********************************************************************************************/ - - @Override - public LogicAnalyzerData getLAData(long timeStamp) { - return realm.where(LogicAnalyzerData.class) - .equalTo("time", timeStamp) - .findFirst(); - } - - @Override - public void clearAllLARecords() { - realm.beginTransaction(); - realm.delete(LogicAnalyzerData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfLARecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfLARecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllLARecords() { - return realm.where(LogicAnalyzerData.class).findAll(); - } - - @Override - public RealmResults getBlockOfLARecords(long block) { - return realm.where(LogicAnalyzerData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Gas Sensor Section - ***********************************************************************************************/ - - @Override - public GasSensorData getGasSensorData(long timeStamp) { - return realm.where(GasSensorData.class) - .equalTo("time", timeStamp) - .findFirst(); - } - - @Override - public void clearAllGasSensorRecords() { - realm.beginTransaction(); - realm.delete(GasSensorData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfGasSensorRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfGasSensorRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllGasSensorRecords() { - return realm.where(GasSensorData.class).findAll(); - } - - @Override - public RealmResults getBlockOfGasSensorRecords(long block) { - return realm.where(GasSensorData.class) - .equalTo("block", block) - .findAll(); - } - - /*********************************************************************************************** - * Dust Sensor Section - ***********************************************************************************************/ - @Override - public DustSensorData getDustSensorData(long timestamp) { - return realm.where(DustSensorData.class).equalTo("time", timestamp).findFirst(); - } - - @Override - public void clearAllDustSensorRecords() { - realm.beginTransaction(); - realm.delete(LuxData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfDustSensorRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfDustSensorRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllDustSensorRecords() { - return realm.where(DustSensorData.class).findAll(); - } - - @Override - public RealmResults getBlockOfDustSensorRecords(long block) { - return realm.where(DustSensorData.class) - .equalTo("block", block) - .findAll(); - } - - - /*********************************************************************************************** - * Sound Meter Section - ***********************************************************************************************/ - @Override - public SoundData getSoundMeterData(long timeStamp) { - return realm.where(SoundData.class).equalTo("time",timeStamp).findFirst(); - } - - @Override - public void clearAllSoundRecords() { - realm.beginTransaction(); - realm.delete(SoundData.class); - realm.commitTransaction(); - } - - @Override - public void clearBlockOfSoundRecords(long block) { - realm.beginTransaction(); - RealmResults data = getBlockOfSoundRecords(block); - data.deleteAllFromRealm(); - realm.commitTransaction(); - } - - @Override - public RealmResults getAllSoundRecords() { - return realm.where(SoundData.class).findAll(); - } - - @Override - public RealmResults getBlockOfSoundRecords(long block) { - return realm.where(SoundData.class).equalTo("block",block) - .findAll(); - } -} diff --git a/app/src/main/java/io/pslab/others/LogicAnalyzerAxisFormatter.java b/app/src/main/java/io/pslab/others/LogicAnalyzerAxisFormatter.java deleted file mode 100644 index 15d3ee415..000000000 --- a/app/src/main/java/io/pslab/others/LogicAnalyzerAxisFormatter.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.pslab.others; - -import com.github.mikephil.charting.components.AxisBase; -import com.github.mikephil.charting.formatter.ValueFormatter; - -import java.util.ArrayList; - -public class LogicAnalyzerAxisFormatter extends ValueFormatter { - - private ArrayList laChannelNames; - - public LogicAnalyzerAxisFormatter(ArrayList channelNames) { - this.laChannelNames = channelNames; - } - - @Override - public String getFormattedValue(float value, AxisBase axis) { - if (value > laChannelNames.size() * 2 - 1) { - switch (laChannelNames.size()) { - case 1: - return laChannelNames.get(0); - case 2: - return laChannelNames.get(1); - case 3: - return laChannelNames.get(2); - case 4: - return laChannelNames.get(3); - default: - return ""; - } - } else { - switch ((int) value) { - case 1: - return laChannelNames.get(0); - case 3: - return laChannelNames.get(1); - case 5: - return laChannelNames.get(2); - case 7: - return laChannelNames.get(3); - default: - return ""; - } - } - } - -} diff --git a/app/src/main/java/io/pslab/others/MathUtils.java b/app/src/main/java/io/pslab/others/MathUtils.java deleted file mode 100644 index 4028f3c65..000000000 --- a/app/src/main/java/io/pslab/others/MathUtils.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.pslab.others; - -import java.util.ArrayList; - -/** - * Created by viveksb007 on 28/7/17. - */ - -public class MathUtils { - - - /* - * Maps a number from one range to another. - * */ - public static double map(double x, double in_min, double in_max, double out_min, double out_max) { - return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; - } - - - /* - * Returns evenly spaced numbers over a specified interval. - * */ - public static double[] linSpace(double start, double stop, int samples) { - ArrayList dataPoints = new ArrayList<>(); - double factor = (stop - start) / samples; - for (double i = start; i < stop; i += factor) dataPoints.add(i); - double[] evenlySpacedArray = new double[dataPoints.size()]; - for (int i = 0; i < dataPoints.size(); i++) { - evenlySpacedArray[i] = dataPoints.get(i); - } - return evenlySpacedArray; - } - - /* - * Returns RMS value of a given list of double values - * */ - public static double rms(double[] list) { - double ms = 0; - for (double i : list) ms += i * i; - ms /= list.length; - return Math.sqrt(ms); - } -} diff --git a/app/src/main/java/io/pslab/others/NothingSelectedSpinnerAdapter.java b/app/src/main/java/io/pslab/others/NothingSelectedSpinnerAdapter.java deleted file mode 100644 index ea9f70fee..000000000 --- a/app/src/main/java/io/pslab/others/NothingSelectedSpinnerAdapter.java +++ /dev/null @@ -1,171 +0,0 @@ -package io.pslab.others; - -import android.content.Context; -import android.database.DataSetObserver; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ListAdapter; -import android.widget.SpinnerAdapter; - - -/** - * Created by akarshan on 7/18/17. - */ - -/** - * Decorator Adapter to allow a Spinner to show a 'Nothing Selected...' initially - * displayed instead of the first choice in the Adapter. - */ -public class NothingSelectedSpinnerAdapter implements SpinnerAdapter, ListAdapter { - - private static final int EXTRA = 1; - protected SpinnerAdapter adapter; - protected Context context; - private int nothingSelectedLayout; - private int nothingSelectedDropdownLayout; - private LayoutInflater layoutInflater; - - /** - * Use this constructor to have NO 'Select One...' item, instead use - * the standard prompt or nothing at all. - * - * @param spinnerAdapter wrapped Adapter. - * @param nothingSelectedLayout layout for nothing selected, perhaps - * you want text grayed out like a prompt... - * @param context - */ - public NothingSelectedSpinnerAdapter( - SpinnerAdapter spinnerAdapter, - int nothingSelectedLayout, Context context) { - - this(spinnerAdapter, nothingSelectedLayout, -1, context); - } - - /** - * Use this constructor to Define your 'Select One...' layout as the first - * row in the returned choices. - * If you do this, you probably don't want a prompt on your spinner or it'll - * have two 'Select' rows. - * - * @param spinnerAdapter wrapped Adapter. Should probably return false for isEnabled(0) - * @param nothingSelectedLayout layout for nothing selected, perhaps you want - * text grayed out like a prompt... - * @param nothingSelectedDropdownLayout layout for your 'Select an Item...' in - * the dropdown. - * @param context - */ - private NothingSelectedSpinnerAdapter(SpinnerAdapter spinnerAdapter, - int nothingSelectedLayout, int nothingSelectedDropdownLayout, Context context) { - this.adapter = spinnerAdapter; - this.context = context; - this.nothingSelectedLayout = nothingSelectedLayout; - this.nothingSelectedDropdownLayout = nothingSelectedDropdownLayout; - layoutInflater = LayoutInflater.from(context); - } - - @Override - public final View getView(int position, View convertView, ViewGroup parent) { - // This provides the View for the Selected Item in the Spinner, not - // the dropdown (unless dropdownView is not set). - if (position == 0) { - return getNothingSelectedView(parent); - } - return adapter.getView(position - EXTRA, null, parent); // Could re-use - // the convertView if possible. - } - - /** - * View to show in Spinner with Nothing Selected - * Override this to do something dynamic... e.g. "37 Options Found" - * - * @param parent - * @return - */ - private View getNothingSelectedView(ViewGroup parent) { - return layoutInflater.inflate(nothingSelectedLayout, parent, false); - } - - @Override - public View getDropDownView(int position, View convertView, ViewGroup parent) { - // Android BUG! http://code.google.com/p/android/issues/detail?id=17128 - - // Spinner does not support multiple view types - if (position == 0) { - return nothingSelectedDropdownLayout == -1 ? - new View(context) : - getNothingSelectedDropdownView(parent); - } - - // Could re-use the convertView if possible, use setTag... - return adapter.getDropDownView(position - EXTRA, null, parent); - } - - /** - * Override this to do something dynamic... For example, "Pick your favorite - * of these 37". - * - * @param parent - * @return - */ - private View getNothingSelectedDropdownView(ViewGroup parent) { - return layoutInflater.inflate(nothingSelectedDropdownLayout, parent, false); - } - - @Override - public int getCount() { - int count = adapter.getCount(); - return count == 0 ? 0 : count + EXTRA; - } - - @Override - public Object getItem(int position) { - return position == 0 ? null : adapter.getItem(position - EXTRA); - } - - @Override - public int getItemViewType(int position) { - return 0; - } - - @Override - public int getViewTypeCount() { - return 1; - } - - @Override - public long getItemId(int position) { - return position >= EXTRA ? adapter.getItemId(position - EXTRA) : position - EXTRA; - } - - @Override - public boolean hasStableIds() { - return adapter.hasStableIds(); - } - - @Override - public boolean isEmpty() { - return adapter.isEmpty(); - } - - @Override - public void registerDataSetObserver(DataSetObserver observer) { - adapter.registerDataSetObserver(observer); - } - - @Override - public void unregisterDataSetObserver(DataSetObserver observer) { - adapter.unregisterDataSetObserver(observer); - } - - @Override - public boolean areAllItemsEnabled() { - return false; - } - - @Override - public boolean isEnabled(int position) { - return position != 0; // Don't allow the 'nothing selected' - // item to be picked. - } - -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/others/OscilloscopeMeasurements.java b/app/src/main/java/io/pslab/others/OscilloscopeMeasurements.java deleted file mode 100644 index 6ee5e708b..000000000 --- a/app/src/main/java/io/pslab/others/OscilloscopeMeasurements.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.pslab.others; - -import java.util.HashMap; -import java.util.Map; - -import io.pslab.activity.OscilloscopeActivity.ChannelMeasurements; -import io.pslab.activity.OscilloscopeActivity.CHANNEL; - - -public class OscilloscopeMeasurements { - - public final static Map> channel = new HashMap<>(); - - static { - channel.put(CHANNEL.CH1, new HashMap() {{ - put(ChannelMeasurements.FREQUENCY, 0.00); - put(ChannelMeasurements.PERIOD, 0.00); - put(ChannelMeasurements.AMPLITUDE, 0.00); - put(ChannelMeasurements.POSITIVE_PEAK, 0.00); - put(ChannelMeasurements.NEGATIVE_PEAK, 0.00); - }}); - - channel.put(CHANNEL.CH2, new HashMap() {{ - put(ChannelMeasurements.FREQUENCY, 0.00); - put(ChannelMeasurements.PERIOD, 0.00); - put(ChannelMeasurements.AMPLITUDE, 0.00); - put(ChannelMeasurements.POSITIVE_PEAK, 0.00); - put(ChannelMeasurements.NEGATIVE_PEAK, 0.00); - }}); - - channel.put(CHANNEL.CH3, new HashMap() {{ - put(ChannelMeasurements.FREQUENCY, 0.00); - put(ChannelMeasurements.PERIOD, 0.00); - put(ChannelMeasurements.AMPLITUDE, 0.00); - put(ChannelMeasurements.POSITIVE_PEAK, 0.00); - put(ChannelMeasurements.NEGATIVE_PEAK, 0.00); - }}); - - channel.put(CHANNEL.MIC, new HashMap() {{ - put(ChannelMeasurements.FREQUENCY, 0.00); - put(ChannelMeasurements.PERIOD, 0.00); - put(ChannelMeasurements.AMPLITUDE, 0.00); - put(ChannelMeasurements.POSITIVE_PEAK, 0.00); - put(ChannelMeasurements.NEGATIVE_PEAK, 0.00); - }}); - } -} diff --git a/app/src/main/java/io/pslab/others/PSLabPermission.java b/app/src/main/java/io/pslab/others/PSLabPermission.java deleted file mode 100644 index 0f0274670..000000000 --- a/app/src/main/java/io/pslab/others/PSLabPermission.java +++ /dev/null @@ -1,149 +0,0 @@ -package io.pslab.others; - - -import android.Manifest; -import android.app.Activity; -import android.app.AlertDialog; -import android.content.pm.PackageManager; -import android.util.Log; -import android.view.View; -import android.widget.Toast; - -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import io.pslab.activity.SplashActivity; - -/** - * Created by Padmal on 11/3/18. - */ - -public class PSLabPermission { - - private String[] allPermissions = new String[] { - Manifest.permission.WRITE_EXTERNAL_STORAGE, - Manifest.permission.RECORD_AUDIO, - Manifest.permission.ACCESS_FINE_LOCATION - }; - - private String[] csvPermissions = new String[] { - Manifest.permission.ACCESS_FINE_LOCATION - }; - - private String[] logPermissions = new String[] { - Manifest.permission.WRITE_EXTERNAL_STORAGE - }; - - private String[] mapPermissions = new String[] { - Manifest.permission.ACCESS_FINE_LOCATION - }; - List listPermissionsNeeded = new ArrayList<>(); - - public static final int ALL_PERMISSION = 100; - public static final int LOG_PERMISSION = 101; - public static final int MAP_PERMISSION = 102; - public static final int GPS_PERMISSION = 103; - public static final int CSV_PERMISSION = 104; - - public static int REQUEST_CODE = 0; - - public static int PERMISSIONS_REQUIRED = 0; - - private static final PSLabPermission pslabPermission = new PSLabPermission(); - - public static PSLabPermission getInstance() { - return pslabPermission; - } - - private PSLabPermission() {/**/} - public boolean checkPermissions(Activity activity, int mode) { - if (mode == ALL_PERMISSION) { - for (String permission : allPermissions) { - if (ContextCompat.checkSelfPermission(activity, permission) - != PackageManager.PERMISSION_GRANTED) { - listPermissionsNeeded.add(permission); - } - } - } else if (mode == LOG_PERMISSION) { - for (String permission : logPermissions) { - if (ContextCompat.checkSelfPermission(activity, permission) - != PackageManager.PERMISSION_GRANTED) { - listPermissionsNeeded.add(permission); - } - } - } else if (mode == MAP_PERMISSION) { - for (String permission : mapPermissions) { - if (ContextCompat.checkSelfPermission(activity, permission) - != PackageManager.PERMISSION_GRANTED) { - listPermissionsNeeded.add(permission); - } - } - } else if (mode == GPS_PERMISSION) { - for (String permission : mapPermissions) { - if (ContextCompat.checkSelfPermission(activity, permission) - != PackageManager.PERMISSION_GRANTED) { - listPermissionsNeeded.add(permission); - } - } - } else if (mode == CSV_PERMISSION) { - for (String permission : csvPermissions) { - if (ContextCompat.checkSelfPermission(activity, permission) - != PackageManager.PERMISSION_GRANTED) { - listPermissionsNeeded.add(permission); - } - } - } - PERMISSIONS_REQUIRED = listPermissionsNeeded.size(); - if (!listPermissionsNeeded.isEmpty()) { - for(String permission : listPermissionsNeeded) { - if (Objects.equals(permission, Manifest.permission.ACCESS_FINE_LOCATION)) { - AlertDialog.Builder alert = new AlertDialog.Builder(activity); - alert.setTitle("Location Permission Disclosure"); - alert.setCancelable(false); - alert.setMessage("PSLab requires access to location data to show the location of measurements on a map."); - alert.setPositiveButton("ACCEPT", (dialog, which) -> { - ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ++REQUEST_CODE); - }); - alert.setNegativeButton("DENY", (dialog, which) -> { - Toast.makeText(activity, "Please grant the permission.", Toast.LENGTH_SHORT).show(); - ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ++REQUEST_CODE); - }); - AlertDialog alertDialog = alert.create(); - alertDialog.show(); - } else if (Objects.equals(permission, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { - AlertDialog.Builder alert = new AlertDialog.Builder(activity); - alert.setTitle("Storage Permission Disclosure"); - alert.setMessage("PSLab requires access to storage to enable the storage and import of sensor data."); - alert.setPositiveButton("ACCEPT", (dialog, which) -> { - ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, ++REQUEST_CODE); - }); - alert.setNegativeButton("DENY", (dialog, which) -> { - Toast.makeText(activity, "Please grant the permission.", Toast.LENGTH_SHORT).show(); - ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, ++REQUEST_CODE); - }); - AlertDialog alertDialog = alert.create(); - alertDialog.show(); - } else if (Objects.equals(permission, Manifest.permission.RECORD_AUDIO)) { - AlertDialog.Builder alert = new AlertDialog.Builder(activity); - alert.setTitle("Audio Permission Disclosure"); - alert.setMessage("PSLab requires access to record audio for recording data using the Built-In MIC."); - alert.setPositiveButton("ACCEPT", (dialog, which) -> { - ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.RECORD_AUDIO}, ++REQUEST_CODE); - }); - alert.setNegativeButton("DENY", (dialog, which) -> { - Toast.makeText(activity, "Please grant the permission.", Toast.LENGTH_SHORT).show(); - ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.RECORD_AUDIO}, ++REQUEST_CODE); - }); - AlertDialog alertDialog = alert.create(); - alertDialog.show(); - } - } - return false; - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/others/Plot2D.java b/app/src/main/java/io/pslab/others/Plot2D.java deleted file mode 100644 index 82d92739f..000000000 --- a/app/src/main/java/io/pslab/others/Plot2D.java +++ /dev/null @@ -1,211 +0,0 @@ -package io.pslab.others; - -/** - * Created by akarshan on 7/15/17. - */ - - -import android.content.Context; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Typeface; -import android.util.AttributeSet; -import android.view.MotionEvent; -import android.view.ScaleGestureDetector; -import android.view.View; - -public class Plot2D extends View { - - private Paint paint; - private float[] xValues = {0.0f}; - private float[] yValues = {0.0f}; - private float maxX = 0.0f, maxY = 0.0f, minX = 0.0f, minY = 0.0f, - locxAxis = 0.0f, locyAxis = 0.0f; - private int vectorLength; - private int axis = 1; - private static float MIN_ZOOM = 1f; - private static float MAX_ZOOM = 5f; - - private float scaleFactor = 1.f; - private ScaleGestureDetector detector; - - public Plot2D(Context context, AttributeSet attrs) { - super(context, attrs); - detector = new ScaleGestureDetector(getContext(), new ScaleListener()); - paint = new Paint(); - } - - public Plot2D(Context context, AttributeSet attrs, int id) { - super(context, attrs); - detector = new ScaleGestureDetector(getContext(), new ScaleListener()); - paint = new Paint(); - } - - public void plotData(float[] xValues, float[] yValues, int axis) { - this.xValues = xValues; - this.yValues = yValues; - this.axis = axis; - vectorLength = xValues.length; - // paint = new Paint(); - - getAxis(xValues, yValues); - invalidate(); - } - - public void plotData(float[] yValues, int axis) { - if (yValues != null) { - vectorLength = yValues.length; - this.xValues = new float[vectorLength]; - for (int i = 0; i < vectorLength; i++) { - xValues[i] = i; - } - this.yValues = yValues; - this.axis = axis; - // paint = new Paint(); - - getAxis(xValues, yValues); - invalidate(); - } - } - - - public Plot2D(Context context, float[] xValues, float[] yValues, int axis) { - super(context); - this.xValues = xValues; - this.yValues = yValues; - this.axis = axis; - vectorLength = xValues.length; - paint = new Paint(); - detector = new ScaleGestureDetector(getContext(), new ScaleListener()); - getAxis(xValues, yValues); - - } - - @Override - protected void onDraw(Canvas canvas) { - - canvas.save(); - canvas.scale(scaleFactor, scaleFactor); - - float canvasHeight = getHeight(); - float canvasWidth = getWidth(); - int[] xValuesInPixels = toPixel(canvasWidth, minX, maxX, xValues); - int[] yValuesInPixels = toPixel(canvasHeight, minY, maxY, yValues); - int locxAxisInPixels = toPixelInt(canvasHeight, minY, maxY, locxAxis); - int locyAxisInPixels = toPixelInt(canvasWidth, minX, maxX, locyAxis); - - paint.setStrokeWidth(2); - canvas.drawARGB(255, 0, 0, 0); - for (int i = 0; i < vectorLength - 1; i++) { - paint.setColor(Color.RED); - canvas.drawLine(xValuesInPixels[i], canvasHeight - - yValuesInPixels[i], xValuesInPixels[i + 1], canvasHeight - - yValuesInPixels[i + 1], paint); - } - - paint.setColor(Color.WHITE); - paint.setStrokeWidth(5f); - canvas.drawLine(0, canvasHeight - locxAxisInPixels, canvasWidth, - canvasHeight - locxAxisInPixels, paint); - canvas.drawLine(locyAxisInPixels, 0, locyAxisInPixels, canvasHeight, - paint); - - // Automatic axis markings, modify n to control the number of axis labels - if (axis != 0) { - float temp = 0.0f; - int n = 8; - //paint.setTextAlign(Paint.Align.LEFT); - paint.setTextSize(30.0f); - paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)); - for (int i = 1; i <= n; i++) { - if (i <= n / 2) { - temp = Math.round(10 * (minX + (i - 1) * (maxX - minX) / n)) / 10; - canvas.drawText("" + temp, - (float) toPixelInt(canvasWidth, minX, maxX, temp), - canvasHeight - locxAxisInPixels - 10, paint); - temp = Math.round(10 * (minY + (i - 1) * (maxY - minY) / n)) / 10; - canvas.drawText("" + temp, locyAxisInPixels + 10, canvasHeight - - (float) toPixelInt(canvasHeight, minY, maxY, temp), - paint); - } else { - temp = Math.round(10 * (minX + (i - 1) * (maxX - minX) / n)) / 10; - canvas.drawText("" + temp, - (float) toPixelInt(canvasWidth, minX, maxX, temp), - canvasHeight - locxAxisInPixels + 30, paint); - temp = Math.round(10 * (minY + (i - 1) * (maxY - minY) / n)) / 10; - canvas.drawText("" + temp, locyAxisInPixels - 65, canvasHeight - - (float) toPixelInt(canvasHeight, minY, maxY, temp), - paint); - } - } - canvas.drawText("" + maxX, - (float) toPixelInt(canvasWidth, minX, maxX, maxX), - canvasHeight - locxAxisInPixels + 30, paint); - canvas.drawText("" + maxY, locyAxisInPixels - 65, canvasHeight - - (float) toPixelInt(canvasHeight, minY, maxY, maxY), paint); - - } - canvas.restore(); - } - - private int[] toPixel(float pixels, float min, float max, float[] value) { - double[] p = new double[value.length]; - int[] pInt = new int[value.length]; - - for (int i = 0; i < value.length; i++) { - p[i] = .1 * pixels + ((value[i] - min) / (max - min)) * .8 * pixels; - pInt[i] = (int) p[i]; - } - return (pInt); - } - - private void getAxis(float[] xValues, float[] yValues) { - - minX = -16f; - minY = -16f; - maxX = 16f; - maxY = 16f; - - if (minX >= 0) - locyAxis = minX; - else if (minX < 0 && maxX >= 0) - locyAxis = 0; - else - locyAxis = maxX; - - if (minY >= 0) - locxAxis = minY; - else if (minY < 0 && maxY >= 0) - locxAxis = 0; - else - locxAxis = maxY; - } - - private int toPixelInt(float pixels, float min, float max, float value) { - - double p; - int pInt; - p = .1 * pixels + ((value - min) / (max - min)) * .8 * pixels; - pInt = (int) p; - return (pInt); - } - - @Override - public boolean onTouchEvent(MotionEvent event) { - detector.onTouchEvent(event); - final int action = event.getAction(); - return true; - } - - private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { - @Override - public boolean onScale(ScaleGestureDetector detector) { - scaleFactor *= detector.getScaleFactor(); - scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM)); - invalidate(); - return true; - } - } -} - diff --git a/app/src/main/java/io/pslab/others/PreferenceManager.java b/app/src/main/java/io/pslab/others/PreferenceManager.java deleted file mode 100644 index d34f33dee..000000000 --- a/app/src/main/java/io/pslab/others/PreferenceManager.java +++ /dev/null @@ -1,34 +0,0 @@ -package io.pslab.others; - -import android.content.Context; -import android.content.SharedPreferences; - -/** - * Created by viveksb007 on 21/6/17. - */ - -public class PreferenceManager { - - private SharedPreferences sharedPreferences; - private SharedPreferences.Editor editor; - private Context context; - - private static final String preferenceName = "PSLAB"; - private static final String version = "version"; - - public PreferenceManager(Context context) { - this.context = context; - sharedPreferences = context.getSharedPreferences(preferenceName, Context.MODE_PRIVATE); - } - - public void setVersion(String version) { - editor = sharedPreferences.edit(); - editor.putString(version, version); - editor.apply(); - } - - public String getVersion() { - return sharedPreferences.getString(version, "none"); - } - -} diff --git a/app/src/main/java/io/pslab/others/ScienceLabCommon.java b/app/src/main/java/io/pslab/others/ScienceLabCommon.java deleted file mode 100644 index 8bd20b962..000000000 --- a/app/src/main/java/io/pslab/others/ScienceLabCommon.java +++ /dev/null @@ -1,56 +0,0 @@ -package io.pslab.others; - -import android.util.Log; - -import io.pslab.communication.CommunicationHandler; -import io.pslab.communication.ScienceLab; - -/** - * Created by viveksb007 on 8/5/17. - */ - -public class ScienceLabCommon { - - private static final String TAG = "ScienceLabCommon"; - private static ScienceLabCommon scienceLabCommon = null; - public static ScienceLab scienceLab; - public boolean connected = false; - public static boolean isWifiConnected = false; - private static String espBaseIP = ""; - - private ScienceLabCommon() { - } - - public boolean openDevice(CommunicationHandler communicationHandler) { - scienceLab = new ScienceLab(communicationHandler); - if (!scienceLab.isConnected()) { - Log.e(TAG, "Error in connection"); - return false; - } - connected = true; - return true; - } - - public static ScienceLabCommon getInstance() { - if (scienceLabCommon == null) { - scienceLabCommon = new ScienceLabCommon(); - } - return scienceLabCommon; - } - - public static String getEspIP() { - return espBaseIP; - } - - public static void setEspBaseIP(String espBaseIP) { - ScienceLabCommon.espBaseIP = espBaseIP; - } - - public static boolean isWifiConnected() { - return isWifiConnected; - } - - public static void setIsWifiConnected(boolean wifiConnected) { - isWifiConnected = wifiConnected; - } -} diff --git a/app/src/main/java/io/pslab/others/SwipeGestureDetector.java b/app/src/main/java/io/pslab/others/SwipeGestureDetector.java deleted file mode 100644 index 8b30a7ddb..000000000 --- a/app/src/main/java/io/pslab/others/SwipeGestureDetector.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.pslab.others; - -import android.view.GestureDetector; -import android.view.MotionEvent; -import android.view.View; - -import com.google.android.material.bottomsheet.BottomSheetBehavior; - -public class SwipeGestureDetector extends GestureDetector.SimpleOnGestureListener { - - private final BottomSheetBehavior bottomSheet; - - public SwipeGestureDetector(BottomSheetBehavior bt) { - bottomSheet = bt; - } - - @Override - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { - try { - switch (getDirection(e1.getX(), e1.getY(), e2.getX(), e2.getY())) { - case TOP: - if (bottomSheet.getState() == BottomSheetBehavior.STATE_COLLAPSED) - bottomSheet.setState(BottomSheetBehavior.STATE_EXPANDED); - if (bottomSheet.getState() == BottomSheetBehavior.STATE_HIDDEN) - bottomSheet.setState(BottomSheetBehavior.STATE_COLLAPSED); - return true; - case LEFT: - return true; - case DOWN: - if (bottomSheet.getState() == BottomSheetBehavior.STATE_EXPANDED) - bottomSheet.setState(BottomSheetBehavior.STATE_COLLAPSED); - if (bottomSheet.getState() == BottomSheetBehavior.STATE_COLLAPSED) - bottomSheet.setState(BottomSheetBehavior.STATE_HIDDEN); - return true; - case RIGHT: - return true; - default: - return false; - } - } catch (Exception e) { - return false; - } - } - - private Direction getDirection(float x1, float y1, float x2, float y2) { - double angle = Math.toDegrees(Math.atan2(y1 - y2, x2 - x1)); - if (angle > 45 && angle <= 135) - return Direction.TOP; - if (angle >= 135 && angle < 180 || angle < -135 && angle > -180) - return Direction.LEFT; - if (angle < -45 && angle >= -135) - return Direction.DOWN; - if (angle > -45 && angle <= 45) - return Direction.RIGHT; - return null; - } - - public enum Direction {TOP, RIGHT, LEFT, DOWN} -} diff --git a/app/src/main/java/io/pslab/others/ViewGroupUtils.java b/app/src/main/java/io/pslab/others/ViewGroupUtils.java deleted file mode 100644 index 42511943d..000000000 --- a/app/src/main/java/io/pslab/others/ViewGroupUtils.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.pslab.others; - -import android.view.View; -import android.view.ViewGroup; - -/** - * Created by akarshan on 7/15/17. - */ - -public class ViewGroupUtils { - - private static ViewGroup getParent(View view) { - return (ViewGroup) view.getParent(); - } - - private static void removeView(View view) { - ViewGroup parent = getParent(view); - if (parent != null) { - parent.removeView(view); - } - } - - public static void replaceView(View currentView, View newView) { - ViewGroup parent = getParent(currentView); - if (parent == null) { - return; - } - final int index = parent.indexOfChild(currentView); - removeView(currentView); - removeView(newView); - parent.addView(newView, index); - } -} \ No newline at end of file diff --git a/app/src/main/java/io/pslab/others/WaveGeneratorConstants.java b/app/src/main/java/io/pslab/others/WaveGeneratorConstants.java deleted file mode 100644 index 4e8a76a0d..000000000 --- a/app/src/main/java/io/pslab/others/WaveGeneratorConstants.java +++ /dev/null @@ -1,58 +0,0 @@ -package io.pslab.others; - -import java.util.HashMap; -import java.util.Map; - -import io.pslab.activity.WaveGeneratorActivity; -import io.pslab.activity.WaveGeneratorActivity.WaveConst; -import io.pslab.activity.WaveGeneratorActivity.WaveData; - -public final class WaveGeneratorConstants { - - public final static Map> wave = new HashMap<>(); - - static { - wave.put(WaveConst.WAVE1, new HashMap() {{ - put(WaveConst.FREQUENCY, WaveData.FREQ_MIN.getValue()); - put(WaveConst.WAVETYPE, WaveGeneratorActivity.SIN); - }}); - - wave.put(WaveConst.WAVE2, new HashMap() {{ - put(WaveConst.PHASE, WaveData.PHASE_MIN.getValue()); - put(WaveConst.FREQUENCY, WaveData.FREQ_MIN.getValue()); - put(WaveConst.WAVETYPE, WaveGeneratorActivity.SIN); - }}); - - wave.put(WaveConst.WAVETYPE, new HashMap<>()); - - wave.put(WaveConst.SQR1, new HashMap() {{ - put(WaveConst.FREQUENCY, WaveData.FREQ_MIN.getValue()); //common frequency for all pins(SQR1,SQR2,SQR3,SQR4) - put(WaveConst.DUTY, WaveData.DUTY_MIN.getValue()); - }}); - - wave.put(WaveConst.SQR2, new HashMap() {{ - put(WaveConst.FREQUENCY, WaveData.FREQ_MIN.getValue()); - put(WaveConst.PHASE, WaveData.PHASE_MIN.getValue()); - put(WaveConst.DUTY, WaveData.DUTY_MIN.getValue()); - }}); - - wave.put(WaveConst.SQR3, new HashMap() {{ - put(WaveConst.PHASE, WaveData.PHASE_MIN.getValue()); - put(WaveConst.DUTY, WaveData.DUTY_MIN.getValue()); - }}); - - wave.put(WaveConst.SQR4, new HashMap() {{ - put(WaveConst.PHASE, WaveData.PHASE_MIN.getValue()); - put(WaveConst.DUTY, WaveData.DUTY_MIN.getValue()); - }}); - } - - public static WaveConst mode_selected = WaveConst.SQUARE; - - public final static Map state = new HashMap() {{ - put("SQR1", 0); - put("SQR2", 0); - put("SQR3", 0); - put("SQR4", 0); - }}; -} diff --git a/app/src/main/java/io/pslab/others/ZoomLayout.java b/app/src/main/java/io/pslab/others/ZoomLayout.java deleted file mode 100644 index 9bfa25ff6..000000000 --- a/app/src/main/java/io/pslab/others/ZoomLayout.java +++ /dev/null @@ -1,134 +0,0 @@ -package io.pslab.others; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.util.AttributeSet; -import android.util.Log; -import android.view.MotionEvent; -import android.view.ScaleGestureDetector; -import android.view.View; -import android.widget.RelativeLayout; - -public class ZoomLayout extends RelativeLayout implements ScaleGestureDetector.OnScaleGestureListener { - - private static final float MIN_ZOOM = 1.0f; - private static final float MAX_ZOOM = 4.0f; - private Mode mode = Mode.NONE; - private float scale = 1.0f; - private float lastScaleFactor = 0f; - private float startX = 0f; - private float startY = 0f; - private float dx = 0f; - private float dy = 0f; - private float prevDx = 0f; - private float prevDy = 0f; - - public ZoomLayout(Context context) { - super(context); - init(context); - } - - public ZoomLayout(Context context, AttributeSet attrs) { - super(context, attrs); - init(context); - } - - public ZoomLayout(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(context); - } - - @SuppressLint("ClickableViewAccessibility") - public void init(Context context) { - final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(context, this); - this.setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(View view, MotionEvent motionEvent) { - switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) { - case MotionEvent.ACTION_DOWN: - if (scale > MIN_ZOOM) { - mode = Mode.DRAG; - startX = motionEvent.getX() - prevDx; - startY = motionEvent.getY() - prevDy; - } - break; - case MotionEvent.ACTION_MOVE: - if (mode == Mode.DRAG) { - dx = motionEvent.getX() - startX; - dy = motionEvent.getY() - startY; - } - break; - case MotionEvent.ACTION_POINTER_DOWN: - mode = Mode.ZOOM; - break; - case MotionEvent.ACTION_POINTER_UP: - mode = Mode.DRAG; - break; - case MotionEvent.ACTION_UP: - mode = Mode.NONE; - prevDx = dx; - prevDy = dy; - break; - default: - mode = Mode.NONE; - prevDx = dx; - prevDy = dy; - break; - } - scaleDetector.onTouchEvent(motionEvent); - - if ((mode == Mode.DRAG && scale >= MIN_ZOOM) || mode == Mode.ZOOM) { - getParent().requestDisallowInterceptTouchEvent(true); - float maxDx = (child().getWidth() - (child().getWidth() / scale)) / 2 * scale; - float maxDy = (child().getHeight() - (child().getHeight() / scale)) * scale; - dx = Math.min(Math.max(dx, -maxDx), maxDx); - dy = Math.min(Math.max(dy, -maxDy), maxDy); - applyScaleAndTranslation(); - } - return true; - } - }); - } - - @Override - public boolean onScaleBegin(ScaleGestureDetector scaleDetector) { - return true; - } - - // ScaleGestureDetector - @Override - public boolean onScale(ScaleGestureDetector scaleDetector) { - float scaleFactor = scaleDetector.getScaleFactor(); - Log.i("Zoom Factor", String.valueOf(scaleFactor)); - if (lastScaleFactor == 0 || (Math.signum(scaleFactor) == Math.signum(lastScaleFactor))) { - scale *= scaleFactor; - scale = Math.max(MIN_ZOOM, Math.min(scale, MAX_ZOOM)); - lastScaleFactor = scaleFactor; - } else { - lastScaleFactor = 0; - } - return true; - } - - @Override - public void onScaleEnd(ScaleGestureDetector scaleDetector) { - - } - - private void applyScaleAndTranslation() { - child().setScaleX(scale); - child().setScaleY(scale); - child().setTranslationX(dx); - child().setTranslationY(dy); - } - - private View child() { - return getChildAt(0); - } - - private enum Mode { - NONE, - DRAG, - ZOOM - } -} diff --git a/app/src/main/java/io/pslab/receivers/USBDetachReceiver.java b/app/src/main/java/io/pslab/receivers/USBDetachReceiver.java deleted file mode 100644 index d4d562591..000000000 --- a/app/src/main/java/io/pslab/receivers/USBDetachReceiver.java +++ /dev/null @@ -1,68 +0,0 @@ -package io.pslab.receivers; - -import android.app.Activity; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.hardware.usb.UsbDevice; -import android.hardware.usb.UsbManager; -import com.google.android.material.snackbar.Snackbar; -import androidx.fragment.app.Fragment; - -import android.util.Log; - -import io.pslab.R; -import io.pslab.activity.MainActivity; -import io.pslab.activity.PowerSourceActivity; -import io.pslab.communication.PacketHandler; -import io.pslab.fragment.HomeFragment; -import io.pslab.others.CustomSnackBar; -import io.pslab.others.ScienceLabCommon; - -/** - * Created by viveksb007 on 21/6/17. - */ - -public class USBDetachReceiver extends BroadcastReceiver { - - private final String TAG = this.getClass().getSimpleName(); - private Context activityContext; - - public USBDetachReceiver(){} - public USBDetachReceiver(Context context) { - this.activityContext = context; - } - - @Override - public void onReceive(Context context, Intent intent) { - try { - if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(intent.getAction())) { - UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); - if (device != null) { - ScienceLabCommon.scienceLab.close(); - // Clear saved values in Power Source Instrument - context.getSharedPreferences(PowerSourceActivity.POWER_PREFERENCES, Context.MODE_PRIVATE).edit().clear().apply(); - CustomSnackBar.showSnackBar(((Activity)context).findViewById(android.R.id.content), - "USB Device Disconnected",null,null, Snackbar.LENGTH_SHORT); - - PacketHandler.version = ""; - - if (activityContext != null) { - MainActivity mainActivity = (MainActivity) activityContext; - Fragment currentFragment = mainActivity.getSupportFragmentManager().findFragmentById(R.id.frame); - if (currentFragment instanceof HomeFragment) { - mainActivity.getSupportFragmentManager().beginTransaction().replace(R.id.frame, HomeFragment.newInstance(false, false)).commitAllowingStateLoss(); - } - mainActivity.PSLabisConnected = false; - mainActivity.invalidateOptionsMenu(); - } - } else { - Log.v(TAG, "USB Device is null"); - } - } - } catch (IllegalStateException ignored){ - - } - - } -} diff --git a/app/src/main/java/io/pslab/sensors/SensorADS1115.java b/app/src/main/java/io/pslab/sensors/SensorADS1115.java deleted file mode 100644 index 5be642de0..000000000 --- a/app/src/main/java/io/pslab/sensors/SensorADS1115.java +++ /dev/null @@ -1,302 +0,0 @@ -package io.pslab.sensors; - -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.View; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.IOException; -import java.util.ArrayList; - -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.ADS1115; -import io.pslab.others.ScienceLabCommon; - -public class SensorADS1115 extends AppCompatActivity { - private static int counter; - private final Object lock = new Object(); - private ScienceLab scienceLab; - private SensorADS1115.SensorDataFetch sensorDataFetch; - private TextView tvSensorADS1115; - private LineChart mChart; - private long startTime; - private int flag; - private ArrayList entries; - private RelativeLayout sensorDock; - private CheckBox indefiniteSamplesCheckBox; - private EditText samplesEditBox; - private SeekBar timeGapSeekbar; - private TextView timeGapLabel; - private ImageButton playPauseButton; - private boolean play; - private boolean runIndefinitely; - private int timeGap; - - private ADS1115 sensorADS1115; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.sensor_ads1115); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.ads1115); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - sensorDock = findViewById(R.id.sensor_control_dock_layout); - indefiniteSamplesCheckBox = findViewById(R.id.checkBox_samples_sensor); - samplesEditBox = findViewById(R.id.editBox_samples_sensors); - timeGapSeekbar = findViewById(R.id.seekBar_timegap_sensor); - timeGapLabel = findViewById(R.id.tv_timegap_label); - playPauseButton = findViewById(R.id.imageButton_play_pause_sensor); - setSensorDock(); - sensorDock.setVisibility(View.VISIBLE); - - scienceLab = ScienceLabCommon.scienceLab; - I2C i2c = scienceLab.i2c; - entries = new ArrayList<>(); - try { - sensorADS1115 = new ADS1115(i2c); - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - - Runnable runnable = new Runnable() { - @Override - public void run() { - while (true) { - if (scienceLab.isConnected() && shouldPlay()) { - sensorDataFetch = new SensorADS1115.SensorDataFetch(); - sensorDataFetch.execute(); - if (flag == 0) { - startTime = System.currentTimeMillis(); - flag = 1; - } - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - try { - Thread.sleep(timeGap); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - }; - new Thread(runnable).start(); - - tvSensorADS1115 = findViewById(R.id.tv_sensor_ads1115); - mChart = findViewById(R.id.chart_sensor_ads); - - Spinner spinnerSensorADS1115Gain = findViewById(R.id.spinner_sensor_ads1115_gain); - Spinner spinnerSensorADS1115Channel = findViewById(R.id.spinner_sensor_ads1115_channel); - Spinner spinnerSensorADS1115Rate = findViewById(R.id.spinner_sensor_ads1115_rate); - - if (sensorADS1115 != null) { - sensorADS1115.setGain(spinnerSensorADS1115Gain.getSelectedItem().toString()); - } - if (sensorADS1115 != null) { - sensorADS1115.setChannel(spinnerSensorADS1115Channel.getSelectedItem().toString()); - } - if (sensorADS1115 != null) { - sensorADS1115.setDataRate(Integer.parseInt(spinnerSensorADS1115Rate.getSelectedItem().toString())); - } - XAxis x = mChart.getXAxis(); - YAxis y = mChart.getAxisLeft(); - YAxis y2 = mChart.getAxisRight(); - - mChart.setTouchEnabled(true); - mChart.setHighlightPerDragEnabled(true); - mChart.setDragEnabled(true); - mChart.setScaleEnabled(true); - mChart.setDrawGridBackground(false); - mChart.setPinchZoom(true); - mChart.setScaleYEnabled(false); - mChart.setBackgroundColor(Color.BLACK); - mChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mChart.setData(data); - - Legend l = mChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(6.15f); - y.setAxisMinimum(-6.15f); - y.setDrawGridLines(true); - y.setLabelCount(10); - - y2.setDrawGridLines(false); - } - - private boolean shouldPlay() { - if (play) { - if (indefiniteSamplesCheckBox.isChecked()) - return true; - else if (counter >= 0) { - counter--; - return true; - } else { - play = false; - return false; - } - } else { - return false; - } - } - - private void setSensorDock() { - play = false; - runIndefinitely = true; - timeGap = 100; - final int step = 1; - final int max = 1000; - final int min = 100; - - playPauseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (play && scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else if (!scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else { - playPauseButton.setImageResource(R.drawable.circle_pause_button); - play = true; - if (!indefiniteSamplesCheckBox.isChecked()) { - counter = Integer.parseInt(samplesEditBox.getText().toString()); - } - } - } - }); - sensorDock.setVisibility(View.VISIBLE); - - indefiniteSamplesCheckBox.setChecked(true); - samplesEditBox.setEnabled(false); - indefiniteSamplesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - runIndefinitely = true; - samplesEditBox.setEnabled(false); - } else { - runIndefinitely = false; - samplesEditBox.setEnabled(true); - } - } - }); - - timeGapSeekbar.setMax((max - min) / step); - timeGapSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - timeGap = min + (progress * step); - timeGapLabel.setText(timeGap + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - } - - private class SensorDataFetch extends AsyncTask { - - private int dataADS1115; - private long timeElapsed; - - @Override - protected Void doInBackground(Void... params) { - try { - if (sensorADS1115 != null) { - dataADS1115 = sensorADS1115.getRaw(); - } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - entries.add(new Entry((float) timeElapsed, dataADS1115)); - - return null; - } - - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - tvSensorADS1115.setText(String.valueOf(dataADS1115)); - - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.bx)); - dataSet.setDrawCircles(true); - LineData data = new LineData(dataSet); - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(10); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - samplesEditBox.setText(String.valueOf(counter)); - if (counter == 0 && !runIndefinitely) { - play = false; - playPauseButton.setImageResource(R.drawable.circle_play_button); - } - synchronized (lock) { - lock.notify(); - } - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/sensors/SensorAPDS9960.java b/app/src/main/java/io/pslab/sensors/SensorAPDS9960.java deleted file mode 100644 index 81717129d..000000000 --- a/app/src/main/java/io/pslab/sensors/SensorAPDS9960.java +++ /dev/null @@ -1,393 +0,0 @@ -package io.pslab.sensors; - -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.util.Log; -import android.view.MenuItem; -import android.view.View; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.IOException; -import java.util.ArrayList; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.APDS9960; -import io.pslab.others.ScienceLabCommon; - -public class SensorAPDS9960 extends AppCompatActivity { - private static final String TAG = SensorAPDS9960.class.getSimpleName(); - private static int counter; - private final Object lock = new Object(); - private ScienceLab scienceLab; - private SensorAPDS9960.SensorDataFetch sensorDataFetch; - private TextView tvSensorAPDS9960Red; - private TextView tvSensorAPDS9960Green; - private TextView tvSensorAPDS9960Blue; - private TextView tvSensorAPDS9960Clear; - private TextView tvSensorAPDS9960Proximity; - private TextView tvSensorAPDS9960Gesture; - private APDS9960 sensorAPDS9960; - private LineChart mChartLux; - private LineChart mChartProximity; - private long startTime; - private int flag; - private ArrayList entriesLux; - private ArrayList entriesProximity; - private RelativeLayout sensorDock; - private CheckBox indefiniteSamplesCheckBox; - private EditText samplesEditBox; - private SeekBar timeGapSeekbar; - private TextView timeGapLabel; - private ImageButton playPauseButton; - private Spinner spinnerMode; - private boolean play; - private boolean runIndefinitely; - private int timeGap; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.sensor_apds9960); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.apds9960); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - sensorDock = findViewById(R.id.sensor_control_dock_layout); - indefiniteSamplesCheckBox = findViewById(R.id.checkBox_samples_sensor); - samplesEditBox = findViewById(R.id.editBox_samples_sensors); - timeGapSeekbar = findViewById(R.id.seekBar_timegap_sensor); - timeGapLabel = findViewById(R.id.tv_timegap_label); - playPauseButton = findViewById(R.id.imageButton_play_pause_sensor); - setSensorDock(); - sensorDock.setVisibility(View.VISIBLE); - spinnerMode = findViewById(R.id.spinner_sensor_apds9960); - - scienceLab = ScienceLabCommon.scienceLab; - I2C i2c = scienceLab.i2c; - try { - sensorAPDS9960 = new APDS9960(i2c, scienceLab); - } catch (Exception e) { - Log.e(TAG, "Sensor initialization failed."); - } - - entriesLux = new ArrayList<>(); - entriesProximity = new ArrayList<>(); - - Runnable runnable = new Runnable() { - @Override - public void run() { - while (true) { - if (scienceLab.isConnected() && shouldPlay()) { - sensorDataFetch = new SensorAPDS9960.SensorDataFetch(); - sensorDataFetch.execute(); - - if (flag == 0) { - startTime = System.currentTimeMillis(); - flag = 1; - } - - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - Log.e(TAG, "Thread interrupted while waiting."); - } - } - try { - Thread.sleep(timeGap); - } catch (InterruptedException e) { - Log.e(TAG, "Thread interrupted during sleep."); - } - } - } - } - }; - new Thread(runnable).start(); - - tvSensorAPDS9960Red = findViewById(R.id.tv_sensor_apds9960_red); - tvSensorAPDS9960Green = findViewById(R.id.tv_sensor_apds9960_green); - tvSensorAPDS9960Blue = findViewById(R.id.tv_sensor_apds9960_blue); - tvSensorAPDS9960Clear = findViewById(R.id.tv_sensor_apds9960_clear); - tvSensorAPDS9960Proximity = findViewById(R.id.tv_sensor_apds9960_proximity); - tvSensorAPDS9960Gesture = findViewById(R.id.tv_sensor_apds9960_gesture); - mChartLux = findViewById(R.id.chart_sensor_apds9960_lux); - mChartProximity = findViewById(R.id.chart_sensor_apds9960_proximity); - - XAxis xLux = mChartLux.getXAxis(); - YAxis yLux = mChartLux.getAxisLeft(); - YAxis yLux2 = mChartLux.getAxisRight(); - - XAxis xProximity = mChartProximity.getXAxis(); - YAxis yProximity = mChartProximity.getAxisLeft(); - YAxis yProximity2 = mChartProximity.getAxisRight(); - - mChartLux.setTouchEnabled(true); - mChartLux.setHighlightPerDragEnabled(true); - mChartLux.setDragEnabled(true); - mChartLux.setScaleEnabled(true); - mChartLux.setDrawGridBackground(false); - mChartLux.setPinchZoom(true); - mChartLux.setScaleYEnabled(false); - mChartLux.setBackgroundColor(Color.BLACK); - mChartLux.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartLux.setData(data); - - Legend l = mChartLux.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - xLux.setTextColor(Color.WHITE); - xLux.setDrawGridLines(true); - xLux.setAvoidFirstLastClipping(true); - - yLux.setTextColor(Color.WHITE); - yLux.setAxisMaximum(10000f); - yLux.setAxisMinimum(0); - yLux.setDrawGridLines(true); - yLux.setLabelCount(10); - - yLux2.setDrawGridLines(false); - - mChartProximity.setTouchEnabled(true); - mChartProximity.setHighlightPerDragEnabled(true); - mChartProximity.setDragEnabled(true); - mChartProximity.setScaleEnabled(true); - mChartProximity.setDrawGridBackground(false); - mChartProximity.setPinchZoom(true); - mChartProximity.setScaleYEnabled(false); - mChartProximity.setBackgroundColor(Color.BLACK); - mChartProximity.getDescription().setEnabled(false); - - LineData data2 = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartProximity.setData(data2); - - Legend l2 = mChartProximity.getLegend(); - l2.setForm(Legend.LegendForm.LINE); - l2.setTextColor(Color.WHITE); - - xProximity.setTextColor(Color.WHITE); - xProximity.setDrawGridLines(true); - xProximity.setAvoidFirstLastClipping(true); - - yProximity.setTextColor(Color.WHITE); - yProximity.setAxisMaximum(256f); - yProximity.setAxisMinimum(0f); - yProximity.setDrawGridLines(true); - yProximity.setLabelCount(10); - - yProximity2.setDrawGridLines(false); - } - - private boolean shouldPlay() { - if (play) { - if (indefiniteSamplesCheckBox.isChecked()) - return true; - else if (counter >= 0) { - counter--; - return true; - } else { - play = false; - return false; - } - } else { - return false; - } - } - - private void setSensorDock() { - play = false; - runIndefinitely = true; - timeGap = 100; - final int step = 1; - final int max = 1000; - final int min = 100; - - playPauseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (play && scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else if (!scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else { - playPauseButton.setImageResource(R.drawable.circle_pause_button); - play = true; - if (!indefiniteSamplesCheckBox.isChecked()) { - counter = Integer.parseInt(samplesEditBox.getText().toString()); - } - } - } - }); - sensorDock.setVisibility(View.VISIBLE); - - indefiniteSamplesCheckBox.setChecked(true); - samplesEditBox.setEnabled(false); - indefiniteSamplesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - runIndefinitely = true; - samplesEditBox.setEnabled(false); - } else { - runIndefinitely = false; - samplesEditBox.setEnabled(true); - } - } - }); - - timeGapSeekbar.setMax((max - min) / step); - timeGapSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - timeGap = min + (progress * step); - timeGapLabel.setText(timeGap + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - // Do nothing - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - // Do nothing - } - }); - } - - private class SensorDataFetch extends AsyncTask { - - private int[] dataAPDS9960Color; - private double dataAPDS9960Lux; - private int dataAPDS9960Proximity; - private int dataAPDS9960Gesture; - private long timeElapsed; - - @Override - protected Void doInBackground(Void... params) { - try { - if (sensorAPDS9960 != null) { - if (spinnerMode.getSelectedItemPosition() == 0) { - sensorAPDS9960.enableGesture(false); - sensorAPDS9960.enableColor(true); - sensorAPDS9960.enableProximity(true); - dataAPDS9960Color = sensorAPDS9960.getColorData(); - dataAPDS9960Lux = (-0.32466 * dataAPDS9960Color[0]) + (1.57837 * dataAPDS9960Color[1]) + (-0.73191 * dataAPDS9960Color[2]); - dataAPDS9960Proximity = sensorAPDS9960.getProximity(); - } else { - sensorAPDS9960.enableColor(false); - sensorAPDS9960.enableGesture(true); - sensorAPDS9960.enableProximity(true); - dataAPDS9960Gesture = sensorAPDS9960.getGesture(); - } - } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - entriesLux.add(new Entry((float) timeElapsed, (float) dataAPDS9960Lux)); - entriesProximity.add(new Entry((float) timeElapsed, dataAPDS9960Proximity)); - return null; - } - - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (spinnerMode.getSelectedItemPosition() == 0) { - tvSensorAPDS9960Red.setText(DataFormatter.formatDouble(dataAPDS9960Color[0], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorAPDS9960Green.setText(DataFormatter.formatDouble(dataAPDS9960Color[1], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorAPDS9960Blue.setText(DataFormatter.formatDouble(dataAPDS9960Color[2], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorAPDS9960Clear.setText(DataFormatter.formatDouble(dataAPDS9960Color[3], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorAPDS9960Proximity.setText(DataFormatter.formatDouble(dataAPDS9960Proximity, DataFormatter.HIGH_PRECISION_FORMAT)); - - LineDataSet dataSet1 = new LineDataSet(entriesLux, getString(R.string.light_lux)); - LineDataSet dataSet2 = new LineDataSet(entriesProximity, getString(R.string.proximity)); - - dataSet1.setDrawCircles(true); - dataSet2.setDrawCircles(true); - - LineData data = new LineData(dataSet1); - mChartLux.setData(data); - mChartLux.notifyDataSetChanged(); - mChartLux.setVisibleXRangeMaximum(10); - mChartLux.moveViewToX(data.getEntryCount()); - mChartLux.invalidate(); - - LineData data2 = new LineData(dataSet2); - mChartProximity.setData(data2); - mChartProximity.notifyDataSetChanged(); - mChartProximity.setVisibleXRangeMaximum(10); - mChartProximity.moveViewToX(data2.getEntryCount()); - mChartProximity.invalidate(); - } else { - switch (dataAPDS9960Gesture) { - case 1: - tvSensorAPDS9960Gesture.setText(R.string.up); - break; - case 2: - tvSensorAPDS9960Gesture.setText(R.string.down); - break; - case 3: - tvSensorAPDS9960Gesture.setText(R.string.left); - break; - case 4: - tvSensorAPDS9960Gesture.setText(R.string.right); - break; - default: - break; - } - } - - samplesEditBox.setText(String.valueOf(counter)); - if (counter == 0 && !runIndefinitely) { - play = false; - playPauseButton.setImageResource(R.drawable.circle_play_button); - } - synchronized (lock) { - lock.notify(); - } - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/sensors/SensorBMP180.java b/app/src/main/java/io/pslab/sensors/SensorBMP180.java deleted file mode 100644 index 449366240..000000000 --- a/app/src/main/java/io/pslab/sensors/SensorBMP180.java +++ /dev/null @@ -1,400 +0,0 @@ -package io.pslab.sensors; - -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.View; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.IOException; -import java.util.ArrayList; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.BMP180; -import io.pslab.others.ScienceLabCommon; - -/** - * Created by Harsh on 6/6/18. - */ - -public class SensorBMP180 extends AppCompatActivity { - private static int counter; - private final Object lock = new Object(); - private ScienceLab scienceLab; - private SensorBMP180.SensorDataFetch sensorDataFetch; - private TextView tvSensorBMP180Temp; - private TextView tvSensorBMP180Altitude; - private TextView tvSensorBMP180Pressure; - private BMP180 sensorBMP180; - private LineChart mChartTemperature; - private LineChart mChartAltitude; - private LineChart mChartPressure; - private long startTime; - private int flag; - private ArrayList entriesTemperature; - private ArrayList entriesAltitude; - private ArrayList entriesPressure; - private RelativeLayout sensorDock; - private CheckBox indefiniteSamplesCheckBox; - private EditText samplesEditBox; - private SeekBar timeGapSeekbar; - private TextView timeGapLabel; - private ImageButton playPauseButton; - private boolean play; - private boolean runIndefinitely; - private int timeGap; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.sensor_bmp180); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.bmp180); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - sensorDock = findViewById(R.id.sensor_control_dock_layout); - indefiniteSamplesCheckBox = findViewById(R.id.checkBox_samples_sensor); - samplesEditBox = findViewById(R.id.editBox_samples_sensors); - timeGapSeekbar = findViewById(R.id.seekBar_timegap_sensor); - timeGapLabel = findViewById(R.id.tv_timegap_label); - playPauseButton = findViewById(R.id.imageButton_play_pause_sensor); - setSensorDock(); - sensorDock.setVisibility(View.VISIBLE); - - scienceLab = ScienceLabCommon.scienceLab; - I2C i2c = scienceLab.i2c; - try { - sensorBMP180 = new BMP180(i2c, scienceLab); - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - - Runnable runnable = new Runnable() { - @Override - public void run() { - while (true) { - if (scienceLab.isConnected() && shouldPlay()) { - sensorDataFetch = new SensorBMP180.SensorDataFetch(); - sensorDataFetch.execute(); - - if (flag == 0) { - startTime = System.currentTimeMillis(); - flag = 1; - } - - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - try { - Thread.sleep(timeGap); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - } - } - }; - new Thread(runnable).start(); - - tvSensorBMP180Temp = findViewById(R.id.tv_sensor_bmp180_temp); - tvSensorBMP180Altitude = findViewById(R.id.tv_sensor_bmp180_altitude); - tvSensorBMP180Pressure = findViewById(R.id.tv_sensor_bmp180_pressure); - - mChartTemperature = findViewById(R.id.chart_temp_bmp180); - mChartAltitude = findViewById(R.id.chart_alt_bmp180); - mChartPressure = findViewById(R.id.chart_pre_bmp180); - - XAxis xTemperature = mChartTemperature.getXAxis(); - YAxis yTemperature = mChartTemperature.getAxisLeft(); - YAxis yTemperature2 = mChartTemperature.getAxisRight(); - - XAxis xAltitude = mChartAltitude.getXAxis(); - YAxis yAltitude = mChartAltitude.getAxisLeft(); - YAxis yAltitude2 = mChartAltitude.getAxisRight(); - - XAxis xPressure = mChartPressure.getXAxis(); - YAxis yPressure = mChartPressure.getAxisLeft(); - YAxis yPressure2 = mChartPressure.getAxisRight(); - - entriesTemperature = new ArrayList<>(); - entriesAltitude = new ArrayList<>(); - entriesPressure = new ArrayList<>(); - - mChartTemperature.setTouchEnabled(true); - mChartTemperature.setHighlightPerDragEnabled(true); - mChartTemperature.setDragEnabled(true); - mChartTemperature.setScaleEnabled(true); - mChartTemperature.setDrawGridBackground(false); - mChartTemperature.setPinchZoom(true); - mChartTemperature.setScaleYEnabled(false); - mChartTemperature.setBackgroundColor(Color.BLACK); - mChartTemperature.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartTemperature.setData(data); - - Legend l = mChartTemperature.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - xTemperature.setTextColor(Color.WHITE); - xTemperature.setDrawGridLines(true); - xTemperature.setAvoidFirstLastClipping(true); - - yTemperature.setTextColor(Color.WHITE); - yTemperature.setAxisMaximum(70f); - yTemperature.setAxisMinimum(0f); - yTemperature.setDrawGridLines(true); - yTemperature.setLabelCount(10); - - yTemperature2.setDrawGridLines(false); - - mChartAltitude.setTouchEnabled(true); - mChartAltitude.setHighlightPerDragEnabled(true); - mChartAltitude.setDragEnabled(true); - mChartAltitude.setScaleEnabled(true); - mChartAltitude.setDrawGridBackground(false); - mChartAltitude.setPinchZoom(true); - mChartAltitude.setScaleYEnabled(false); - mChartAltitude.setBackgroundColor(Color.BLACK); - mChartAltitude.getDescription().setEnabled(false); - - LineData data2 = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartAltitude.setData(data2); - - Legend l2 = mChartAltitude.getLegend(); - l2.setForm(Legend.LegendForm.LINE); - l2.setTextColor(Color.WHITE); - - xAltitude.setTextColor(Color.WHITE); - xAltitude.setDrawGridLines(true); - xAltitude.setAvoidFirstLastClipping(true); - - yAltitude.setTextColor(Color.WHITE); - yAltitude.setAxisMaximum(3000f); - yAltitude.setAxisMinimum(0f); - yAltitude.setDrawGridLines(true); - yAltitude.setLabelCount(10); - - yAltitude2.setDrawGridLines(false); - - mChartPressure.setTouchEnabled(true); - mChartPressure.setHighlightPerDragEnabled(true); - mChartPressure.setDragEnabled(true); - mChartPressure.setScaleEnabled(true); - mChartPressure.setDrawGridBackground(false); - mChartPressure.setPinchZoom(true); - mChartPressure.setScaleYEnabled(false); - mChartPressure.setBackgroundColor(Color.BLACK); - mChartPressure.getDescription().setEnabled(false); - - LineData data3 = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartTemperature.setData(data3); - - Legend l3 = mChartTemperature.getLegend(); - l3.setForm(Legend.LegendForm.LINE); - l3.setTextColor(Color.WHITE); - - xPressure.setTextColor(Color.WHITE); - xPressure.setDrawGridLines(true); - xPressure.setAvoidFirstLastClipping(true); - - yPressure.setTextColor(Color.WHITE); - yPressure.setAxisMaximum(1000000f); - yPressure.setAxisMinimum(0f); - yPressure.setDrawGridLines(true); - yPressure.setLabelCount(10); - - yPressure2.setDrawGridLines(false); - } - - private boolean shouldPlay() { - if (play && scienceLab.isConnected()) { - if (indefiniteSamplesCheckBox.isChecked()) - return true; - else if (counter >= 0) { - counter--; - return true; - } else { - play = false; - return false; - } - } else { - return false; - } - } - - private void setSensorDock() { - play = false; - runIndefinitely = true; - timeGap = 100; - final int step = 1; - final int max = 1000; - final int min = 100; - - playPauseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (play && scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else if (!scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else { - playPauseButton.setImageResource(R.drawable.circle_pause_button); - play = true; - if (!indefiniteSamplesCheckBox.isChecked()) { - counter = Integer.parseInt(samplesEditBox.getText().toString()); - } - } - } - }); - sensorDock.setVisibility(View.VISIBLE); - - indefiniteSamplesCheckBox.setChecked(true); - samplesEditBox.setEnabled(false); - indefiniteSamplesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - runIndefinitely = true; - samplesEditBox.setEnabled(false); - } else { - runIndefinitely = false; - samplesEditBox.setEnabled(true); - } - } - }); - - timeGapSeekbar.setMax((max - min) / step); - timeGapSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - timeGap = min + (progress * step); - timeGapLabel.setText(timeGap + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - } - - private class SensorDataFetch extends AsyncTask { - - private double[] dataBMP180 = new double[3]; - private long timeElapsed; - - @Override - protected Void doInBackground(Void... params) { - try { - if (sensorBMP180 != null && scienceLab.isConnected()) { - dataBMP180 = sensorBMP180.getRaw(); - } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - entriesTemperature.add(new Entry((float) timeElapsed, (float) dataBMP180[0])); - entriesAltitude.add(new Entry((float) timeElapsed, (float) dataBMP180[1])); - entriesPressure.add(new Entry((float) timeElapsed, (float) dataBMP180[2])); - return null; - } - - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - tvSensorBMP180Temp.setText(DataFormatter.formatDouble(dataBMP180[0], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorBMP180Altitude.setText(DataFormatter.formatDouble(dataBMP180[1], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorBMP180Pressure.setText(DataFormatter.formatDouble(dataBMP180[2], DataFormatter.HIGH_PRECISION_FORMAT)); - - LineDataSet dataSet1 = new LineDataSet(entriesTemperature, getString(R.string.temperature)); - LineDataSet dataSet2 = new LineDataSet(entriesAltitude, getString(R.string.altitude)); - LineDataSet dataSet3 = new LineDataSet(entriesPressure, getString(R.string.pressure)); - - dataSet1.setColor(Color.BLUE); - dataSet2.setColor(Color.GREEN); - dataSet3.setColor(Color.RED); - - LineData data = new LineData(dataSet1); - mChartTemperature.setData(data); - mChartTemperature.notifyDataSetChanged(); - mChartTemperature.setVisibleXRangeMaximum(10); - mChartTemperature.moveViewToX(data.getEntryCount()); - mChartTemperature.invalidate(); - - LineData data2 = new LineData(dataSet2); - mChartAltitude.setData(data2); - mChartAltitude.notifyDataSetChanged(); - mChartAltitude.setVisibleXRangeMaximum(10); - mChartAltitude.moveViewToX(data.getEntryCount()); - mChartAltitude.invalidate(); - - LineData data3 = new LineData(dataSet3); - mChartPressure.setData(data3); - mChartPressure.notifyDataSetChanged(); - mChartPressure.setVisibleXRangeMaximum(10); - mChartPressure.moveViewToX(data.getEntryCount()); - mChartPressure.invalidate(); - samplesEditBox.setText(String.valueOf(counter)); - if (counter == 0 && !runIndefinitely) { - play = false; - playPauseButton.setImageResource(R.drawable.circle_play_button); - } - synchronized (lock) { - lock.notify(); - } - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/sensors/SensorCCS811.java b/app/src/main/java/io/pslab/sensors/SensorCCS811.java deleted file mode 100644 index c2218009e..000000000 --- a/app/src/main/java/io/pslab/sensors/SensorCCS811.java +++ /dev/null @@ -1,349 +0,0 @@ -package io.pslab.sensors; - -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.View; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.IOException; -import java.util.ArrayList; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.CCS811; -import io.pslab.communication.sensors.SHT21; -import io.pslab.others.ScienceLabCommon; - -public class SensorCCS811 extends AppCompatActivity { - private static int counter; - private final Object lock = new Object(); - private ScienceLab scienceLab; - private SensorCCS811.SensorDataFetch sensorDataFetch; - private TextView tvSensorCCS811eCO2; - private TextView tvSensorCCS811TVOC; - private CCS811 sensorCCS811; - private LineChart mCharteCO2; - private LineChart mChartTVOC; - private long startTime; - private int flag; - private ArrayList entrieseCO2; - private ArrayList entriesTVOC; - private RelativeLayout sensorDock; - private CheckBox indefiniteSamplesCheckBox; - private EditText samplesEditBox; - private SeekBar timeGapSeekbar; - private TextView timeGapLabel; - private ImageButton playPauseButton; - private boolean play; - private boolean runIndefinitely; - private int timeGap; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.sensor_ccs811); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.ccs811); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - sensorDock = findViewById(R.id.sensor_control_dock_layout); - indefiniteSamplesCheckBox = findViewById(R.id.checkBox_samples_sensor); - samplesEditBox = findViewById(R.id.editBox_samples_sensors); - timeGapSeekbar = findViewById(R.id.seekBar_timegap_sensor); - timeGapLabel = findViewById(R.id.tv_timegap_label); - playPauseButton = findViewById(R.id.imageButton_play_pause_sensor); - setSensorDock(); - sensorDock.setVisibility(View.VISIBLE); - - scienceLab = ScienceLabCommon.scienceLab; - I2C i2c = scienceLab.i2c; - try { - sensorCCS811 = new CCS811(i2c, scienceLab); - } catch (Exception e) { - e.printStackTrace(); - } - - entrieseCO2 = new ArrayList<>(); - entriesTVOC = new ArrayList<>(); - - Runnable runnable = new Runnable() { - @Override - public void run() { - while (true) { - if (scienceLab.isConnected() && shouldPlay()) { - sensorDataFetch = new SensorCCS811.SensorDataFetch(); - sensorDataFetch.execute(); - - if (flag == 0) { - startTime = System.currentTimeMillis(); - flag = 1; - } - - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - try { - Thread.sleep(timeGap); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - }; - new Thread(runnable).start(); - - tvSensorCCS811eCO2 = findViewById(R.id.tv_sensor_ccs811_eCO2); - tvSensorCCS811TVOC = findViewById(R.id.tv_sensor_ccs811_TVOC); - mCharteCO2 = findViewById(R.id.chart_eCO2_ccs811); - mChartTVOC = findViewById(R.id.chart_TVOC_ccs811); - - XAxis xeCO2 = mCharteCO2.getXAxis(); - YAxis yeCO2 = mCharteCO2.getAxisLeft(); - YAxis yeCO22 = mCharteCO2.getAxisRight(); - - XAxis xTVOC = mChartTVOC.getXAxis(); - YAxis yTVOC = mChartTVOC.getAxisLeft(); - YAxis yTVOC2 = mChartTVOC.getAxisRight(); - - mCharteCO2.setTouchEnabled(true); - mCharteCO2.setHighlightPerDragEnabled(true); - mCharteCO2.setDragEnabled(true); - mCharteCO2.setScaleEnabled(true); - mCharteCO2.setDrawGridBackground(false); - mCharteCO2.setPinchZoom(true); - mCharteCO2.setScaleYEnabled(false); - mCharteCO2.setBackgroundColor(Color.BLACK); - mCharteCO2.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mCharteCO2.setData(data); - - Legend l = mCharteCO2.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - xeCO2.setTextColor(Color.WHITE); - xeCO2.setDrawGridLines(true); - xeCO2.setAvoidFirstLastClipping(true); - - yeCO2.setTextColor(Color.WHITE); - yeCO2.setAxisMaximum(10000f); - yeCO2.setAxisMinimum(0); - yeCO2.setDrawGridLines(true); - yeCO2.setLabelCount(10); - - yeCO22.setDrawGridLines(false); - - mChartTVOC.setTouchEnabled(true); - mChartTVOC.setHighlightPerDragEnabled(true); - mChartTVOC.setDragEnabled(true); - mChartTVOC.setScaleEnabled(true); - mChartTVOC.setDrawGridBackground(false); - mChartTVOC.setPinchZoom(true); - mChartTVOC.setScaleYEnabled(false); - mChartTVOC.setBackgroundColor(Color.BLACK); - mChartTVOC.getDescription().setEnabled(false); - - LineData data2 = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartTVOC.setData(data2); - - Legend l2 = mChartTVOC.getLegend(); - l2.setForm(Legend.LegendForm.LINE); - l2.setTextColor(Color.WHITE); - - xTVOC.setTextColor(Color.WHITE); - xTVOC.setDrawGridLines(true); - xTVOC.setAvoidFirstLastClipping(true); - - yTVOC.setTextColor(Color.WHITE); - yTVOC.setAxisMaximum(2000f); - yTVOC.setAxisMinimum(0f); - yTVOC.setDrawGridLines(true); - yTVOC.setLabelCount(10); - - yTVOC2.setDrawGridLines(false); - - } - - private boolean shouldPlay() { - if (play) { - if (indefiniteSamplesCheckBox.isChecked()) - return true; - else if (counter >= 0) { - counter--; - return true; - } else { - play = false; - return false; - } - } else { - return false; - } - } - - private void setSensorDock() { - play = false; - runIndefinitely = true; - timeGap = 100; - final int step = 1; - final int max = 1000; - final int min = 100; - - playPauseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (play && scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else if (!scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else { - playPauseButton.setImageResource(R.drawable.circle_pause_button); - play = true; - if (!indefiniteSamplesCheckBox.isChecked()) { - counter = Integer.parseInt(samplesEditBox.getText().toString()); - } - } - } - }); - sensorDock.setVisibility(View.VISIBLE); - - indefiniteSamplesCheckBox.setChecked(true); - samplesEditBox.setEnabled(false); - indefiniteSamplesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - runIndefinitely = true; - samplesEditBox.setEnabled(false); - } else { - runIndefinitely = false; - samplesEditBox.setEnabled(true); - } - } - }); - - timeGapSeekbar.setMax((max - min) / step); - timeGapSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - timeGap = min + (progress * step); - timeGapLabel.setText(timeGap + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - // Do nothing - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - // Do nothing - } - }); - } - - private class SensorDataFetch extends AsyncTask { - - private int[] dataCS811; - private int dataCCS811eCO2; - private int dataCCS811TVOC; - private long timeElapsed; - - @Override - protected Void doInBackground(Void... params) { - try { - if (sensorCCS811 != null) { - dataCS811 = sensorCCS811.getRaw(); - dataCCS811eCO2 = dataCS811[0]; - dataCCS811TVOC = dataCS811[1]; - } - } catch (IOException e) { - e.printStackTrace(); - } - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - entrieseCO2.add(new Entry((float) timeElapsed, dataCCS811eCO2)); - entriesTVOC.add(new Entry((float) timeElapsed, dataCCS811TVOC)); - return null; - } - - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - tvSensorCCS811eCO2.setText(DataFormatter.formatDouble(dataCCS811eCO2, DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorCCS811TVOC.setText(DataFormatter.formatDouble(dataCCS811TVOC, DataFormatter.HIGH_PRECISION_FORMAT)); - - LineDataSet dataSet1 = new LineDataSet(entrieseCO2, getString(R.string.eCO2)); - LineDataSet dataSet2 = new LineDataSet(entriesTVOC, getString(R.string.eTVOC)); - - dataSet1.setDrawCircles(true); - dataSet2.setDrawCircles(true); - - LineData data = new LineData(dataSet1); - mCharteCO2.setData(data); - mCharteCO2.notifyDataSetChanged(); - mCharteCO2.setVisibleXRangeMaximum(10); - mCharteCO2.moveViewToX(data.getEntryCount()); - mCharteCO2.invalidate(); - - LineData data2 = new LineData(dataSet2); - mChartTVOC.setData(data2); - mChartTVOC.notifyDataSetChanged(); - mChartTVOC.setVisibleXRangeMaximum(10); - mChartTVOC.moveViewToX(data2.getEntryCount()); - mChartTVOC.invalidate(); - samplesEditBox.setText(String.valueOf(counter)); - if (counter == 0 && !runIndefinitely) { - play = false; - playPauseButton.setImageResource(R.drawable.circle_play_button); - } - synchronized (lock) { - lock.notify(); - } - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/sensors/SensorHMC5883L.java b/app/src/main/java/io/pslab/sensors/SensorHMC5883L.java deleted file mode 100644 index 395dfd7a8..000000000 --- a/app/src/main/java/io/pslab/sensors/SensorHMC5883L.java +++ /dev/null @@ -1,323 +0,0 @@ -package io.pslab.sensors; - -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.View; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; -import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.HMC5883L; -import io.pslab.others.ScienceLabCommon; - -/** - * Created by Harsh on 6/6/18. - */ - -public class SensorHMC5883L extends AppCompatActivity { - private static int counter; - private final Object lock = new Object(); - private ScienceLab scienceLab; - private SensorHMC5883L.SensorDataFetch sensorDataFetch; - private TextView tvSensorHMC5883Lbx; - private TextView tvSensorHMC5883Lby; - private TextView tvSensorHMC5883Lbz; - private HMC5883L sensorHMC5883L; - private LineChart mChart; - private long startTime; - private int flag; - private ArrayList entriesBx; - private ArrayList entriesBy; - private ArrayList entriesBz; - private RelativeLayout sensorDock; - private CheckBox indefiniteSamplesCheckBox; - private EditText samplesEditBox; - private SeekBar timeGapSeekbar; - private TextView timeGapLabel; - private ImageButton playPauseButton; - private boolean play; - private boolean runIndefinitely; - private int timeGap; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.sensor_hmc5883l); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.hmc5883l); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - sensorDock = findViewById(R.id.sensor_control_dock_layout); - indefiniteSamplesCheckBox = findViewById(R.id.checkBox_samples_sensor); - samplesEditBox = findViewById(R.id.editBox_samples_sensors); - timeGapSeekbar = findViewById(R.id.seekBar_timegap_sensor); - timeGapLabel = findViewById(R.id.tv_timegap_label); - playPauseButton = findViewById(R.id.imageButton_play_pause_sensor); - setSensorDock(); - sensorDock.setVisibility(View.VISIBLE); - - scienceLab = ScienceLabCommon.scienceLab; - I2C i2c = scienceLab.i2c; - try { - sensorHMC5883L = new HMC5883L(i2c, scienceLab); - } catch (IOException e) { - e.printStackTrace(); - } - - entriesBx = new ArrayList<>(); - entriesBy = new ArrayList<>(); - entriesBz = new ArrayList<>(); - sensorDock.setVisibility(View.VISIBLE); - - Runnable runnable = new Runnable() { - @Override - public void run() { - while (true) { - if (scienceLab.isConnected() && shouldPlay()) { - sensorDataFetch = new SensorHMC5883L.SensorDataFetch(); - sensorDataFetch.execute(); - if (flag == 0) { - startTime = System.currentTimeMillis(); - flag = 1; - } - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - try { - Thread.sleep(timeGap); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - }; - new Thread(runnable).start(); - - tvSensorHMC5883Lbx = findViewById(R.id.tv_sensor_hmc5883l_bx); - tvSensorHMC5883Lby = findViewById(R.id.tv_sensor_hmc5883l_by); - tvSensorHMC5883Lbz = findViewById(R.id.tv_sensor_hmc5883l_bz); - mChart = findViewById(R.id.chart_hmc5883l); - XAxis x = mChart.getXAxis(); - YAxis y = mChart.getAxisLeft(); - YAxis y2 = mChart.getAxisRight(); - - mChart.setTouchEnabled(true); - mChart.setHighlightPerDragEnabled(true); - mChart.setDragEnabled(true); - mChart.setScaleEnabled(true); - mChart.setDrawGridBackground(false); - mChart.setPinchZoom(true); - mChart.setScaleYEnabled(false); - mChart.setBackgroundColor(Color.BLACK); - mChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mChart.setData(data); - - Legend l = mChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(10f); - y.setAxisMinimum(-10f); - y.setDrawGridLines(true); - y.setLabelCount(10); - - y2.setDrawGridLines(false); - } - - private boolean shouldPlay() { - if (play) { - if (indefiniteSamplesCheckBox.isChecked()) - return true; - else if (counter >= 0) { - counter--; - return true; - } else { - play = false; - return false; - } - } else { - return false; - } - } - - private void setSensorDock() { - play = false; - runIndefinitely = true; - timeGap = 100; - final int step = 1; - final int max = 1000; - final int min = 100; - - playPauseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (play && scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else if (!scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else { - playPauseButton.setImageResource(R.drawable.circle_pause_button); - play = true; - if (!indefiniteSamplesCheckBox.isChecked()) { - counter = Integer.parseInt(samplesEditBox.getText().toString()); - } - } - } - }); - sensorDock.setVisibility(View.VISIBLE); - - indefiniteSamplesCheckBox.setChecked(true); - samplesEditBox.setEnabled(false); - indefiniteSamplesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - runIndefinitely = true; - samplesEditBox.setEnabled(false); - } else { - runIndefinitely = false; - samplesEditBox.setEnabled(true); - } - } - }); - - timeGapSeekbar.setMax((max - min) / step); - timeGapSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - timeGap = min + (progress * step); - timeGapLabel.setText(timeGap + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - } - - private class SensorDataFetch extends AsyncTask { - - private ArrayList dataHMC5883L = new ArrayList<>(); - private long timeElapsed; - - @Override - protected Void doInBackground(Void... params) { - try { - if (sensorHMC5883L != null) { - dataHMC5883L = sensorHMC5883L.getRaw(); - } - } catch (IOException e) { - e.printStackTrace(); - } - - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - entriesBx.add(new Entry((float) timeElapsed, dataHMC5883L.get(0).floatValue())); - entriesBy.add(new Entry((float) timeElapsed, dataHMC5883L.get(1).floatValue())); - entriesBz.add(new Entry((float) timeElapsed, dataHMC5883L.get(2).floatValue())); - return null; - } - - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - - tvSensorHMC5883Lbx.setText(DataFormatter.formatDouble(dataHMC5883L.get(0), DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorHMC5883Lby.setText(DataFormatter.formatDouble(dataHMC5883L.get(1), DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorHMC5883Lbz.setText(DataFormatter.formatDouble(dataHMC5883L.get(2), DataFormatter.HIGH_PRECISION_FORMAT)); - - LineDataSet dataset1 = new LineDataSet(entriesBx, getString(R.string.bx)); - LineDataSet dataSet2 = new LineDataSet(entriesBy, getString(R.string.by)); - LineDataSet dataSet3 = new LineDataSet(entriesBz, getString(R.string.bz)); - - dataset1.setColor(Color.BLUE); - dataSet2.setColor(Color.GREEN); - dataSet3.setColor(Color.RED); - - dataset1.setDrawCircles(true); - dataSet2.setDrawCircles(true); - dataSet3.setDrawCircles(true); - - List dataSets = new ArrayList<>(); - dataSets.add(dataset1); - dataSets.add(dataSet2); - dataSets.add(dataSet3); - - LineData data = new LineData(dataSets); - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(10); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - - samplesEditBox.setText(String.valueOf(counter)); - if (counter == 0 && !runIndefinitely) { - play = false; - playPauseButton.setImageResource(R.drawable.circle_play_button); - } - synchronized (lock) { - lock.notify(); - } - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/sensors/SensorMLX90614.java b/app/src/main/java/io/pslab/sensors/SensorMLX90614.java deleted file mode 100644 index fef015cc9..000000000 --- a/app/src/main/java/io/pslab/sensors/SensorMLX90614.java +++ /dev/null @@ -1,399 +0,0 @@ -package io.pslab.sensors; - -import android.annotation.SuppressLint; -import android.content.SharedPreferences; -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AlertDialog; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.IOException; -import java.util.ArrayList; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.MLX90614; -import io.pslab.others.ScienceLabCommon; - - -public class SensorMLX90614 extends AppCompatActivity { - - private static final String PREF_NAME = "SensorMLX90614"; - private static final String KEY = "SensorMLX90614Key"; - - private static int counter; - private final Object lock = new Object(); - private ScienceLab scienceLab; - private SensorMLX90614.SensorDataFetch sensorDataFetch; - private TextView tvSensorMLX90614ObjectTemp; - private TextView tvSensorMLX90614AmbientTemp; - private MLX90614 sensorMLX90614; - private LineChart mChartObjectTemperature; - private LineChart mChartAmbientTemperature; - private long startTime; - private int flag; - private ArrayList entriesObjectTemperature; - private ArrayList entriesAmbientTemperature; - private RelativeLayout sensorDock; - private CheckBox indefiniteSamplesCheckBox; - private EditText samplesEditBox; - private SeekBar timeGapSeekbar; - private TextView timeGapLabel; - private ImageButton playPauseButton; - private boolean play; - private boolean runIndefinitely; - private int timeGap; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.sensor_mlx90614); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.mlx90614); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - howToConnectDialog(getString(R.string.ir_thermometer), getString(R.string.ir_thermometer_intro), R.drawable.mlx90614_schematic, getString(R.string.ir_thermometer_desc)); - - sensorDock = findViewById(R.id.sensor_control_dock_layout); - indefiniteSamplesCheckBox = findViewById(R.id.checkBox_samples_sensor); - samplesEditBox = findViewById(R.id.editBox_samples_sensors); - timeGapSeekbar = findViewById(R.id.seekBar_timegap_sensor); - timeGapLabel = findViewById(R.id.tv_timegap_label); - playPauseButton = findViewById(R.id.imageButton_play_pause_sensor); - setSensorDock(); - sensorDock.setVisibility(View.VISIBLE); - - scienceLab = ScienceLabCommon.scienceLab; - I2C i2c = scienceLab.i2c; - try { - sensorMLX90614 = new MLX90614(i2c); - } catch (IOException e) { - e.printStackTrace(); - } - - entriesObjectTemperature = new ArrayList<>(); - entriesAmbientTemperature = new ArrayList<>(); - - Runnable runnable = new Runnable() { - @Override - public void run() { - while (true) { - if (scienceLab.isConnected() && shouldPlay()) { - sensorDataFetch = new SensorMLX90614.SensorDataFetch(); - sensorDataFetch.execute(); - if (flag == 0) { - startTime = System.currentTimeMillis(); - flag = 1; - } - - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - try { - Thread.sleep(timeGap); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - }; - new Thread(runnable).start(); - - tvSensorMLX90614ObjectTemp = findViewById(R.id.tv_sensor_mlx90614_object_temp); - tvSensorMLX90614AmbientTemp = findViewById(R.id.tv_sensor_mlx90614_ambient_temp); - - mChartObjectTemperature = findViewById(R.id.chart_obj_temp_mlx); - mChartAmbientTemperature = findViewById(R.id.chart_amb_temp_mlx); - - XAxis xObjectTemperature = mChartObjectTemperature.getXAxis(); - YAxis yObjectTemperature = mChartObjectTemperature.getAxisLeft(); - YAxis yObjectTemperature2 = mChartObjectTemperature.getAxisRight(); - - XAxis xAmbientTemperature = mChartAmbientTemperature.getXAxis(); - YAxis yAmbientTemperature = mChartAmbientTemperature.getAxisLeft(); - YAxis yAmbientTemperature2 = mChartAmbientTemperature.getAxisRight(); - - mChartObjectTemperature.setTouchEnabled(true); - mChartObjectTemperature.setHighlightPerDragEnabled(true); - mChartObjectTemperature.setDragEnabled(true); - mChartObjectTemperature.setScaleEnabled(true); - mChartObjectTemperature.setDrawGridBackground(false); - mChartObjectTemperature.setPinchZoom(true); - mChartObjectTemperature.setScaleYEnabled(false); - mChartObjectTemperature.setBackgroundColor(Color.BLACK); - mChartObjectTemperature.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartObjectTemperature.setData(data); - - Legend l = mChartObjectTemperature.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - xObjectTemperature.setTextColor(Color.WHITE); - xObjectTemperature.setDrawGridLines(true); - xObjectTemperature.setAvoidFirstLastClipping(true); - - yObjectTemperature.setTextColor(Color.WHITE); - yObjectTemperature.setAxisMaximum(125f); - yObjectTemperature.setAxisMinimum(-40f); - yObjectTemperature.setDrawGridLines(true); - yObjectTemperature.setLabelCount(10); - - yObjectTemperature2.setDrawGridLines(false); - - mChartAmbientTemperature.setTouchEnabled(true); - mChartAmbientTemperature.setHighlightPerDragEnabled(true); - mChartAmbientTemperature.setDragEnabled(true); - mChartAmbientTemperature.setScaleEnabled(true); - mChartAmbientTemperature.setDrawGridBackground(false); - mChartAmbientTemperature.setPinchZoom(true); - mChartAmbientTemperature.setScaleYEnabled(false); - mChartAmbientTemperature.setBackgroundColor(Color.BLACK); - mChartAmbientTemperature.getDescription().setEnabled(false); - - LineData data2 = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartAmbientTemperature.setData(data2); - - Legend l2 = mChartAmbientTemperature.getLegend(); - l2.setForm(Legend.LegendForm.LINE); - l2.setTextColor(Color.WHITE); - - xAmbientTemperature.setTextColor(Color.WHITE); - xAmbientTemperature.setDrawGridLines(true); - xAmbientTemperature.setAvoidFirstLastClipping(true); - - yAmbientTemperature.setTextColor(Color.WHITE); - yAmbientTemperature.setAxisMaximum(380f); - yAmbientTemperature.setAxisMinimum(-70f); - yAmbientTemperature.setDrawGridLines(true); - yAmbientTemperature.setLabelCount(10); - - yAmbientTemperature2.setDrawGridLines(false); - } - - private boolean shouldPlay() { - if (play) { - if (indefiniteSamplesCheckBox.isChecked()) - return true; - else if (counter >= 0) { - counter--; - return true; - } else { - play = false; - return false; - } - } else { - return false; - } - } - - private void setSensorDock() { - play = false; - runIndefinitely = true; - timeGap = 100; - final int step = 1; - final int max = 1000; - final int min = 100; - - playPauseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (play && scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else if (!scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else { - playPauseButton.setImageResource(R.drawable.circle_pause_button); - play = true; - if (!indefiniteSamplesCheckBox.isChecked()) { - counter = Integer.parseInt(samplesEditBox.getText().toString()); - } - } - } - }); - sensorDock.setVisibility(View.VISIBLE); - - indefiniteSamplesCheckBox.setChecked(true); - samplesEditBox.setEnabled(false); - indefiniteSamplesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - runIndefinitely = true; - samplesEditBox.setEnabled(false); - } else { - runIndefinitely = false; - samplesEditBox.setEnabled(true); - } - } - }); - - timeGapSeekbar.setMax((max - min) / step); - timeGapSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - timeGap = min + (progress * step); - timeGapLabel.setText(timeGap + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - } - - @SuppressLint("ResourceType") - public void howToConnectDialog(String title, String intro, int imageID, String desc) { - try { - final AlertDialog.Builder builder = new AlertDialog.Builder(this); - LayoutInflater inflater = getLayoutInflater(); - View dialogView = inflater.inflate(R.layout.custom_dialog_box, null); - builder.setView(dialogView); - builder.setTitle(title); - - final TextView dialogText = dialogView.findViewById(R.id.custom_dialog_text); - final TextView dialogDesc = dialogView.findViewById(R.id.description_text); - final ImageView dialogImage = dialogView.findViewById(R.id.custom_dialog_schematic); - final CheckBox doNotShowDialog = dialogView.findViewById(R.id.toggle_show_again); - final Button okButton = dialogView.findViewById(R.id.dismiss_button); - dialogText.setText(intro); - dialogImage.setImageResource(imageID); - dialogDesc.setText(desc); - - final SharedPreferences sharedPreferences = this.getSharedPreferences(PREF_NAME, MODE_PRIVATE); - final AlertDialog dialog = builder.create(); - Boolean skipDialog = sharedPreferences.getBoolean(KEY, false); - okButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (doNotShowDialog.isChecked()) { - SharedPreferences.Editor editor = sharedPreferences.edit(); - editor.putBoolean(KEY, true); - editor.apply(); - } - dialog.dismiss(); - } - }); - if (!skipDialog) { - dialog.show(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private class SensorDataFetch extends AsyncTask { - - private Double dataMLX90614ObjectTemp; - private Double dataMLX90614AmbientTemp; - private long timeElapsed; - - @Override - protected Void doInBackground(Void... params) { - try { - if (sensorMLX90614 != null) { - dataMLX90614ObjectTemp = sensorMLX90614.getObjectTemperature(); - dataMLX90614AmbientTemp = sensorMLX90614.getAmbientTemperature(); - } - } catch (IOException e) { - e.printStackTrace(); - } - - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - entriesObjectTemperature.add(new Entry((float) timeElapsed, dataMLX90614ObjectTemp.floatValue())); - entriesAmbientTemperature.add(new Entry((float) timeElapsed, dataMLX90614AmbientTemp.floatValue())); - return null; - } - - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - tvSensorMLX90614ObjectTemp.setText(DataFormatter.formatDouble(dataMLX90614ObjectTemp, DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMLX90614AmbientTemp.setText(DataFormatter.formatDouble(dataMLX90614AmbientTemp, DataFormatter.HIGH_PRECISION_FORMAT)); - - LineDataSet dataSet1 = new LineDataSet(entriesObjectTemperature, getString(R.string.object_temp)); - LineDataSet dataSet2 = new LineDataSet(entriesAmbientTemperature, getString(R.string.ambient_temp)); - - dataSet1.setDrawCircles(true); - dataSet2.setDrawCircles(true); - - LineData data1 = new LineData(dataSet1); - mChartObjectTemperature.setData(data1); - mChartObjectTemperature.notifyDataSetChanged(); - mChartObjectTemperature.setVisibleXRangeMaximum(10); - mChartObjectTemperature.moveViewToX(data1.getEntryCount()); - mChartObjectTemperature.invalidate(); - - LineData data2 = new LineData(dataSet2); - mChartAmbientTemperature.setData(data2); - mChartAmbientTemperature.notifyDataSetChanged(); - mChartAmbientTemperature.setVisibleXRangeMaximum(10); - mChartAmbientTemperature.moveViewToX(data2.getEntryCount()); - mChartAmbientTemperature.invalidate(); - samplesEditBox.setText(String.valueOf(counter)); - if (counter == 0 && !runIndefinitely) { - play = false; - playPauseButton.setImageResource(R.drawable.circle_play_button); - } - synchronized (lock) { - lock.notify(); - } - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/sensors/SensorMPU6050.java b/app/src/main/java/io/pslab/sensors/SensorMPU6050.java deleted file mode 100644 index 0a2518ddd..000000000 --- a/app/src/main/java/io/pslab/sensors/SensorMPU6050.java +++ /dev/null @@ -1,424 +0,0 @@ -package io.pslab.sensors; - -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.View; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; -import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.MPU6050; -import io.pslab.others.ScienceLabCommon; - -/** - * Created by Harsh on 6/6/18. - */ - -public class SensorMPU6050 extends AppCompatActivity { - private static int counter; - private final Object lock = new Object(); - private ScienceLab scienceLab; - private SensorMPU6050.SensorDataFetch sensorDataFetch; - private TextView tvSensorMPU6050ax; - private TextView tvSensorMPU6050ay; - private TextView tvSensorMPU6050az; - private TextView tvSensorMPU6050gx; - private TextView tvSensorMPU6050gy; - private TextView tvSensorMPU6050gz; - private TextView tvSensorMPU6050temp; - private MPU6050 sensorMPU6050; - private LineChart mChartAcceleration; - private LineChart mChartGyroscope; - private long startTime; - private int flag; - private ArrayList entriesAx; - private ArrayList entriesAy; - private ArrayList entriesAz; - private ArrayList entriesGx; - private ArrayList entriesGy; - private ArrayList entriesGz; - private RelativeLayout sensorDock; - private CheckBox indefiniteSamplesCheckBox; - private EditText samplesEditBox; - private SeekBar timeGapSeekbar; - private TextView timeGapLabel; - private ImageButton playPauseButton; - private boolean play; - private boolean runIndefinitely; - private int timeGap; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.sensor_mpu6050); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.mpu6050); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - sensorDock = findViewById(R.id.sensor_control_dock_layout); - indefiniteSamplesCheckBox = findViewById(R.id.checkBox_samples_sensor); - samplesEditBox = findViewById(R.id.editBox_samples_sensors); - timeGapSeekbar = findViewById(R.id.seekBar_timegap_sensor); - timeGapLabel = findViewById(R.id.tv_timegap_label); - playPauseButton = findViewById(R.id.imageButton_play_pause_sensor); - setSensorDock(); - sensorDock.setVisibility(View.VISIBLE); - - scienceLab = ScienceLabCommon.scienceLab; - I2C i2c = scienceLab.i2c; - try { - sensorMPU6050 = new MPU6050(i2c, scienceLab); - } catch (IOException e) { - e.printStackTrace(); - } - - entriesAx = new ArrayList<>(); - entriesAy = new ArrayList<>(); - entriesAz = new ArrayList<>(); - entriesGx = new ArrayList<>(); - entriesGy = new ArrayList<>(); - entriesGz = new ArrayList<>(); - - Runnable runnable = new Runnable() { - @Override - public void run() { - while (true) { - if (scienceLab.isConnected() && shouldPlay()) { - sensorDataFetch = new SensorMPU6050.SensorDataFetch(); - sensorDataFetch.execute(); - - if (flag == 0) { - startTime = System.currentTimeMillis(); - flag = 1; - } - - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - try { - Thread.sleep(timeGap); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - }; - new Thread(runnable).start(); - - tvSensorMPU6050ax = findViewById(R.id.tv_sensor_mpu6050_ax); - tvSensorMPU6050ay = findViewById(R.id.tv_sensor_mpu6050_ay); - tvSensorMPU6050az = findViewById(R.id.tv_sensor_mpu6050_az); - tvSensorMPU6050gx = findViewById(R.id.tv_sensor_mpu6050_gx); - tvSensorMPU6050gy = findViewById(R.id.tv_sensor_mpu6050_gy); - tvSensorMPU6050gz = findViewById(R.id.tv_sensor_mpu6050_gz); - tvSensorMPU6050temp = findViewById(R.id.tv_sensor_mpu6050_temp); - - Spinner spinnerSensorMPU60501 = findViewById(R.id.spinner_sensor_mpu6050_1); - Spinner spinnerSensorMPU60502 = findViewById(R.id.spinner_sensor_mpu6050_2); - Spinner spinnerSensorMPU60503 = findViewById(R.id.spinner_sensor_mpu6050_3); - Spinner spinnerSensorMPU60504 = findViewById(R.id.spinner_sensor_mpu6050_4); - - mChartAcceleration = findViewById(R.id.chart_sensor_mpu6050_accelerometer); - mChartGyroscope = findViewById(R.id.chart_sensor_mpu6050_gyroscope); - - XAxis xAccelerometer = mChartAcceleration.getXAxis(); - YAxis yAccelerometer = mChartAcceleration.getAxisLeft(); - YAxis yAccelerometer2 = mChartAcceleration.getAxisRight(); - - XAxis xGyroscope = mChartGyroscope.getXAxis(); - YAxis yGyroscope = mChartGyroscope.getAxisLeft(); - YAxis yGyroscope2 = mChartGyroscope.getAxisRight(); - - mChartAcceleration.setTouchEnabled(true); - mChartAcceleration.setHighlightPerDragEnabled(true); - mChartAcceleration.setDragEnabled(true); - mChartAcceleration.setScaleEnabled(true); - mChartAcceleration.setDrawGridBackground(false); - mChartAcceleration.setPinchZoom(true); - mChartAcceleration.setScaleYEnabled(false); - mChartAcceleration.setBackgroundColor(Color.BLACK); - mChartAcceleration.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartAcceleration.setData(data); - - Legend l = mChartAcceleration.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - xAccelerometer.setTextColor(Color.WHITE); - xAccelerometer.setDrawGridLines(true); - xAccelerometer.setAvoidFirstLastClipping(true); - - yAccelerometer.setTextColor(Color.WHITE); - yAccelerometer.setAxisMaximum(25f); - yAccelerometer.setAxisMinimum(-25f); - yAccelerometer.setDrawGridLines(true); - yAccelerometer.setLabelCount(10); - - yAccelerometer2.setDrawGridLines(false); - - mChartGyroscope.setTouchEnabled(true); - mChartGyroscope.setHighlightPerDragEnabled(true); - mChartGyroscope.setDragEnabled(true); - mChartGyroscope.setScaleEnabled(true); - mChartGyroscope.setDrawGridBackground(false); - mChartGyroscope.setPinchZoom(true); - mChartGyroscope.setScaleYEnabled(false); - mChartGyroscope.setBackgroundColor(Color.BLACK); - mChartGyroscope.getDescription().setEnabled(false); - - LineData data2 = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartGyroscope.setData(data2); - - Legend l2 = mChartGyroscope.getLegend(); - l2.setForm(Legend.LegendForm.LINE); - l2.setTextColor(Color.WHITE); - - xGyroscope.setTextColor(Color.WHITE); - xGyroscope.setDrawGridLines(true); - xGyroscope.setAvoidFirstLastClipping(true); - - yGyroscope.setTextColor(Color.WHITE); - yGyroscope.setAxisMaximum(200f); - yGyroscope.setAxisMinimum(-200f); - yGyroscope.setDrawGridLines(true); - yGyroscope.setLabelCount(10); - - yGyroscope2.setDrawGridLines(false); - - try { - if (sensorMPU6050 != null && scienceLab.isConnected()) { - sensorMPU6050.setAccelerationRange(Integer.parseInt(spinnerSensorMPU60502.getSelectedItem().toString())); - } - } catch (IOException e) { - e.printStackTrace(); - } - - try { - if (sensorMPU6050 != null && scienceLab.isConnected()) { - sensorMPU6050.setGyroRange(Integer.parseInt(spinnerSensorMPU60501.getSelectedItem().toString())); - } - } catch (IOException e) { - e.printStackTrace(); - } - - } - - private boolean shouldPlay() { - if (play && scienceLab.isConnected()) { - if (indefiniteSamplesCheckBox.isChecked()) - return true; - else if (counter >= 0) { - counter--; - return true; - } else { - play = false; - return false; - } - } else { - return false; - } - } - - private void setSensorDock() { - play = false; - runIndefinitely = true; - timeGap = 100; - final int step = 1; - final int max = 1000; - final int min = 100; - - playPauseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (play && scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else if (!scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else { - playPauseButton.setImageResource(R.drawable.circle_pause_button); - play = true; - if (!indefiniteSamplesCheckBox.isChecked()) { - counter = Integer.parseInt(samplesEditBox.getText().toString()); - } - } - } - }); - sensorDock.setVisibility(View.VISIBLE); - - indefiniteSamplesCheckBox.setChecked(true); - samplesEditBox.setEnabled(false); - indefiniteSamplesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - runIndefinitely = true; - samplesEditBox.setEnabled(false); - } else { - runIndefinitely = false; - samplesEditBox.setEnabled(true); - } - } - }); - - timeGapSeekbar.setMax((max - min) / step); - timeGapSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - timeGap = min + (progress * step); - timeGapLabel.setText(timeGap + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - } - - private class SensorDataFetch extends AsyncTask { - - private ArrayList dataMPU6050 = new ArrayList<>(); - private long timeElapsed; - - @Override - protected Void doInBackground(Void... params) { - - try { - dataMPU6050 = sensorMPU6050.getRaw(); - } catch (IOException e) { - e.printStackTrace(); - } - - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - - entriesAx.add(new Entry((float) timeElapsed, dataMPU6050.get(0).floatValue())); - entriesAy.add(new Entry((float) timeElapsed, dataMPU6050.get(1).floatValue())); - entriesAz.add(new Entry((float) timeElapsed, dataMPU6050.get(2).floatValue())); - - entriesGx.add(new Entry((float) timeElapsed, dataMPU6050.get(4).floatValue())); - entriesGy.add(new Entry((float) timeElapsed, dataMPU6050.get(5).floatValue())); - entriesGz.add(new Entry((float) timeElapsed, dataMPU6050.get(6).floatValue())); - - return null; - } - - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - tvSensorMPU6050ax.setText(DataFormatter.formatDouble(dataMPU6050.get(0), DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU6050ay.setText(DataFormatter.formatDouble(dataMPU6050.get(1), DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU6050az.setText(DataFormatter.formatDouble(dataMPU6050.get(2), DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU6050gx.setText(DataFormatter.formatDouble(dataMPU6050.get(4), DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU6050gy.setText(DataFormatter.formatDouble(dataMPU6050.get(5), DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU6050gz.setText(DataFormatter.formatDouble(dataMPU6050.get(6), DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU6050temp.setText(DataFormatter.formatDouble(dataMPU6050.get(3), DataFormatter.HIGH_PRECISION_FORMAT)); - - LineDataSet dataset1 = new LineDataSet(entriesAx, getString(R.string.ax)); - LineDataSet dataSet2 = new LineDataSet(entriesAy, getString(R.string.ay)); - LineDataSet dataSet3 = new LineDataSet(entriesAz, getString(R.string.az)); - - LineDataSet dataset4 = new LineDataSet(entriesGx, getString(R.string.gx)); - LineDataSet dataSet5 = new LineDataSet(entriesGy, getString(R.string.gy)); - LineDataSet dataSet6 = new LineDataSet(entriesGz, getString(R.string.gz)); - - - dataset1.setColor(Color.BLUE); - dataSet2.setColor(Color.GREEN); - dataSet3.setColor(Color.RED); - - dataset4.setColor(Color.BLUE); - dataSet5.setColor(Color.GREEN); - dataSet6.setColor(Color.RED); - - List dataSets = new ArrayList<>(); - dataSets.add(dataset1); - dataSets.add(dataSet2); - dataSets.add(dataSet3); - - List dataSets2 = new ArrayList<>(); - dataSets2.add(dataset4); - dataSets2.add(dataSet5); - dataSets2.add(dataSet6); - - LineData data = new LineData(dataSets); - mChartAcceleration.setData(data); - mChartAcceleration.notifyDataSetChanged(); - mChartAcceleration.setVisibleXRangeMaximum(10); - mChartAcceleration.moveViewToX(data.getEntryCount()); - mChartAcceleration.invalidate(); - - LineData data2 = new LineData(dataSets2); - mChartGyroscope.setData(data2); - mChartGyroscope.notifyDataSetChanged(); - mChartGyroscope.setVisibleXRangeMaximum(10); - mChartGyroscope.moveViewToX(data2.getEntryCount()); - mChartGyroscope.invalidate(); - samplesEditBox.setText(String.valueOf(counter)); - if (counter == 0 && !runIndefinitely) { - play = false; - playPauseButton.setImageResource(R.drawable.circle_play_button); - } - synchronized (lock) { - lock.notify(); - } - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/sensors/SensorMPU925X.java b/app/src/main/java/io/pslab/sensors/SensorMPU925X.java deleted file mode 100644 index 8a81203d4..000000000 --- a/app/src/main/java/io/pslab/sensors/SensorMPU925X.java +++ /dev/null @@ -1,428 +0,0 @@ -package io.pslab.sensors; - -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.View; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; -import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.MPU925x; -import io.pslab.others.ScienceLabCommon; - -/** - * Created by Harsh on 6/6/18. - */ - -public class SensorMPU925X extends AppCompatActivity { - private static int counter; - private final Object lock = new Object(); - private ScienceLab scienceLab; - private SensorMPU925X.SensorDataFetch sensorDataFetch; - private TextView tvSensorMPU925Xax; - private TextView tvSensorMPU925Xay; - private TextView tvSensorMPU925Xaz; - private TextView tvSensorMPU925Xgx; - private TextView tvSensorMPU925Xgy; - private TextView tvSensorMPU925Xgz; - private TextView tvSensorMPU925Xtemp; - private MPU925x sensorMPU925X; - private LineChart mChartAcceleration; - private LineChart mChartGyroscope; - private long startTime; - private int flag; - private ArrayList entriesax; - private ArrayList entriesay; - private ArrayList entriesaz; - private ArrayList entriesgx; - private ArrayList entriesgy; - private ArrayList entriesgz; - private RelativeLayout sensorDock; - private CheckBox indefiniteSamplesCheckBox; - private EditText samplesEditBox; - private SeekBar timeGapSeekbar; - private TextView timeGapLabel; - private ImageButton playPauseButton; - private boolean play; - private boolean runIndefinitely; - private int timeGap; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.sensor_mpu925x); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.mpu925x); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - sensorDock = findViewById(R.id.sensor_control_dock_layout); - indefiniteSamplesCheckBox = findViewById(R.id.checkBox_samples_sensor); - samplesEditBox = findViewById(R.id.editBox_samples_sensors); - timeGapSeekbar = findViewById(R.id.seekBar_timegap_sensor); - timeGapLabel = findViewById(R.id.tv_timegap_label); - playPauseButton = findViewById(R.id.imageButton_play_pause_sensor); - setSensorDock(); - sensorDock.setVisibility(View.VISIBLE); - - scienceLab = ScienceLabCommon.scienceLab; - I2C i2c = scienceLab.i2c; - try { - if (i2c == null) throw new IOException("i2c not found"); - sensorMPU925X = new MPU925x(i2c); - } catch (IOException e) { - e.printStackTrace(); - } - - entriesax = new ArrayList<>(); - entriesay = new ArrayList<>(); - entriesaz = new ArrayList<>(); - entriesgx = new ArrayList<>(); - entriesgy = new ArrayList<>(); - entriesgz = new ArrayList<>(); - - Runnable runnable = new Runnable() { - @Override - public void run() { - while (true) { - if (scienceLab.isConnected() && shouldPlay()) { - sensorDataFetch = new SensorMPU925X.SensorDataFetch(); - sensorDataFetch.execute(); - - if (flag == 0) { - startTime = System.currentTimeMillis(); - flag = 1; - } - - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - try { - Thread.sleep(timeGap); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - }; - new Thread(runnable).start(); - - tvSensorMPU925Xax = findViewById(R.id.tv_sensor_mpu925x_ax); - tvSensorMPU925Xay = findViewById(R.id.tv_sensor_mpu925x_ay); - tvSensorMPU925Xaz = findViewById(R.id.tv_sensor_mpu925x_az); - tvSensorMPU925Xgx = findViewById(R.id.tv_sensor_mpu925x_gx); - tvSensorMPU925Xgy = findViewById(R.id.tv_sensor_mpu925x_gy); - tvSensorMPU925Xgz = findViewById(R.id.tv_sensor_mpu925x_gz); - tvSensorMPU925Xtemp = findViewById(R.id.tv_sensor_mpu925x_temp); - - Spinner spinnerSensorMPU925X1 = findViewById(R.id.spinner_sensor_mpu925x_1); - Spinner spinnerSensorMPU925X2 = findViewById(R.id.spinner_sensor_mpu925x_2); - Spinner spinnerSensorMPU925X3 = findViewById(R.id.spinner_sensor_mpu925x_3); - Spinner spinnerSensorMPU925X4 = findViewById(R.id.spinner_sensor_mpu925x_4); - - mChartAcceleration = findViewById(R.id.chart_sensor_mpu925x_accelerometer); - mChartGyroscope = findViewById(R.id.chart_sensor_mpu925x_gyroscope); - - XAxis xAccelerometer = mChartAcceleration.getXAxis(); - YAxis yAccelerometer = mChartAcceleration.getAxisLeft(); - YAxis yAccelerometer2 = mChartAcceleration.getAxisRight(); - - XAxis xGyroscope = mChartGyroscope.getXAxis(); - YAxis yGyroscope = mChartGyroscope.getAxisLeft(); - YAxis yGyroscope2 = mChartGyroscope.getAxisRight(); - - mChartAcceleration.setTouchEnabled(true); - mChartAcceleration.setHighlightPerDragEnabled(true); - mChartAcceleration.setDragEnabled(true); - mChartAcceleration.setScaleEnabled(true); - mChartAcceleration.setDrawGridBackground(false); - mChartAcceleration.setPinchZoom(true); - mChartAcceleration.setScaleYEnabled(false); - mChartAcceleration.setBackgroundColor(Color.BLACK); - mChartAcceleration.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartAcceleration.setData(data); - - Legend l = mChartAcceleration.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - xAccelerometer.setTextColor(Color.WHITE); - xAccelerometer.setDrawGridLines(true); - xAccelerometer.setAvoidFirstLastClipping(true); - - yAccelerometer.setTextColor(Color.WHITE); - yAccelerometer.setAxisMaximum(25f); - yAccelerometer.setAxisMinimum(-25f); - yAccelerometer.setDrawGridLines(true); - yAccelerometer.setLabelCount(10); - - yAccelerometer2.setDrawGridLines(false); - - mChartGyroscope.setTouchEnabled(true); - mChartGyroscope.setHighlightPerDragEnabled(true); - mChartGyroscope.setDragEnabled(true); - mChartGyroscope.setScaleEnabled(true); - mChartGyroscope.setDrawGridBackground(false); - mChartGyroscope.setPinchZoom(true); - mChartGyroscope.setScaleYEnabled(false); - mChartGyroscope.setBackgroundColor(Color.BLACK); - mChartGyroscope.getDescription().setEnabled(false); - - LineData data2 = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartGyroscope.setData(data2); - - Legend l2 = mChartGyroscope.getLegend(); - l2.setForm(Legend.LegendForm.LINE); - l2.setTextColor(Color.WHITE); - - xGyroscope.setTextColor(Color.WHITE); - xGyroscope.setDrawGridLines(true); - xGyroscope.setAvoidFirstLastClipping(true); - - yGyroscope.setTextColor(Color.WHITE); - yGyroscope.setAxisMaximum(200f); - yGyroscope.setAxisMinimum(-200f); - yGyroscope.setDrawGridLines(true); - yGyroscope.setLabelCount(10); - - yGyroscope2.setDrawGridLines(false); - - try { - if (sensorMPU925X != null) { - sensorMPU925X.setAccelRange(Integer.parseInt(spinnerSensorMPU925X2.getSelectedItem().toString())); - } - } catch (IOException e) { - e.printStackTrace(); - } - - try { - if (sensorMPU925X != null) { - sensorMPU925X.setGyroRange(Integer.parseInt(spinnerSensorMPU925X1.getSelectedItem().toString())); - } - } catch (IOException e) { - e.printStackTrace(); - } - - } - - private boolean shouldPlay() { - if (play) { - if (indefiniteSamplesCheckBox.isChecked()) - return true; - else if (counter >= 0) { - counter--; - return true; - } else { - play = false; - return false; - } - } else { - return false; - } - } - - private void setSensorDock() { - play = false; - runIndefinitely = true; - timeGap = 100; - final int step = 1; - final int max = 1000; - final int min = 100; - - playPauseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (play && scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else if (!scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else { - playPauseButton.setImageResource(R.drawable.circle_pause_button); - play = true; - if (!indefiniteSamplesCheckBox.isChecked()) { - counter = Integer.parseInt(samplesEditBox.getText().toString()); - } - } - } - }); - sensorDock.setVisibility(View.VISIBLE); - - indefiniteSamplesCheckBox.setChecked(true); - samplesEditBox.setEnabled(false); - indefiniteSamplesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - runIndefinitely = true; - samplesEditBox.setEnabled(false); - } else { - runIndefinitely = false; - samplesEditBox.setEnabled(true); - } - } - }); - - timeGapSeekbar.setMax((max - min) / step); - timeGapSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - timeGap = min + (progress * step); - timeGapLabel.setText(timeGap + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - } - - private class SensorDataFetch extends AsyncTask { - - private double[] dataGyro, dataAccel; - private double dataTemp; - private long timeElapsed; - - @Override - protected Void doInBackground(Void... params) { - - try { - dataGyro = sensorMPU925X.getGyroscope(); - dataAccel = sensorMPU925X.getAcceleration(); - dataTemp = sensorMPU925X.getTemperature(); - } catch (IOException e) { - e.printStackTrace(); - } - - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - - entriesax.add(new Entry((float) timeElapsed, (float) dataAccel[0])); - entriesay.add(new Entry((float) timeElapsed, (float) dataAccel[1])); - entriesaz.add(new Entry((float) timeElapsed, (float) dataAccel[2])); - - entriesgx.add(new Entry((float) timeElapsed, (float) dataGyro[0])); - entriesgy.add(new Entry((float) timeElapsed, (float) dataGyro[1])); - entriesgz.add(new Entry((float) timeElapsed, (float) dataGyro[2])); - - return null; - } - - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - tvSensorMPU925Xax.setText(DataFormatter.formatDouble(dataAccel[0], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU925Xay.setText(DataFormatter.formatDouble(dataAccel[1], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU925Xaz.setText(DataFormatter.formatDouble(dataAccel[2], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU925Xgx.setText(DataFormatter.formatDouble(dataGyro[0], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU925Xgy.setText(DataFormatter.formatDouble(dataGyro[1], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU925Xgz.setText(DataFormatter.formatDouble(dataGyro[2], DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorMPU925Xtemp.setText(DataFormatter.formatDouble(dataTemp, DataFormatter.HIGH_PRECISION_FORMAT)); - LineDataSet dataSet1 = new LineDataSet(entriesax, getString(R.string.ax)); - LineDataSet dataSet2 = new LineDataSet(entriesay, getString(R.string.ay)); - LineDataSet dataSet3 = new LineDataSet(entriesaz, getString(R.string.az)); - - LineDataSet dataSet4 = new LineDataSet(entriesgx, getString(R.string.gx)); - LineDataSet dataSet5 = new LineDataSet(entriesgy, getString(R.string.gy)); - LineDataSet dataSet6 = new LineDataSet(entriesgz, getString(R.string.gz)); - - - dataSet1.setColor(Color.BLUE); - dataSet2.setColor(Color.GREEN); - dataSet3.setColor(Color.RED); - - dataSet4.setColor(Color.BLUE); - dataSet5.setColor(Color.GREEN); - dataSet6.setColor(Color.RED); - - List dataSets = new ArrayList<>(); - dataSets.add(dataSet1); - dataSets.add(dataSet2); - dataSets.add(dataSet3); - - List dataSets2 = new ArrayList<>(); - dataSets2.add(dataSet4); - dataSets2.add(dataSet5); - dataSets2.add(dataSet6); - - LineData data = new LineData(dataSets); - mChartAcceleration.setData(data); - mChartAcceleration.notifyDataSetChanged(); - mChartAcceleration.setVisibleXRangeMaximum(10); - mChartAcceleration.moveViewToX(data.getEntryCount()); - mChartAcceleration.invalidate(); - - LineData data2 = new LineData(dataSets2); - mChartGyroscope.setData(data2); - mChartGyroscope.notifyDataSetChanged(); - mChartGyroscope.setVisibleXRangeMaximum(10); - mChartGyroscope.moveViewToX(data2.getEntryCount()); - mChartGyroscope.invalidate(); - samplesEditBox.setText(String.valueOf(counter)); - if (counter == 0 && !runIndefinitely) { - play = false; - playPauseButton.setImageResource(R.drawable.circle_play_button); - } - synchronized (lock) { - lock.notify(); - } - } - } - - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/sensors/SensorSHT21.java b/app/src/main/java/io/pslab/sensors/SensorSHT21.java deleted file mode 100644 index 9b4448c82..000000000 --- a/app/src/main/java/io/pslab/sensors/SensorSHT21.java +++ /dev/null @@ -1,352 +0,0 @@ -package io.pslab.sensors; - -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.View; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.IOException; -import java.util.ArrayList; - -import io.pslab.DataFormatter; -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.SHT21; -import io.pslab.others.ScienceLabCommon; - -/** - * Created by Harsh on 6/6/18. - */ - -public class SensorSHT21 extends AppCompatActivity { - private static int counter; - private final Object lock = new Object(); - private ScienceLab scienceLab; - private SensorSHT21.SensorDataFetch sensorDataFetch; - private TextView tvSensorSHT21Temp; - private TextView tvSensorSHT21Humidity; - private SHT21 sensorSHT21; - private LineChart mChartTemperature; - private LineChart mChartHumidity; - private long startTime; - private int flag; - private ArrayList entriesTemperature; - private ArrayList entriesHumidity; - private RelativeLayout sensorDock; - private CheckBox indefiniteSamplesCheckBox; - private EditText samplesEditBox; - private SeekBar timeGapSeekbar; - private TextView timeGapLabel; - private ImageButton playPauseButton; - private boolean play; - private boolean runIndefinitely; - private int timeGap; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.sensor_sht21); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.sht21); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - sensorDock = findViewById(R.id.sensor_control_dock_layout); - indefiniteSamplesCheckBox = findViewById(R.id.checkBox_samples_sensor); - samplesEditBox = findViewById(R.id.editBox_samples_sensors); - timeGapSeekbar = findViewById(R.id.seekBar_timegap_sensor); - timeGapLabel = findViewById(R.id.tv_timegap_label); - playPauseButton = findViewById(R.id.imageButton_play_pause_sensor); - setSensorDock(); - sensorDock.setVisibility(View.VISIBLE); - - scienceLab = ScienceLabCommon.scienceLab; - I2C i2c = scienceLab.i2c; - try { - sensorSHT21 = new SHT21(i2c, scienceLab); - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - - entriesTemperature = new ArrayList<>(); - entriesHumidity = new ArrayList<>(); - - Runnable runnable = new Runnable() { - @Override - public void run() { - while (true) { - if (scienceLab.isConnected() && shouldPlay()) { - sensorDataFetch = new SensorSHT21.SensorDataFetch(); - sensorDataFetch.execute(); - - if (flag == 0) { - startTime = System.currentTimeMillis(); - flag = 1; - } - - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - try { - Thread.sleep(timeGap); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - }; - new Thread(runnable).start(); - - tvSensorSHT21Temp = findViewById(R.id.tv_sensor_sht21_temp); - tvSensorSHT21Humidity = findViewById(R.id.tv_sensor_sht21_humidity); - mChartTemperature = findViewById(R.id.chart_temperature_sht21); - mChartHumidity = findViewById(R.id.chart_humidity_sht21); - - XAxis xTemperature = mChartTemperature.getXAxis(); - YAxis yTemperature = mChartTemperature.getAxisLeft(); - YAxis yTemperature2 = mChartTemperature.getAxisRight(); - - XAxis xHumidity = mChartHumidity.getXAxis(); - YAxis yHumidity = mChartHumidity.getAxisLeft(); - YAxis yHumidity2 = mChartHumidity.getAxisRight(); - - mChartTemperature.setTouchEnabled(true); - mChartTemperature.setHighlightPerDragEnabled(true); - mChartTemperature.setDragEnabled(true); - mChartTemperature.setScaleEnabled(true); - mChartTemperature.setDrawGridBackground(false); - mChartTemperature.setPinchZoom(true); - mChartTemperature.setScaleYEnabled(false); - mChartTemperature.setBackgroundColor(Color.BLACK); - mChartTemperature.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartTemperature.setData(data); - - Legend l = mChartTemperature.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - xTemperature.setTextColor(Color.WHITE); - xTemperature.setDrawGridLines(true); - xTemperature.setAvoidFirstLastClipping(true); - - yTemperature.setTextColor(Color.WHITE); - yTemperature.setAxisMaximum(125f); - yTemperature.setAxisMinimum(-40f); - yTemperature.setDrawGridLines(true); - yTemperature.setLabelCount(10); - - yTemperature2.setDrawGridLines(false); - - mChartHumidity.setTouchEnabled(true); - mChartHumidity.setHighlightPerDragEnabled(true); - mChartHumidity.setDragEnabled(true); - mChartHumidity.setScaleEnabled(true); - mChartHumidity.setDrawGridBackground(false); - mChartHumidity.setPinchZoom(true); - mChartHumidity.setScaleYEnabled(false); - mChartHumidity.setBackgroundColor(Color.BLACK); - mChartHumidity.getDescription().setEnabled(false); - - LineData data2 = new LineData(); - data.setValueTextColor(Color.WHITE); - mChartHumidity.setData(data2); - - Legend l2 = mChartHumidity.getLegend(); - l2.setForm(Legend.LegendForm.LINE); - l2.setTextColor(Color.WHITE); - - xHumidity.setTextColor(Color.WHITE); - xHumidity.setDrawGridLines(true); - xHumidity.setAvoidFirstLastClipping(true); - - yHumidity.setTextColor(Color.WHITE); - yHumidity.setAxisMaximum(100f); - yHumidity.setAxisMinimum(0f); - yHumidity.setDrawGridLines(true); - yHumidity.setLabelCount(10); - - yHumidity2.setDrawGridLines(false); - - } - - private boolean shouldPlay() { - if (play) { - if (indefiniteSamplesCheckBox.isChecked()) - return true; - else if (counter >= 0) { - counter--; - return true; - } else { - play = false; - return false; - } - } else { - return false; - } - } - - private void setSensorDock() { - play = false; - runIndefinitely = true; - timeGap = 100; - final int step = 1; - final int max = 1000; - final int min = 100; - - playPauseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (play && scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else if (!scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else { - playPauseButton.setImageResource(R.drawable.circle_pause_button); - play = true; - if (!indefiniteSamplesCheckBox.isChecked()) { - counter = Integer.parseInt(samplesEditBox.getText().toString()); - } - } - } - }); - sensorDock.setVisibility(View.VISIBLE); - - indefiniteSamplesCheckBox.setChecked(true); - samplesEditBox.setEnabled(false); - indefiniteSamplesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - runIndefinitely = true; - samplesEditBox.setEnabled(false); - } else { - runIndefinitely = false; - samplesEditBox.setEnabled(true); - } - } - }); - - timeGapSeekbar.setMax((max - min) / step); - timeGapSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - timeGap = min + (progress * step); - timeGapLabel.setText(timeGap + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - } - - private class SensorDataFetch extends AsyncTask { - - private ArrayList dataSHT21Temp = new ArrayList<>(); - private ArrayList dataSHT21Humidity = new ArrayList<>(); - private long timeElapsed; - - @Override - protected Void doInBackground(Void... params) { - try { - if (sensorSHT21 != null) { - sensorSHT21.selectParameter("temperature"); - dataSHT21Temp = sensorSHT21.getRaw(); - sensorSHT21.selectParameter("humidity"); - dataSHT21Humidity = sensorSHT21.getRaw(); - } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - entriesTemperature.add(new Entry((float) timeElapsed, dataSHT21Temp.get(0).floatValue())); - entriesTemperature.add(new Entry((float) timeElapsed, dataSHT21Humidity.get(0).floatValue())); - return null; - } - - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - tvSensorSHT21Temp.setText(DataFormatter.formatDouble(dataSHT21Temp.get(0), DataFormatter.HIGH_PRECISION_FORMAT)); - tvSensorSHT21Humidity.setText(DataFormatter.formatDouble(dataSHT21Humidity.get(0), DataFormatter.HIGH_PRECISION_FORMAT)); - - LineDataSet dataSet1 = new LineDataSet(entriesTemperature, getString(R.string.temperature)); - LineDataSet dataSet2 = new LineDataSet(entriesHumidity, getString(R.string.humidity)); - - dataSet1.setDrawCircles(true); - dataSet2.setDrawCircles(true); - - LineData data = new LineData(dataSet1); - mChartTemperature.setData(data); - mChartTemperature.notifyDataSetChanged(); - mChartTemperature.setVisibleXRangeMaximum(10); - mChartTemperature.moveViewToX(data.getEntryCount()); - mChartTemperature.invalidate(); - - LineData data2 = new LineData(dataSet2); - mChartHumidity.setData(data2); - mChartHumidity.notifyDataSetChanged(); - mChartHumidity.setVisibleXRangeMaximum(10); - mChartHumidity.moveViewToX(data2.getEntryCount()); - mChartHumidity.invalidate(); - samplesEditBox.setText(String.valueOf(counter)); - if (counter == 0 && !runIndefinitely) { - play = false; - playPauseButton.setImageResource(R.drawable.circle_play_button); - } - synchronized (lock) { - lock.notify(); - } - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/sensors/SensorTSL2561.java b/app/src/main/java/io/pslab/sensors/SensorTSL2561.java deleted file mode 100644 index 805d566cf..000000000 --- a/app/src/main/java/io/pslab/sensors/SensorTSL2561.java +++ /dev/null @@ -1,341 +0,0 @@ -package io.pslab.sensors; - -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.View; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; -import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.TSL2561; -import io.pslab.others.ScienceLabCommon; - -/** - * Created by Harsh on 6/6/18. - */ - -public class SensorTSL2561 extends AppCompatActivity { - private static int counter; - private final Object lock = new Object(); - private ScienceLab scienceLab; - private SensorTSL2561.SensorDataFetch sensorDataFetch; - private TextView tvSensorTSL2561FullSpectrum; - private TextView tvSensorTSL2561Infrared; - private TextView tvSensorTSL2561Visible; - private EditText etSensorTSL2561Timing; - private TSL2561 sensorTSL2561; - private LineChart mChart; - private long startTime; - private int flag; - private ArrayList entriesFull; - private ArrayList entriesInfrared; - private ArrayList entriesVisible; - private RelativeLayout sensorDock; - private CheckBox indefiniteSamplesCheckBox; - private EditText samplesEditBox; - private SeekBar timeGapSeekbar; - private TextView timeGapLabel; - private ImageButton playPauseButton; - private boolean play; - private boolean runIndefinitely; - private int timeGap; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.sensor_tsl2561); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.tsl2561); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - sensorDock = findViewById(R.id.sensor_control_dock_layout); - indefiniteSamplesCheckBox = findViewById(R.id.checkBox_samples_sensor); - samplesEditBox = findViewById(R.id.editBox_samples_sensors); - timeGapSeekbar = findViewById(R.id.seekBar_timegap_sensor); - timeGapLabel = findViewById(R.id.tv_timegap_label); - playPauseButton = findViewById(R.id.imageButton_play_pause_sensor); - setSensorDock(); - sensorDock.setVisibility(View.VISIBLE); - - scienceLab = ScienceLabCommon.scienceLab; - I2C i2c = scienceLab.i2c; - try { - sensorTSL2561 = new TSL2561(i2c, scienceLab); - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - - entriesFull = new ArrayList<>(); - entriesInfrared = new ArrayList<>(); - entriesVisible = new ArrayList<>(); - - Runnable runnable = new Runnable() { - @Override - public void run() { - while (true) { - if (scienceLab.isConnected() && shouldPlay()) { - try { - sensorDataFetch = new SensorTSL2561.SensorDataFetch(); - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - sensorDataFetch.execute(); - if (flag == 0) { - startTime = System.currentTimeMillis(); - flag = 1; - } - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - try { - Thread.sleep(timeGap); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - }; - new Thread(runnable).start(); - - tvSensorTSL2561FullSpectrum = findViewById(R.id.tv_sensor_tsl2561_full); - tvSensorTSL2561Infrared = findViewById(R.id.tv_sensor_tsl2561_infrared); - tvSensorTSL2561Visible = findViewById(R.id.tv_sensor_tsl2561_visible); - Spinner spinnerSensorTSL2561Gain = findViewById(R.id.spinner_sensor_tsl2561_gain); - etSensorTSL2561Timing = findViewById(R.id.et_sensor_tsl2561_timing); - mChart = findViewById(R.id.chart_tsl2561); - - try { - if (sensorTSL2561 != null & scienceLab.isConnected()) { - sensorTSL2561.setGain(spinnerSensorTSL2561Gain.getSelectedItem().toString()); - } - } catch (IOException e) { - e.printStackTrace(); - } - - XAxis x = mChart.getXAxis(); - YAxis y = mChart.getAxisLeft(); - YAxis y2 = mChart.getAxisRight(); - - mChart.setTouchEnabled(true); - mChart.setHighlightPerDragEnabled(true); - mChart.setDragEnabled(true); - mChart.setScaleEnabled(true); - mChart.setDrawGridBackground(false); - mChart.setPinchZoom(true); - mChart.setScaleYEnabled(false); - mChart.setBackgroundColor(Color.BLACK); - mChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mChart.setData(data); - - Legend l = mChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(1700f); - y.setAxisMinimum(0f); - y.setDrawGridLines(true); - y.setLabelCount(10); - - y2.setDrawGridLines(false); - - - } - - private boolean shouldPlay() { - if (play) { - if (indefiniteSamplesCheckBox.isChecked()) - return true; - else if (counter >= 0) { - counter--; - return true; - } else { - play = false; - return false; - } - } else { - return false; - } - } - - private void setSensorDock() { - play = false; - runIndefinitely = true; - timeGap = 100; - final int step = 1; - final int max = 1000; - final int min = 100; - - playPauseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (play && scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else if (!scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else { - playPauseButton.setImageResource(R.drawable.circle_pause_button); - play = true; - if (!indefiniteSamplesCheckBox.isChecked()) { - counter = Integer.parseInt(samplesEditBox.getText().toString()); - } - } - } - }); - sensorDock.setVisibility(View.VISIBLE); - - indefiniteSamplesCheckBox.setChecked(true); - samplesEditBox.setEnabled(false); - indefiniteSamplesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - runIndefinitely = true; - samplesEditBox.setEnabled(false); - } else { - runIndefinitely = false; - samplesEditBox.setEnabled(true); - } - } - }); - - timeGapSeekbar.setMax((max - min) / step); - timeGapSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - timeGap = min + (progress * step); - timeGapLabel.setText(timeGap + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - } - - private class SensorDataFetch extends AsyncTask { - - private int[] dataTSL2561; - private long timeElapsed; - - private SensorDataFetch() throws IOException, InterruptedException { - } - - @Override - protected Void doInBackground(Void... params) { - try { - if (sensorTSL2561 != null) { - dataTSL2561 = sensorTSL2561.getRaw(); - } - } catch (IOException e) { - e.printStackTrace(); - } - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - entriesFull.add(new Entry((float) timeElapsed, dataTSL2561[0])); - entriesInfrared.add(new Entry((float) timeElapsed, dataTSL2561[1])); - entriesVisible.add(new Entry((float) timeElapsed, dataTSL2561[2])); - return null; - } - - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - tvSensorTSL2561FullSpectrum.setText(String.valueOf(dataTSL2561[0])); - tvSensorTSL2561Infrared.setText(String.valueOf(dataTSL2561[1])); - tvSensorTSL2561Visible.setText(String.valueOf(dataTSL2561[2])); - - LineDataSet dataset1 = new LineDataSet(entriesFull, getString(R.string.full)); - LineDataSet dataSet2 = new LineDataSet(entriesInfrared, getString(R.string.infrared)); - LineDataSet dataSet3 = new LineDataSet(entriesVisible, getString(R.string.visible)); - - dataset1.setColor(Color.BLUE); - dataSet2.setColor(Color.GREEN); - dataSet3.setColor(Color.RED); - - dataset1.setDrawCircles(true); - dataSet2.setDrawCircles(true); - dataSet3.setDrawCircles(true); - - List dataSets = new ArrayList<>(); - dataSets.add(dataset1); - dataSets.add(dataSet2); - dataSets.add(dataSet3); - - LineData data = new LineData(dataSets); - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(10); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - samplesEditBox.setText(String.valueOf(counter)); - if (counter == 0 && !runIndefinitely) { - play = false; - playPauseButton.setImageResource(R.drawable.circle_play_button); - } - synchronized (lock) { - lock.notify(); - } - } - } - - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return true; - } -} diff --git a/app/src/main/java/io/pslab/sensors/SensorVL53L0X.java b/app/src/main/java/io/pslab/sensors/SensorVL53L0X.java deleted file mode 100644 index c45b3a041..000000000 --- a/app/src/main/java/io/pslab/sensors/SensorVL53L0X.java +++ /dev/null @@ -1,289 +0,0 @@ -package io.pslab.sensors; - -import android.graphics.Color; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.View; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; -import com.github.mikephil.charting.data.Entry; -import com.github.mikephil.charting.data.LineData; -import com.github.mikephil.charting.data.LineDataSet; - -import java.io.IOException; -import java.util.ArrayList; - -import io.pslab.R; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.ADS1115; -import io.pslab.communication.sensors.VL53L0X; -import io.pslab.others.ScienceLabCommon; - -public class SensorVL53L0X extends AppCompatActivity { - private static int counter; - private final Object lock = new Object(); - private ScienceLab scienceLab; - private SensorVL53L0X.SensorDataFetch sensorDataFetch; - private TextView tvSensorVL53L0X; - private LineChart mChart; - private long startTime; - private int flag; - private ArrayList entries; - private RelativeLayout sensorDock; - private CheckBox indefiniteSamplesCheckBox; - private EditText samplesEditBox; - private SeekBar timeGapSeekbar; - private TextView timeGapLabel; - private ImageButton playPauseButton; - private boolean play; - private boolean runIndefinitely; - private int timeGap; - - private VL53L0X sensorVL53L0X; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.sensor_vl53l0x); - - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - final ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setTitle(R.string.vl53l0x); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); - } - - sensorDock = findViewById(R.id.sensor_control_dock_layout); - indefiniteSamplesCheckBox = findViewById(R.id.checkBox_samples_sensor); - samplesEditBox = findViewById(R.id.editBox_samples_sensors); - timeGapSeekbar = findViewById(R.id.seekBar_timegap_sensor); - timeGapLabel = findViewById(R.id.tv_timegap_label); - playPauseButton = findViewById(R.id.imageButton_play_pause_sensor); - setSensorDock(); - sensorDock.setVisibility(View.VISIBLE); - - scienceLab = ScienceLabCommon.scienceLab; - I2C i2c = scienceLab.i2c; - entries = new ArrayList<>(); - try { - sensorVL53L0X = new VL53L0X(i2c, scienceLab); - } catch (Exception e) { - e.printStackTrace(); - } - - Runnable runnable = new Runnable() { - @Override - public void run() { - while (true) { - if (scienceLab.isConnected() && shouldPlay()) { - sensorDataFetch = new SensorVL53L0X.SensorDataFetch(); - sensorDataFetch.execute(); - if (flag == 0) { - startTime = System.currentTimeMillis(); - flag = 1; - } - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - try { - Thread.sleep(timeGap); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - }; - new Thread(runnable).start(); - - tvSensorVL53L0X = findViewById(R.id.tv_sensor_vl53l0x); - mChart = findViewById(R.id.chart_sensor_ads); - XAxis x = mChart.getXAxis(); - YAxis y = mChart.getAxisLeft(); - YAxis y2 = mChart.getAxisRight(); - - mChart.setTouchEnabled(true); - mChart.setHighlightPerDragEnabled(true); - mChart.setDragEnabled(true); - mChart.setScaleEnabled(true); - mChart.setDrawGridBackground(false); - mChart.setPinchZoom(true); - mChart.setScaleYEnabled(false); - mChart.setBackgroundColor(Color.BLACK); - mChart.getDescription().setEnabled(false); - - LineData data = new LineData(); - data.setValueTextColor(Color.WHITE); - mChart.setData(data); - - Legend l = mChart.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(10000f); - y.setAxisMinimum(0); - y.setDrawGridLines(true); - y.setLabelCount(10); - - y2.setDrawGridLines(false); - } - - private boolean shouldPlay() { - if (play) { - if (indefiniteSamplesCheckBox.isChecked()) - return true; - else if (counter >= 0) { - counter--; - return true; - } else { - play = false; - return false; - } - } else { - return false; - } - } - - private void setSensorDock() { - play = false; - runIndefinitely = true; - timeGap = 100; - final int step = 1; - final int max = 1000; - final int min = 100; - - playPauseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (play && scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else if (!scienceLab.isConnected()) { - playPauseButton.setImageResource(R.drawable.circle_play_button); - play = false; - } else { - playPauseButton.setImageResource(R.drawable.circle_pause_button); - play = true; - if (!indefiniteSamplesCheckBox.isChecked()) { - counter = Integer.parseInt(samplesEditBox.getText().toString()); - } - } - } - }); - sensorDock.setVisibility(View.VISIBLE); - - indefiniteSamplesCheckBox.setChecked(true); - samplesEditBox.setEnabled(false); - indefiniteSamplesCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - runIndefinitely = true; - samplesEditBox.setEnabled(false); - } else { - runIndefinitely = false; - samplesEditBox.setEnabled(true); - } - } - }); - - timeGapSeekbar.setMax((max - min) / step); - timeGapSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - timeGap = min + (progress * step); - timeGapLabel.setText(timeGap + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - // Do nothing - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - // Do nothing - } - }); - } - - private class SensorDataFetch extends AsyncTask { - - private int dataVL53L0X; - private long timeElapsed; - - @Override - protected Void doInBackground(Void... params) { - try { - if (sensorVL53L0X != null) { - dataVL53L0X = sensorVL53L0X.getRaw(); - } - } catch (Exception e) { - e.printStackTrace(); - } - - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - entries.add(new Entry((float) timeElapsed, dataVL53L0X)); - - return null; - } - - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - tvSensorVL53L0X.setText(String.valueOf(dataVL53L0X)); - - LineDataSet dataSet = new LineDataSet(entries, getString(R.string.bx)); - dataSet.setDrawCircles(true); - LineData data = new LineData(dataSet); - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.setVisibleXRangeMaximum(10); - mChart.moveViewToX(data.getEntryCount()); - mChart.invalidate(); - samplesEditBox.setText(String.valueOf(counter)); - if (counter == 0 && !runIndefinitely) { - play = false; - playPauseButton.setImageResource(R.drawable.circle_play_button); - } - synchronized (lock) { - lock.notify(); - } - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - } - return true; - } -} diff --git a/app/src/main/res/anim/fade_in.xml b/app/src/main/res/anim/fade_in.xml deleted file mode 100644 index 8bbd341c3..000000000 --- a/app/src/main/res/anim/fade_in.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/app/src/main/res/anim/fade_out.xml b/app/src/main/res/anim/fade_out.xml deleted file mode 100644 index e419507e2..000000000 --- a/app/src/main/res/anim/fade_out.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/app/src/main/res/animator-v21/selector_animator.xml b/app/src/main/res/animator-v21/selector_animator.xml deleted file mode 100644 index 502f18fe7..000000000 --- a/app/src/main/res/animator-v21/selector_animator.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable-hdpi/compass_icon.png b/app/src/main/res/drawable-hdpi/compass_icon.png deleted file mode 100644 index 985d88e6f..000000000 Binary files a/app/src/main/res/drawable-hdpi/compass_icon.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_pwm_pic.png b/app/src/main/res/drawable-hdpi/ic_pwm_pic.png deleted file mode 100644 index a17fcacd5..000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_pwm_pic.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_sin.png b/app/src/main/res/drawable-hdpi/ic_sin.png deleted file mode 100644 index b9a6c52e9..000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_sin.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_square.png b/app/src/main/res/drawable-hdpi/ic_square.png deleted file mode 100644 index fdad65fd1..000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_square.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_triangular.png b/app/src/main/res/drawable-hdpi/ic_triangular.png deleted file mode 100644 index 22074d047..000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_triangular.png and /dev/null differ diff --git a/app/src/main/res/drawable-ldpi/compass_icon.png b/app/src/main/res/drawable-ldpi/compass_icon.png deleted file mode 100644 index 1f3c4662e..000000000 Binary files a/app/src/main/res/drawable-ldpi/compass_icon.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/compass_icon.png b/app/src/main/res/drawable-mdpi/compass_icon.png deleted file mode 100644 index b8a0d05e1..000000000 Binary files a/app/src/main/res/drawable-mdpi/compass_icon.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_pwm_pic.png b/app/src/main/res/drawable-mdpi/ic_pwm_pic.png deleted file mode 100644 index 3ac1e45b1..000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_pwm_pic.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_sin.png b/app/src/main/res/drawable-mdpi/ic_sin.png deleted file mode 100644 index 7a8ff9769..000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_sin.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_square.png b/app/src/main/res/drawable-mdpi/ic_square.png deleted file mode 100644 index 89621dbc3..000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_square.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_triangular.png b/app/src/main/res/drawable-mdpi/ic_triangular.png deleted file mode 100644 index d0a91b0e1..000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_triangular.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/rectangle_border_black.xml b/app/src/main/res/drawable-mdpi/rectangle_border_black.xml deleted file mode 100644 index 0d33d7e03..000000000 --- a/app/src/main/res/drawable-mdpi/rectangle_border_black.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable-xhdpi/compass_icon.png b/app/src/main/res/drawable-xhdpi/compass_icon.png deleted file mode 100644 index 44cbd3d02..000000000 Binary files a/app/src/main/res/drawable-xhdpi/compass_icon.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_pwm_pic.png b/app/src/main/res/drawable-xhdpi/ic_pwm_pic.png deleted file mode 100644 index b2a7495f0..000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_pwm_pic.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_sin.png b/app/src/main/res/drawable-xhdpi/ic_sin.png deleted file mode 100644 index c308d4eec..000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_sin.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_square.png b/app/src/main/res/drawable-xhdpi/ic_square.png deleted file mode 100644 index cf75cdff9..000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_square.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_triangular.png b/app/src/main/res/drawable-xhdpi/ic_triangular.png deleted file mode 100644 index 3bc641ce3..000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_triangular.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_square.png b/app/src/main/res/drawable-xxhdpi/ic_square.png deleted file mode 100644 index 3b17a62d8..000000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_square.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/tile_icon_gas.xml b/app/src/main/res/drawable-xxhdpi/tile_icon_gas.xml deleted file mode 100644 index 47ab25e20..000000000 --- a/app/src/main/res/drawable-xxhdpi/tile_icon_gas.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - diff --git a/app/src/main/res/drawable-xxxhdpi/compass_icon.png b/app/src/main/res/drawable-xxxhdpi/compass_icon.png deleted file mode 100644 index fbe46d8d9..000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/compass_icon.png and /dev/null differ diff --git a/app/src/main/res/drawable/action_item_advanced.png b/app/src/main/res/drawable/action_item_advanced.png deleted file mode 100644 index 9fb20aeae..000000000 Binary files a/app/src/main/res/drawable/action_item_advanced.png and /dev/null differ diff --git a/app/src/main/res/drawable/action_item_main.png b/app/src/main/res/drawable/action_item_main.png deleted file mode 100644 index b6a6fe498..000000000 Binary files a/app/src/main/res/drawable/action_item_main.png and /dev/null differ diff --git a/app/src/main/res/drawable/action_item_read.png b/app/src/main/res/drawable/action_item_read.png deleted file mode 100644 index 80bf15c59..000000000 Binary files a/app/src/main/res/drawable/action_item_read.png and /dev/null differ diff --git a/app/src/main/res/drawable/app_icon.png b/app/src/main/res/drawable/app_icon.png deleted file mode 100644 index 09da1420b..000000000 Binary files a/app/src/main/res/drawable/app_icon.png and /dev/null differ diff --git a/app/src/main/res/drawable/baseline_article_24.xml b/app/src/main/res/drawable/baseline_article_24.xml deleted file mode 100644 index 30d5d26b9..000000000 --- a/app/src/main/res/drawable/baseline_article_24.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/app/src/main/res/drawable/baseline_attribution_24.xml b/app/src/main/res/drawable/baseline_attribution_24.xml deleted file mode 100644 index 9278d2133..000000000 --- a/app/src/main/res/drawable/baseline_attribution_24.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/app/src/main/res/drawable/baseline_menu_book_24.xml b/app/src/main/res/drawable/baseline_menu_book_24.xml deleted file mode 100644 index 10d9f76b5..000000000 --- a/app/src/main/res/drawable/baseline_menu_book_24.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/app/src/main/res/drawable/baseline_star_24.xml b/app/src/main/res/drawable/baseline_star_24.xml deleted file mode 100644 index 9b295a03c..000000000 --- a/app/src/main/res/drawable/baseline_star_24.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/app/src/main/res/drawable/bg_circle.xml b/app/src/main/res/drawable/bg_circle.xml deleted file mode 100644 index 88f4995a4..000000000 --- a/app/src/main/res/drawable/bg_circle.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/bmp180_schematic.png b/app/src/main/res/drawable/bmp180_schematic.png deleted file mode 100644 index e78c752f5..000000000 Binary files a/app/src/main/res/drawable/bmp180_schematic.png and /dev/null differ diff --git a/app/src/main/res/drawable/btn_back_rounded.xml b/app/src/main/res/drawable/btn_back_rounded.xml deleted file mode 100644 index 35e099f47..000000000 --- a/app/src/main/res/drawable/btn_back_rounded.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/btn_back_rounded_light.xml b/app/src/main/res/drawable/btn_back_rounded_light.xml deleted file mode 100644 index 0965b8c5b..000000000 --- a/app/src/main/res/drawable/btn_back_rounded_light.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - diff --git a/app/src/main/res/drawable/btn_sheet_back.xml b/app/src/main/res/drawable/btn_sheet_back.xml deleted file mode 100644 index a9582b7c0..000000000 --- a/app/src/main/res/drawable/btn_sheet_back.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/button_clicked.xml b/app/src/main/res/drawable/button_clicked.xml deleted file mode 100644 index c6965284e..000000000 --- a/app/src/main/res/drawable/button_clicked.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/button_normal.xml b/app/src/main/res/drawable/button_normal.xml deleted file mode 100644 index 928de7f1f..000000000 --- a/app/src/main/res/drawable/button_normal.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/capacitor.png b/app/src/main/res/drawable/capacitor.png deleted file mode 100644 index cd6669cce..000000000 Binary files a/app/src/main/res/drawable/capacitor.png and /dev/null differ diff --git a/app/src/main/res/drawable/carousel_view_background.xml b/app/src/main/res/drawable/carousel_view_background.xml deleted file mode 100644 index 09f235cc2..000000000 --- a/app/src/main/res/drawable/carousel_view_background.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/ccs811.jpg b/app/src/main/res/drawable/ccs811.jpg deleted file mode 100644 index 5d69742f2..000000000 Binary files a/app/src/main/res/drawable/ccs811.jpg and /dev/null differ diff --git a/app/src/main/res/drawable/circle_pause_button.xml b/app/src/main/res/drawable/circle_pause_button.xml deleted file mode 100644 index 2a15db43a..000000000 --- a/app/src/main/res/drawable/circle_pause_button.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/circle_play_button.xml b/app/src/main/res/drawable/circle_play_button.xml deleted file mode 100644 index e7b6e6324..000000000 --- a/app/src/main/res/drawable/circle_play_button.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/compass_help_icon.xml b/app/src/main/res/drawable/compass_help_icon.xml deleted file mode 100644 index 757b585c5..000000000 --- a/app/src/main/res/drawable/compass_help_icon.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/control_custom_border.xml b/app/src/main/res/drawable/control_custom_border.xml deleted file mode 100644 index e8282afc1..000000000 --- a/app/src/main/res/drawable/control_custom_border.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/control_edittext.xml b/app/src/main/res/drawable/control_edittext.xml deleted file mode 100644 index 58075abd4..000000000 --- a/app/src/main/res/drawable/control_edittext.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/create_config_icon.xml b/app/src/main/res/drawable/create_config_icon.xml deleted file mode 100644 index a4dd6d23b..000000000 --- a/app/src/main/res/drawable/create_config_icon.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/delete_icon.xml b/app/src/main/res/drawable/delete_icon.xml deleted file mode 100755 index 7e8e3ce02..000000000 --- a/app/src/main/res/drawable/delete_icon.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/dialog_body_background.xml b/app/src/main/res/drawable/dialog_body_background.xml deleted file mode 100644 index 9af2cdd54..000000000 --- a/app/src/main/res/drawable/dialog_body_background.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/dialog_header_background.xml b/app/src/main/res/drawable/dialog_header_background.xml deleted file mode 100644 index a9acd5f6f..000000000 --- a/app/src/main/res/drawable/dialog_header_background.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/find_mobile_axis.png b/app/src/main/res/drawable/find_mobile_axis.png deleted file mode 100644 index f1f666a79..000000000 Binary files a/app/src/main/res/drawable/find_mobile_axis.png and /dev/null differ diff --git a/app/src/main/res/drawable/green_led.png b/app/src/main/res/drawable/green_led.png deleted file mode 100644 index d7987b7aa..000000000 Binary files a/app/src/main/res/drawable/green_led.png and /dev/null differ diff --git a/app/src/main/res/drawable/gyroscope_logdata_logo.png b/app/src/main/res/drawable/gyroscope_logdata_logo.png deleted file mode 100644 index 847068197..000000000 Binary files a/app/src/main/res/drawable/gyroscope_logdata_logo.png and /dev/null differ diff --git a/app/src/main/res/drawable/gyroscope_logo.xml b/app/src/main/res/drawable/gyroscope_logo.xml deleted file mode 100644 index 0c2cc2e30..000000000 --- a/app/src/main/res/drawable/gyroscope_logo.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/hmc5883l.jpg b/app/src/main/res/drawable/hmc5883l.jpg deleted file mode 100644 index 00de91740..000000000 Binary files a/app/src/main/res/drawable/hmc5883l.jpg and /dev/null differ diff --git a/app/src/main/res/drawable/ic_android_black_24dp.xml b/app/src/main/res/drawable/ic_android_black_24dp.xml deleted file mode 100644 index 401cbf63b..000000000 --- a/app/src/main/res/drawable/ic_android_black_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_apps_black_24dp.xml b/app/src/main/res/drawable/ic_apps_black_24dp.xml deleted file mode 100644 index ff485cf1a..000000000 --- a/app/src/main/res/drawable/ic_apps_black_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_arrow_back_white_24dp.xml b/app/src/main/res/drawable/ic_arrow_back_white_24dp.xml deleted file mode 100644 index 563937bf1..000000000 --- a/app/src/main/res/drawable/ic_arrow_back_white_24dp.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_arrow_drop_down_black_24dp.xml b/app/src/main/res/drawable/ic_arrow_drop_down_black_24dp.xml deleted file mode 100644 index 6f45c6ee6..000000000 --- a/app/src/main/res/drawable/ic_arrow_drop_down_black_24dp.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_arrow_drop_down_white_24dp.xml b/app/src/main/res/drawable/ic_arrow_drop_down_white_24dp.xml deleted file mode 100644 index b89b1bbf1..000000000 --- a/app/src/main/res/drawable/ic_arrow_drop_down_white_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_arrow_drop_up_black_24dp.xml b/app/src/main/res/drawable/ic_arrow_drop_up_black_24dp.xml deleted file mode 100644 index 3ea9d609c..000000000 --- a/app/src/main/res/drawable/ic_arrow_drop_up_black_24dp.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_arrow_drop_up_white_24dp.xml b/app/src/main/res/drawable/ic_arrow_drop_up_white_24dp.xml deleted file mode 100644 index acea1e92c..000000000 --- a/app/src/main/res/drawable/ic_arrow_drop_up_white_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_arrow_left_24dp.xml b/app/src/main/res/drawable/ic_arrow_left_24dp.xml deleted file mode 100644 index b79d00f6e..000000000 --- a/app/src/main/res/drawable/ic_arrow_left_24dp.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_arrow_right_24dp.xml b/app/src/main/res/drawable/ic_arrow_right_24dp.xml deleted file mode 100644 index ff5a73fff..000000000 --- a/app/src/main/res/drawable/ic_arrow_right_24dp.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_bug_report_black_24dp.png b/app/src/main/res/drawable/ic_bug_report_black_24dp.png deleted file mode 100644 index 6eb1474e3..000000000 Binary files a/app/src/main/res/drawable/ic_bug_report_black_24dp.png and /dev/null differ diff --git a/app/src/main/res/drawable/ic_delete_red_24dp.xml b/app/src/main/res/drawable/ic_delete_red_24dp.xml deleted file mode 100644 index 3e7908563..000000000 --- a/app/src/main/res/drawable/ic_delete_red_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_developer_board_black_24dp.xml b/app/src/main/res/drawable/ic_developer_board_black_24dp.xml deleted file mode 100644 index 27d3805f0..000000000 --- a/app/src/main/res/drawable/ic_developer_board_black_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_export_file.xml b/app/src/main/res/drawable/ic_export_file.xml deleted file mode 100644 index 88b8e4673..000000000 --- a/app/src/main/res/drawable/ic_export_file.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - diff --git a/app/src/main/res/drawable/ic_feedback_black_24dp.png b/app/src/main/res/drawable/ic_feedback_black_24dp.png deleted file mode 100644 index 1343fa837..000000000 Binary files a/app/src/main/res/drawable/ic_feedback_black_24dp.png and /dev/null differ diff --git a/app/src/main/res/drawable/ic_fullscreen_black_24dp.xml b/app/src/main/res/drawable/ic_fullscreen_black_24dp.xml deleted file mode 100644 index 8bb67b6c5..000000000 --- a/app/src/main/res/drawable/ic_fullscreen_black_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_info_black_24dp.png b/app/src/main/res/drawable/ic_info_black_24dp.png deleted file mode 100644 index c8f86b925..000000000 Binary files a/app/src/main/res/drawable/ic_info_black_24dp.png and /dev/null differ diff --git a/app/src/main/res/drawable/ic_map_red_24dp.xml b/app/src/main/res/drawable/ic_map_red_24dp.xml deleted file mode 100644 index 07885fb63..000000000 --- a/app/src/main/res/drawable/ic_map_red_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_nav_header_logo.xml b/app/src/main/res/drawable/ic_nav_header_logo.xml deleted file mode 100644 index 34661c2f6..000000000 --- a/app/src/main/res/drawable/ic_nav_header_logo.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - diff --git a/app/src/main/res/drawable/ic_pause_white_24dp.xml b/app/src/main/res/drawable/ic_pause_white_24dp.xml deleted file mode 100644 index baf8f08b3..000000000 --- a/app/src/main/res/drawable/ic_pause_white_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_play_arrow_white_24dp.xml b/app/src/main/res/drawable/ic_play_arrow_white_24dp.xml deleted file mode 100644 index 7e05ffccf..000000000 --- a/app/src/main/res/drawable/ic_play_arrow_white_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_play_button.xml b/app/src/main/res/drawable/ic_play_button.xml deleted file mode 100644 index bf2ad5b07..000000000 --- a/app/src/main/res/drawable/ic_play_button.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_record_stop_white.xml b/app/src/main/res/drawable/ic_record_stop_white.xml deleted file mode 100644 index ff13e3487..000000000 --- a/app/src/main/res/drawable/ic_record_stop_white.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - diff --git a/app/src/main/res/drawable/ic_record_white.xml b/app/src/main/res/drawable/ic_record_white.xml deleted file mode 100644 index ec6323806..000000000 --- a/app/src/main/res/drawable/ic_record_white.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - diff --git a/app/src/main/res/drawable/ic_settings_black_24dp.xml b/app/src/main/res/drawable/ic_settings_black_24dp.xml deleted file mode 100644 index ace746c40..000000000 --- a/app/src/main/res/drawable/ic_settings_black_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_shopping_cart_black_24dp.xml b/app/src/main/res/drawable/ic_shopping_cart_black_24dp.xml deleted file mode 100644 index 11887e38f..000000000 --- a/app/src/main/res/drawable/ic_shopping_cart_black_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_stop_white_24dp.xml b/app/src/main/res/drawable/ic_stop_white_24dp.xml deleted file mode 100644 index 86b8cd2de..000000000 --- a/app/src/main/res/drawable/ic_stop_white_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_usb_connected.xml b/app/src/main/res/drawable/ic_usb_connected.xml deleted file mode 100644 index 59b3ad703..000000000 --- a/app/src/main/res/drawable/ic_usb_connected.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_usb_disconnected.xml b/app/src/main/res/drawable/ic_usb_disconnected.xml deleted file mode 100644 index ec696e430..000000000 --- a/app/src/main/res/drawable/ic_usb_disconnected.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_user__24dp.xml b/app/src/main/res/drawable/ic_user__24dp.xml deleted file mode 100644 index 1936c32f1..000000000 --- a/app/src/main/res/drawable/ic_user__24dp.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_widgets_black_24dp.xml b/app/src/main/res/drawable/ic_widgets_black_24dp.xml deleted file mode 100644 index 4abb823f8..000000000 --- a/app/src/main/res/drawable/ic_widgets_black_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_wifi_tethering_black_24dp.xml b/app/src/main/res/drawable/ic_wifi_tethering_black_24dp.xml deleted file mode 100644 index 4e021adaa..000000000 --- a/app/src/main/res/drawable/ic_wifi_tethering_black_24dp.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/icon_logic_analyzer_white.xml b/app/src/main/res/drawable/icon_logic_analyzer_white.xml deleted file mode 100644 index 933d8c7fc..000000000 --- a/app/src/main/res/drawable/icon_logic_analyzer_white.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/icon_oscilloscope_white.xml b/app/src/main/res/drawable/icon_oscilloscope_white.xml deleted file mode 100644 index 8aa5db4ff..000000000 --- a/app/src/main/res/drawable/icon_oscilloscope_white.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - diff --git a/app/src/main/res/drawable/knob.xml b/app/src/main/res/drawable/knob.xml deleted file mode 100644 index 447fa9c93..000000000 --- a/app/src/main/res/drawable/knob.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/knob_base.xml b/app/src/main/res/drawable/knob_base.xml deleted file mode 100644 index 843f9b298..000000000 --- a/app/src/main/res/drawable/knob_base.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/la_chart_custom_border.xml b/app/src/main/res/drawable/la_chart_custom_border.xml deleted file mode 100644 index c66955abe..000000000 --- a/app/src/main/res/drawable/la_chart_custom_border.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/la_custom_border.xml b/app/src/main/res/drawable/la_custom_border.xml deleted file mode 100644 index 43f586ea8..000000000 --- a/app/src/main/res/drawable/la_custom_border.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/la_formatted_button.xml b/app/src/main/res/drawable/la_formatted_button.xml deleted file mode 100644 index 359d428d0..000000000 --- a/app/src/main/res/drawable/la_formatted_button.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/logo200x200.png b/app/src/main/res/drawable/logo200x200.png deleted file mode 100644 index effdfbab9..000000000 Binary files a/app/src/main/res/drawable/logo200x200.png and /dev/null differ diff --git a/app/src/main/res/drawable/menu_icon_guide.xml b/app/src/main/res/drawable/menu_icon_guide.xml deleted file mode 100644 index 6e1584405..000000000 --- a/app/src/main/res/drawable/menu_icon_guide.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/menu_icon_map.xml b/app/src/main/res/drawable/menu_icon_map.xml deleted file mode 100644 index 265f9ebc2..000000000 --- a/app/src/main/res/drawable/menu_icon_map.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/menu_icon_save.xml b/app/src/main/res/drawable/menu_icon_save.xml deleted file mode 100644 index 5ac6640cc..000000000 --- a/app/src/main/res/drawable/menu_icon_save.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/mlx90614.jpg b/app/src/main/res/drawable/mlx90614.jpg deleted file mode 100644 index c9cadf1a2..000000000 Binary files a/app/src/main/res/drawable/mlx90614.jpg and /dev/null differ diff --git a/app/src/main/res/drawable/mlx90614_schematic.png b/app/src/main/res/drawable/mlx90614_schematic.png deleted file mode 100644 index 9fd28bfd3..000000000 Binary files a/app/src/main/res/drawable/mlx90614_schematic.png and /dev/null differ diff --git a/app/src/main/res/drawable/nav_header_logo.png b/app/src/main/res/drawable/nav_header_logo.png deleted file mode 100644 index 09b19eec4..000000000 Binary files a/app/src/main/res/drawable/nav_header_logo.png and /dev/null differ diff --git a/app/src/main/res/drawable/pause.png b/app/src/main/res/drawable/pause.png deleted file mode 100644 index b34ca580d..000000000 Binary files a/app/src/main/res/drawable/pause.png and /dev/null differ diff --git a/app/src/main/res/drawable/pause_icon.xml b/app/src/main/res/drawable/pause_icon.xml deleted file mode 100755 index 1802dd3db..000000000 --- a/app/src/main/res/drawable/pause_icon.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/play.png b/app/src/main/res/drawable/play.png deleted file mode 100644 index a9db0ea39..000000000 Binary files a/app/src/main/res/drawable/play.png and /dev/null differ diff --git a/app/src/main/res/drawable/pslab_v5_back_colormap.png b/app/src/main/res/drawable/pslab_v5_back_colormap.png deleted file mode 100644 index 4a9eeddbb..000000000 Binary files a/app/src/main/res/drawable/pslab_v5_back_colormap.png and /dev/null differ diff --git a/app/src/main/res/drawable/pslab_v5_back_layout.png b/app/src/main/res/drawable/pslab_v5_back_layout.png deleted file mode 100644 index ab7510231..000000000 Binary files a/app/src/main/res/drawable/pslab_v5_back_layout.png and /dev/null differ diff --git a/app/src/main/res/drawable/pslab_v5_front_colormap.png b/app/src/main/res/drawable/pslab_v5_front_colormap.png deleted file mode 100644 index 32957eecc..000000000 Binary files a/app/src/main/res/drawable/pslab_v5_front_colormap.png and /dev/null differ diff --git a/app/src/main/res/drawable/pslab_v5_front_layout.png b/app/src/main/res/drawable/pslab_v5_front_layout.png deleted file mode 100644 index aabb61fe5..000000000 Binary files a/app/src/main/res/drawable/pslab_v5_front_layout.png and /dev/null differ diff --git a/app/src/main/res/drawable/rectangle_border.xml b/app/src/main/res/drawable/rectangle_border.xml deleted file mode 100644 index 784d0b027..000000000 --- a/app/src/main/res/drawable/rectangle_border.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/red_led.png b/app/src/main/res/drawable/red_led.png deleted file mode 100644 index 6cd18b923..000000000 Binary files a/app/src/main/res/drawable/red_led.png and /dev/null differ diff --git a/app/src/main/res/drawable/robotic_arm.xml b/app/src/main/res/drawable/robotic_arm.xml deleted file mode 100644 index 6def11c69..000000000 --- a/app/src/main/res/drawable/robotic_arm.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/rounded_custom_border.xml b/app/src/main/res/drawable/rounded_custom_border.xml deleted file mode 100644 index e7ad4668f..000000000 --- a/app/src/main/res/drawable/rounded_custom_border.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/app/src/main/res/drawable/rounded_custom_border_2.xml b/app/src/main/res/drawable/rounded_custom_border_2.xml deleted file mode 100644 index 025466a8d..000000000 --- a/app/src/main/res/drawable/rounded_custom_border_2.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/app/src/main/res/drawable/selector_button.xml b/app/src/main/res/drawable/selector_button.xml deleted file mode 100644 index 21e6b4fc3..000000000 --- a/app/src/main/res/drawable/selector_button.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/servo_drag_handle.png b/app/src/main/res/drawable/servo_drag_handle.png deleted file mode 100644 index 12e2669a7..000000000 Binary files a/app/src/main/res/drawable/servo_drag_handle.png and /dev/null differ diff --git a/app/src/main/res/drawable/share_icon.png b/app/src/main/res/drawable/share_icon.png deleted file mode 100755 index 451d998d9..000000000 Binary files a/app/src/main/res/drawable/share_icon.png and /dev/null differ diff --git a/app/src/main/res/drawable/text.png b/app/src/main/res/drawable/text.png deleted file mode 100644 index f6087a7d2..000000000 Binary files a/app/src/main/res/drawable/text.png and /dev/null differ diff --git a/app/src/main/res/drawable/text_color_selector.xml b/app/src/main/res/drawable/text_color_selector.xml deleted file mode 100644 index 0e56de3f0..000000000 --- a/app/src/main/res/drawable/text_color_selector.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/thermometer_logo.xml b/app/src/main/res/drawable/thermometer_logo.xml deleted file mode 100644 index cc273b0e0..000000000 --- a/app/src/main/res/drawable/thermometer_logo.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_accelerometer.xml b/app/src/main/res/drawable/tile_icon_accelerometer.xml deleted file mode 100644 index d2db10273..000000000 --- a/app/src/main/res/drawable/tile_icon_accelerometer.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_barometer.xml b/app/src/main/res/drawable/tile_icon_barometer.xml deleted file mode 100644 index ebba14d06..000000000 --- a/app/src/main/res/drawable/tile_icon_barometer.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_barometer_log.xml b/app/src/main/res/drawable/tile_icon_barometer_log.xml deleted file mode 100644 index 18314c11c..000000000 --- a/app/src/main/res/drawable/tile_icon_barometer_log.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_compass.xml b/app/src/main/res/drawable/tile_icon_compass.xml deleted file mode 100644 index ed6401fe9..000000000 --- a/app/src/main/res/drawable/tile_icon_compass.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_compass_log.xml b/app/src/main/res/drawable/tile_icon_compass_log.xml deleted file mode 100644 index 4bd54e644..000000000 --- a/app/src/main/res/drawable/tile_icon_compass_log.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - diff --git a/app/src/main/res/drawable/tile_icon_horizontal_bars.xml b/app/src/main/res/drawable/tile_icon_horizontal_bars.xml deleted file mode 100644 index 0db0475fd..000000000 --- a/app/src/main/res/drawable/tile_icon_horizontal_bars.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - diff --git a/app/src/main/res/drawable/tile_icon_logic_analyzer.xml b/app/src/main/res/drawable/tile_icon_logic_analyzer.xml deleted file mode 100644 index 52cff074d..000000000 --- a/app/src/main/res/drawable/tile_icon_logic_analyzer.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_lux_meter.xml b/app/src/main/res/drawable/tile_icon_lux_meter.xml deleted file mode 100644 index fd756135c..000000000 --- a/app/src/main/res/drawable/tile_icon_lux_meter.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_lux_meter_log.xml b/app/src/main/res/drawable/tile_icon_lux_meter_log.xml deleted file mode 100644 index f67692589..000000000 --- a/app/src/main/res/drawable/tile_icon_lux_meter_log.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_multimeter.xml b/app/src/main/res/drawable/tile_icon_multimeter.xml deleted file mode 100644 index 9f7912e3c..000000000 --- a/app/src/main/res/drawable/tile_icon_multimeter.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_oscilloscope.xml b/app/src/main/res/drawable/tile_icon_oscilloscope.xml deleted file mode 100644 index cd819f7b8..000000000 --- a/app/src/main/res/drawable/tile_icon_oscilloscope.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_power_source.xml b/app/src/main/res/drawable/tile_icon_power_source.xml deleted file mode 100644 index 79fe450a4..000000000 --- a/app/src/main/res/drawable/tile_icon_power_source.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_sensors.xml b/app/src/main/res/drawable/tile_icon_sensors.xml deleted file mode 100644 index 4ca8c2f38..000000000 --- a/app/src/main/res/drawable/tile_icon_sensors.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - diff --git a/app/src/main/res/drawable/tile_icon_vertical_bars.xml b/app/src/main/res/drawable/tile_icon_vertical_bars.xml deleted file mode 100644 index 081fbb8a8..000000000 --- a/app/src/main/res/drawable/tile_icon_vertical_bars.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - diff --git a/app/src/main/res/drawable/tile_icon_wave_generator.xml b/app/src/main/res/drawable/tile_icon_wave_generator.xml deleted file mode 100644 index 107f406a2..000000000 --- a/app/src/main/res/drawable/tile_icon_wave_generator.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - diff --git a/app/src/main/res/drawable/tv_border.xml b/app/src/main/res/drawable/tv_border.xml deleted file mode 100644 index 6be99461b..000000000 --- a/app/src/main/res/drawable/tv_border.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/app/src/main/res/layout-hdpi/activity_multimeter.xml b/app/src/main/res/layout-hdpi/activity_multimeter.xml deleted file mode 100644 index 9ec5b7d53..000000000 --- a/app/src/main/res/layout-hdpi/activity_multimeter.xml +++ /dev/null @@ -1,433 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/layout-hdpi/control_main_list_item.xml b/app/src/main/res/layout-hdpi/control_main_list_item.xml deleted file mode 100644 index 335045039..000000000 --- a/app/src/main/res/layout-hdpi/control_main_list_item.xml +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - - - - - - -