Search in sources :

Example 1 with HomeStats

use of it.angelic.mpw.model.jsonpojos.home.HomeStats in project MPW by shineangelic.

the class PoolDbHelper method getLastHomeStats.

public LinkedMap<Date, HomeStats> getLastHomeStats(int limit) {
    LinkedMap<Date, HomeStats> ret = new LinkedMap<>();
    int cnt = 0;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(DataBaseContract.HomeStats_.TABLE_NAME, new String[] { DataBaseContract.HomeStats_._ID, DataBaseContract.HomeStats_.COLUMN_NAME_DTM, DataBaseContract.HomeStats_.COLUMN_NAME_JSON }, null, // String[] selectionArgs
    null, null, // HAVING
    null, DataBaseContract.HomeStats_.COLUMN_NAME_DTM + " DESC", // 2 results to do compare
    "" + limit);
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        Gson gson = builder.create();
        do {
            try {
                HomeStats retrieved = gson.fromJson(cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.Wallet_.COLUMN_NAME_JSON)), HomeStats.class);
                cnt++;
                // Adding contact to list
                Date curDate = new Date(cursor.getLong(cursor.getColumnIndexOrThrow(DataBaseContract.Wallet_.COLUMN_NAME_DTM)));
                ret.put(curDate, retrieved);
            } catch (Exception ce) {
                Log.e(TAG, "Cant read HomeStats entry: " + ce.getMessage());
            }
        } while (cursor.moveToNext());
    }
    Log.i(TAG, "SELECT DONE. WALLET HISTORY SIZE: " + cnt);
    cursor.close();
    return ret;
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) Gson(com.google.gson.Gson) HomeStats(it.angelic.mpw.model.jsonpojos.home.HomeStats) Cursor(android.database.Cursor) LinkedMap(org.apache.commons.collections4.map.LinkedMap) Date(java.util.Date)

Example 2 with HomeStats

use of it.angelic.mpw.model.jsonpojos.home.HomeStats in project MPW by shineangelic.

the class MainActivity method updateCurrentStats.

/**
 * Update header with last persisted DB row
 */
private void updateCurrentStats() {
    try {
        HomeStats lastHit = storia.get(storia.lastKey());
        try {
            Calendar when = Calendar.getInstance();
            when.setTimeZone(TimeZone.getDefault());
            when.setTime(lastHit.getStats().getLastBlockFound());
            lastFoundTextLabel.setText(getString(R.string.last_block_found) + " " + Utils.getTimeAgo(when));
            lastFoundText.setText(yearFormatExtended.format(lastHit.getStats().getLastBlockFound()));
        } catch (Exception ee) {
            Log.w(Constants.TAG, "No block found yet?");
        }
        textViewNetDiffValue.setText(Utils.formatBigNumber(Long.parseLong(lastHit.getNodes().get(0).getDifficulty())));
        Calendar lastB = Calendar.getInstance();
        lastB.setTime(lastHit.getNodes().get(0).getLastBeat());
        yearFormatExtended.setTimeZone(TimeZone.getDefault());
        poolLastBeat.setText(yearFormatExtended.format(lastB.getTime()));
        onlineMinersText.setText("" + (lastHit.getMinersTotal() == null ? 0 : lastHit.getMinersTotal()));
        textViewBlockChainHeightValue.setText(Utils.formatBigNumber(Long.parseLong(lastHit.getNodes().get(0).getHeight())));
        poolHashrateText.setText(Utils.formatHashrate(Long.parseLong(lastHit.getHashrate().toString())));
        roundSharesText.setText(Utils.formatBigNumber(lastHit.getStats().getRoundShares()));
        noobText.setText(String.format(getString(R.string.tot_block_found), mPool.toString(), lastHit.getMaturedTotal(), mCur.name()));
        try {
            MathContext mc = new MathContext(4, RoundingMode.HALF_UP);
            // Variance % = Pool Shares / Network Difficulty Thanks to alfred
            BigDecimal bigDecX = new BigDecimal(lastHit.getStats().getRoundShares());
            BigDecimal bigDecY = new BigDecimal(Long.parseLong(lastHit.getNodes().get(0).getDifficulty()));
            BigDecimal bd3 = bigDecX.divide(bigDecY, mc).multiply(new BigDecimal(100));
            textViewVarianceValue.setText(bd3.stripTrailingZeros().toPlainString() + "%");
        } catch (Exception e) {
            Log.e(Constants.TAG, "Errore refresh share perc: " + e.getMessage());
            e.printStackTrace();
        }
    } catch (Exception e) {
        Log.e(Constants.TAG, "Errore refresh: " + e.getMessage());
        e.printStackTrace();
    }
}
Also used : Calendar(java.util.Calendar) HomeStats(it.angelic.mpw.model.jsonpojos.home.HomeStats) MathContext(java.math.MathContext) BigDecimal(java.math.BigDecimal)

Example 3 with HomeStats

use of it.angelic.mpw.model.jsonpojos.home.HomeStats in project MPW by shineangelic.

the class MainActivity method issueRefresh.

private void issueRefresh(final PoolDbHelper mDbHelper, final GsonBuilder builder) {
    Log.i(Constants.TAG, "JsonObjectRequest for: " + Utils.getHomeStatsURL(PreferenceManager.getDefaultSharedPreferences(MainActivity.this)));
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, Utils.getHomeStatsURL(PreferenceManager.getDefaultSharedPreferences(MainActivity.this)), null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(final JSONObject response) {
            Log.d(Constants.TAG, response.toString());
            hashText.post(new Runnable() {

                @Override
                public void run() {
                    Gson gson = builder.create();
                    // Register an adapter to manage the date types as long values
                    HomeStats retrieved = gson.fromJson(response.toString(), HomeStats.class);
                    mDbHelper.logHomeStats(retrieved);
                    // dati semi grezzi
                    int radioButtonID = radioGroupBackTo.getCheckedRadioButtonId();
                    View radioButton = findViewById(radioButtonID);
                    storia = mDbHelper.getHistoryData(BackToEnum.valueOf((String) radioButton.getTag()));
                    updateCurrentStats();
                    final RadioButton radioDay = findViewById(R.id.radioButtonDay);
                    final RadioButton radioMin = findViewById(R.id.radioButtonMinutes);
                    GranularityEnum granoEnum = GranularityEnum.HOUR;
                    if (radioDay.isChecked())
                        granoEnum = GranularityEnum.DAY;
                    else if (radioMin.isChecked())
                        granoEnum = GranularityEnum.MINUTE;
                    ChartUtils.drawDifficultyHistory(textViewNetDiffTitle, PoolQueryGrouper.groupAvgQueryResult(storia, granoEnum), (LineView) findViewById(R.id.line_view_difficulty), granoEnum);
                    ChartUtils.drawHashrateHistory(hashText, PoolQueryGrouper.groupAvgQueryResult(storia, granoEnum), (LineView) findViewById(R.id.line_view_hashrate), granoEnum);
                }
            });
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(Constants.TAG, "Error: " + error.getMessage());
            Snackbar.make(findViewById(android.R.id.content), "Network Error", Snackbar.LENGTH_SHORT).show();
            // prevent stale data appear
            updateCurrentStats();
        }
    });
    /*
        JsonArrayRequest jsonArrayCurrenciesReq = new JsonArrayRequest(Request.Method.GET,
                Constants.ETHER_STATS_URL, null,
                new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(final JSONArray response) {
                        Log.d(Constants.TAG, response.toString());
                        hashText.post(new Runnable() {
                            @Override
                            public void run() {
                                Gson gson = builder.create();
                                Log.d(Constants.TAG, response.toString());
                                Type listType = new TypeToken<List<Ticker>>() {}.getType();
                                List<Ticker> posts = gson.fromJson(response.toString(), listType);
                                Ticker fnd = null;
                                for (Ticker currency : posts) {
                                    if (mCur.name().equalsIgnoreCase(currency.getSymbol()) || mCur.toString().equalsIgnoreCase(currency.getName())) {
                                        fnd = currency;
                                    }
                                    //always save ETH
                                    if (CurrencyEnum.ETH.name().equalsIgnoreCase(currency.getSymbol())) {
                                        CryptoSharedPreferencesUtils.saveEthereumValues(currency, MainActivity.this);
                                    }
                                    //always save BTC
                                    if (CurrencyEnum.BTC.name().equalsIgnoreCase(currency.getSymbol())) {
                                        CryptoSharedPreferencesUtils.saveBtcValues(currency, MainActivity.this);
                                    }
                                }
                                //eventually resets  when fnd = null
                                CryptoSharedPreferencesUtils.saveEtherValues(fnd, MainActivity.this);
                            }
                        });
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(Constants.TAG, "Error: " + error.getMessage());
                Crashlytics.logException(error);
            }
        });*/
    // Adding request to request queue
    JSONClientSingleton.getInstance(this).addToRequestQueue(jsonObjReq);
// JSONClientSingleton.getInstance(this).addToRequestQueue(jsonArrayCurrenciesReq);
}
Also used : VolleyError(com.android.volley.VolleyError) Gson(com.google.gson.Gson) HomeStats(it.angelic.mpw.model.jsonpojos.home.HomeStats) RadioButton(android.widget.RadioButton) NavigationView(android.support.design.widget.NavigationView) LineView(im.dacer.androidcharts.LineView) View(android.view.View) AdView(com.google.android.gms.ads.AdView) TextView(android.widget.TextView) Response(com.android.volley.Response) JSONObject(org.json.JSONObject) GranularityEnum(it.angelic.mpw.model.db.GranularityEnum) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest)

Example 4 with HomeStats

use of it.angelic.mpw.model.jsonpojos.home.HomeStats in project MPW by shineangelic.

the class PaymentsActivity method drawProjectionTable.

private void drawProjectionTable(final PoolDbHelper mDbHelper, Block matured) {
    Double shareperc = 0d;
    TableLayout minersTable = findViewById(R.id.tableLayoutProjections);
    minersTable.removeAllViews();
    // table header
    TableRow row = (TableRow) LayoutInflater.from(PaymentsActivity.this).inflate(R.layout.row_projection, null);
    minersTable.addView(row);
    try {
        MathContext mc = new MathContext(4, RoundingMode.HALF_UP);
        HomeStats last = mDbHelper.getLastHomeStats(1).getValue(0);
        // bigIntX is a BigInteger
        BigDecimal bigDecRoundShares = new BigDecimal(mDbHelper.getLastWallet().getRoundShares());
        BigDecimal bigDecY = new BigDecimal(last.getStats().getRoundShares());
        shareperc = bigDecRoundShares.divide(bigDecY, mc).doubleValue();
        // By current currency
        TableRow rowCur = (TableRow) LayoutInflater.from(PaymentsActivity.this).inflate(R.layout.row_projection_color, null);
        ((TextView) rowCur.findViewById(R.id.textViewProjEmpty)).setText(mCur.name());
        Double dayP = Utils.getDailyProfitProjection(shareperc, matured.getMatured());
        ((TextView) rowCur.findViewById(R.id.textViewProjDayCur)).setText(Utils.formatGenericCurrency(PaymentsActivity.this, dayP, PrecisionEnum.TWO_DIGIT));
        ((TextView) rowCur.findViewById(R.id.textViewProjWeekCur)).setText(Utils.formatGenericCurrency(PaymentsActivity.this, dayP * 7, PrecisionEnum.TWO_DIGIT));
        Calendar c = Calendar.getInstance();
        int monthMaxDays = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        ((TextView) rowCur.findViewById(R.id.textViewProjMonthCur)).setText(Utils.formatGenericCurrency(PaymentsActivity.this, dayP * monthMaxDays, PrecisionEnum.TWO_DIGIT));
        minersTable.addView(rowCur);
        // CAZZO DI DOLLARI
        try {
            TableRow rowCurEl = (TableRow) LayoutInflater.from(PaymentsActivity.this).inflate(R.layout.row_projection_color, null);
            ((TextView) rowCurEl.findViewById(R.id.textViewProjEmpty)).setText(" $ ");
            SharedPreferences settings = PaymentsActivity.this.getSharedPreferences("COINMARKETCAP", MODE_PRIVATE);
            Double val = Double.valueOf(settings.getString("CURUSD", "0"));
            Double dayPD = dayP * val.doubleValue();
            ((TextView) rowCurEl.findViewById(R.id.textViewProjDayCur)).setText(Utils.formatUSDCurrency(PaymentsActivity.this, dayPD));
            ((TextView) rowCurEl.findViewById(R.id.textViewProjWeekCur)).setText(Utils.formatUSDCurrency(PaymentsActivity.this, dayPD * 7));
            ((TextView) rowCurEl.findViewById(R.id.textViewProjMonthCur)).setText(Utils.formatUSDCurrency(PaymentsActivity.this, dayPD * monthMaxDays));
            minersTable.addView(rowCurEl);
            if (!CurrencyEnum.ETH.equals(mCur)) {
                try {
                    TableRow rowCurEl2 = (TableRow) LayoutInflater.from(PaymentsActivity.this).inflate(R.layout.row_projection_color, null);
                    ((TextView) rowCurEl2.findViewById(R.id.textViewProjEmpty)).setText(CurrencyEnum.ETH.name());
                    Double valUsdETH = 1 / Double.valueOf(settings.getString("ETHUSD", "0"));
                    Double dayPDETH = dayPD * valUsdETH;
                    ((TextView) rowCurEl2.findViewById(R.id.textViewProjDayCur)).setText(Utils.formatGenericCurrency(PaymentsActivity.this, dayPDETH, PrecisionEnum.TWO_DIGIT));
                    ((TextView) rowCurEl2.findViewById(R.id.textViewProjWeekCur)).setText(Utils.formatGenericCurrency(PaymentsActivity.this, dayPDETH * 7, PrecisionEnum.TWO_DIGIT));
                    ((TextView) rowCurEl2.findViewById(R.id.textViewProjMonthCur)).setText(Utils.formatGenericCurrency(PaymentsActivity.this, dayPDETH * monthMaxDays, PrecisionEnum.TWO_DIGIT));
                    minersTable.addView(rowCurEl2);
                } catch (Exception oioi) {
                    Log.w(Constants.TAG, "Internal Row 3 fail", oioi);
                }
            }
        } catch (Exception oioi) {
            Log.w(Constants.TAG, "Internal Row 2 fail");
        }
    } catch (Exception e) {
        Log.e(Constants.TAG, "Errore refresh share perc: ", e);
    // textViewWalRoundSharesPercValue.setText("NA");
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) TableRow(android.widget.TableRow) Calendar(java.util.Calendar) HomeStats(it.angelic.mpw.model.jsonpojos.home.HomeStats) TextView(android.widget.TextView) TableLayout(android.widget.TableLayout) MathContext(java.math.MathContext) BigDecimal(java.math.BigDecimal)

Example 5 with HomeStats

use of it.angelic.mpw.model.jsonpojos.home.HomeStats in project MPW by shineangelic.

the class NoobPoolInstrumentedTest method testJsonRequest.

@Test
public void testJsonRequest() throws Exception {
    final GsonBuilder builder = new GsonBuilder();
    // gestione UNIX time lungo e non
    builder.registerTypeAdapter(Date.class, new MyDateTypeAdapter());
    builder.registerTypeAdapter(Calendar.class, new MyTimeStampTypeAdapter());
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, Utils.getHomeStatsURL(sharedPreferences), null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(final JSONObject response) {
            Log.d(Constants.TAG, response.toString());
            Gson gson = builder.create();
            // Register an adapter to manage the date types as long values
            HomeStats retrieved = gson.fromJson(response.toString(), HomeStats.class);
            assertNotNull(retrieved);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(Constants.TAG, "Error: " + error.getMessage());
            fail();
        // hide the progress dialog
        }
    });
    // Adding request to request queue
    JSONClientSingleton.getInstance(InstrumentationRegistry.getTargetContext()).addToRequestQueue(jsonObjReq);
}
Also used : Response(com.android.volley.Response) VolleyError(com.android.volley.VolleyError) JSONObject(org.json.JSONObject) GsonBuilder(com.google.gson.GsonBuilder) MyDateTypeAdapter(it.angelic.mpw.model.MyDateTypeAdapter) MyTimeStampTypeAdapter(it.angelic.mpw.model.MyTimeStampTypeAdapter) Gson(com.google.gson.Gson) HomeStats(it.angelic.mpw.model.jsonpojos.home.HomeStats) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) Test(org.junit.Test)

Aggregations

HomeStats (it.angelic.mpw.model.jsonpojos.home.HomeStats)11 Gson (com.google.gson.Gson)7 Response (com.android.volley.Response)5 VolleyError (com.android.volley.VolleyError)5 JsonObjectRequest (com.android.volley.toolbox.JsonObjectRequest)5 Calendar (java.util.Calendar)5 JSONObject (org.json.JSONObject)5 GsonBuilder (com.google.gson.GsonBuilder)4 MyDateTypeAdapter (it.angelic.mpw.model.MyDateTypeAdapter)4 MyTimeStampTypeAdapter (it.angelic.mpw.model.MyTimeStampTypeAdapter)4 LinkedMap (org.apache.commons.collections4.map.LinkedMap)4 TextView (android.widget.TextView)3 BigDecimal (java.math.BigDecimal)3 MathContext (java.math.MathContext)3 Date (java.util.Date)3 Test (org.junit.Test)3 SharedPreferences (android.content.SharedPreferences)2 Cursor (android.database.Cursor)2 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)2 NavigationView (android.support.design.widget.NavigationView)2