Skip to content

Commit

Permalink
Merge pull request #83 from kike-canaries/av/map_improvements
Browse files Browse the repository at this point in the history
Map detail in recorded tracks fragment
  • Loading branch information
hpsaturn authored Mar 27, 2021
2 parents bf08e1f + e39833e commit 2f350bf
Show file tree
Hide file tree
Showing 13 changed files with 281 additions and 162 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import com.google.firebase.database.FirebaseDatabase;
import com.hpsaturn.tools.Logger;
import com.iamhabib.easy_preference.EasyPreference;
//import com.livinglifetechway.quickpermissions.annotations.WithPermissions;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public class RecordTrackService extends Service {
private RecordTrackManager recordTrackManager;

private final int RETRY_POLICY = 5;
private final int MAX_POINTS_SAVING = 3000;
private final int MAX_POINTS_SAVING = 1500;

private int retry_connect = 0;
private int retry_notify_setup = 0;
Expand Down Expand Up @@ -135,8 +135,6 @@ public void onServiceStatus(String status) {

@Override
public void onServiceStart() {
// Logger.d(TAG, "[BLE] request service start..");
// startConnection();
}

@Override
Expand Down Expand Up @@ -257,13 +255,7 @@ public void onNotificationSetupFailure() {

@Override
public void onNotificationReceived(byte[] bytes) {
// String strdata = new String(bytes);
// SensorData data = new Gson().fromJson(strdata, SensorData.class);
// Logger.d(TAG, "[BLE] pushing notification data to GUI..");
// recordTrackManager.sensorNotificationData(data);

if (bleHandler != null) bleHandler.readSensorData();

retry_notify_setup = 0;
}

Expand Down
201 changes: 133 additions & 68 deletions app/src/main/java/hpsaturn/pollutionreporter/view/ChartFragment.java
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
package hpsaturn.pollutionreporter.view;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.preference.MultiSelectListPreference;
import androidx.preference.PreferenceManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceManager;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
Expand All @@ -28,9 +26,14 @@
import com.hpsaturn.tools.DeviceUtil;
import com.hpsaturn.tools.Logger;

import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Polyline;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -84,6 +87,9 @@ public class ChartFragment extends Fragment {

private Map<String,String> map = new HashMap<>();

private List<GeoPoint> geoPoints = new ArrayList<>();
private MapView mapView;

public static ChartFragment newInstance() {
return new ChartFragment();
}
Expand All @@ -99,7 +105,18 @@ public static ChartFragment newInstance(String recordId) {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_chart, container, false);
// Try to load old track (records view)
View view;
Bundle args = getArguments();
if(args!=null){
recordId = args.getString(KEY_RECORD_ID) ;
Logger.i(TAG,"[CHART] recordId: "+recordId);
view = inflater.inflate(R.layout.fragment_chart, container, false);
mapView = view.findViewById(R.id.mapview);
}else{
view = inflater.inflate(R.layout.fragment_chart_realtime, container, false);
}

ButterKnife.bind(this, view);

Description description = new Description();
Expand All @@ -125,15 +142,74 @@ public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
map.put(types[i],labels[i]);
}

return view;
}

private void setupMap() {
mapView.setVisibility(View.VISIBLE);
mapView.setClickable(true);
mapView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
mapView.setMultiTouchControls(true);
mapView.setMaxZoomLevel((double) 19);
mapView.getController().setZoom((double) 17); //set initial zoom-level, depends on your need
mapView.setUseDataConnection(true); //keeps the mapView from loading online tiles using network connection.
mapView.setEnabled(true);
(mapView.getTileProvider().getTileCache()).getProtectedTileComputers().clear();
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Logger.i(TAG,"[CHART] starting load data thread..");
loadSelectedVariables();
if(recordId!=null) requireActivity().runOnUiThread(this::setupMap);
}

Bundle args = getArguments();
if(args!=null){
recordId = args.getString(KEY_RECORD_ID) ;
Logger.i(TAG,"[CHART] recordId: "+recordId);
/**
* initialization of data for chart and map
* load data of current recording track or old recorded track
*/
private void loadData() {
Logger.i(TAG,"[CHART] loading data..");
loadingData = true;
ArrayList<SensorData> data = new ArrayList<>();
if(recordId==null) {
Logger.i(TAG,"[CHART] loading current data in storage..");
data = Storage.getSensorData(getActivity());
}
else {
track = Storage.getTrack(getActivity(), recordId);
if(track!=null) {
Logger.i(TAG,"[CHART] loading track data from storage..");
data = track.data;
setTrackDescription(track);
getMain().enableShareButton();
}
else{
Logger.i(TAG,"[CHART] loading track from firebase..");
DatabaseReference trackRef = getMain().getDatabase().child(Config.FB_TRACKS_DATA).child(recordId);
trackRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
SensorTrack track = dataSnapshot.getValue(SensorTrack.class);
if(track!=null){
Logger.i(TAG,"[CHART] loading track on chart..");
addData(track.data);
setTrackDescription(track);
}
else{
Logger.e(TAG,"[CHART] onDataChange getValue is null");
}
}

return view;
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Logger.e(TAG,"[CHART] onCancelled, databaseError: "+databaseError.getDetails());
}
});
}
}
addData(data);
}

public void loadSelectedVariables(){
Expand All @@ -149,15 +225,11 @@ public void loadSelectedVariables(){
variables.add(var);
Logger.i(TAG, "[CHART]"+type);
}
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Logger.i(TAG,"[CHART] starting load data thread..");
requireActivity().runOnUiThread(this::loadData);
}


private void calculateReferenceTime(){
ArrayList<SensorData> data = Storage.getSensorData(getActivity());
if (data.isEmpty()) {
Expand All @@ -171,20 +243,16 @@ private void calculateReferenceTime(){
}


public void addData(SensorData data) {
if (!loadingData) {
Long currentTime = System.currentTimeMillis() / 1000;
long time = currentTime - referenceTimestamp;
addValue(time,data);
refreshDataSets();
}
}

/**
* Add data from previous data (recorded track for example)
* @param data
*/
private void addData(ArrayList<SensorData> data){
if(data==null)return;
else if (!data.isEmpty()) {
Iterator<SensorData> it = data.iterator();
while (it.hasNext()) {
int count = 0;
while (it.hasNext() && count++ <3000) {
SensorData d = it.next();
long time = d.timestamp - referenceTimestamp;
addValue(time,d);
Expand All @@ -198,7 +266,9 @@ else if (!data.isEmpty()) {
private void addValue(long time, SensorData data) {
Iterator<ChartVar> it = variables.iterator();
while (it.hasNext()){
it.next().addValue(time,data);
ChartVar var = it.next();
var.addValue(time,data);
if(recordId!=null && var.type.equals("P25"))addMapSegment(var,data);
}
}

Expand All @@ -218,49 +288,44 @@ private void refreshDataSets() {
chart.setData(linedata);
chart.notifyDataSetChanged();
chart.invalidate();

if(recordId!=null)updateMap();
}

private void loadData() {
Logger.i(TAG,"[CHART] loading data..");
loadingData = true;
ArrayList<SensorData> data = new ArrayList<>();
if(recordId==null) {
Logger.i(TAG,"[CHART] loading current data in storage..");
data = Storage.getSensorData(getActivity());
/**
* Add external data to fragment (real time visualization)
* @param data
*/
public void addData(SensorData data) {
if (!loadingData) {
Long currentTime = System.currentTimeMillis() / 1000;
long time = currentTime - referenceTimestamp;
addValue(time,data);
refreshDataSets();
}
else {
track = Storage.getTrack(getActivity(), recordId);
if(track!=null) {
Logger.i(TAG,"[CHART] loading track data from storage..");
data = track.data;
setTrackDescription(track);
getMain().enableShareButton();
}
else{
Logger.i(TAG,"[CHART] loading track from firebase..");
DatabaseReference trackRef = getMain().getDatabase().child(Config.FB_TRACKS_DATA).child(recordId);
trackRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
SensorTrack track = dataSnapshot.getValue(SensorTrack.class);
if(track!=null){
Logger.i(TAG,"[CHART] loading track on chart..");
addData(track.data);
setTrackDescription(track);
}
else{
Logger.e(TAG,"[CHART] onDataChange getValue is null");
}
}
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Logger.e(TAG,"[CHART] onCancelled, databaseError: "+databaseError.getDetails());
}
});
}
private void addMapSegment(ChartVar var, SensorData data) {
geoPoints.add(new GeoPoint(data.lat,data.lon));
if(geoPoints.size()>1){
Polyline line = new Polyline(); //see note below!
List<GeoPoint> segment = new ArrayList<>();
segment.add(geoPoints.get(geoPoints.size()-2));
segment.add(geoPoints.get(geoPoints.size()-1));
line.setPoints(segment);
line.getOutlinePaint().setColor(var.colors.get(var.colors.size()-1));
line.getOutlinePaint().setStrokeWidth(18F);
line.getOutlinePaint().setStrokeCap(Paint.Cap.ROUND);
line.getOutlinePaint().setAntiAlias(true);
mapView.getOverlayManager().add(line);
}
}

private void updateMap() {
if(geoPoints.size()>1) {
BoundingBox center = BoundingBox.fromGeoPoints(geoPoints);
mapView.zoomToBoundingBox(center, false);
}
addData(data);
}

private void setTrackDescription(SensorTrack track){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class ChartVar {

private Context ctx;

private final String type;
public String type;

public List<Entry> entries = new ArrayList<Entry>();

Expand Down Expand Up @@ -121,15 +121,15 @@ public void addValue(float time,SensorData data){
switch (type) {
case "CO2":
if (data.CO2 <= 600) colors.add(ctx.getResources().getColor(R.color.green));
else if (data.CO2 <= 800) colors.add(ctx.getResources().getColor(R.color.yellow));
else if (data.CO2 <= 800) colors.add(ctx.getResources().getColor(R.color.yellow_dark));
else if (data.CO2 <= 1000) colors.add(ctx.getResources().getColor(R.color.orange));
else if (data.CO2 <= 1500) colors.add(ctx.getResources().getColor(R.color.red));
else if (data.CO2 <= 2000) colors.add(ctx.getResources().getColor(R.color.purple));
else colors.add(ctx.getResources().getColor(R.color.brown));
break;
case "P25":
if (data.P25 <= 13) colors.add(ctx.getResources().getColor(R.color.green));
else if (data.P25 <= 35) colors.add(ctx.getResources().getColor(R.color.yellow));
else if (data.P25 <= 35) colors.add(ctx.getResources().getColor(R.color.yellow_dark));
else if (data.P25 <= 55) colors.add(ctx.getResources().getColor(R.color.orange));
else if (data.P25 <= 150)colors.add(ctx.getResources().getColor(R.color.red));
else if (data.P25 <= 250)colors.add(ctx.getResources().getColor(R.color.purple));
Expand All @@ -139,7 +139,7 @@ public void addValue(float time,SensorData data){

try {
float value = data.getClass().getField(type).getFloat(data);
Logger.i(TAG,"--> "+type+ ":"+value);
// Logger.i(TAG,"--> "+type+ ":"+value);
dataSet.addEntry(new Entry(time,value));

} catch (IllegalAccessException | NoSuchFieldException e) {
Expand Down
Loading

0 comments on commit 2f350bf

Please sign in to comment.