Search in sources :

Example 6 with HomeStats

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

the class MaxHashInstrumentedTest 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)

Example 7 with HomeStats

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

the class PoolDbHelper method getHistoryData.

public LinkedMap<Date, HomeStats> getHistoryData(@NonNull BackToEnum cutoff) {
    int cnt = 0;
    LinkedMap<Date, HomeStats> ret = new LinkedMap<>();
    SQLiteDatabase db = this.getReadableDatabase();
    String limitCause = "";
    Calendar now = Calendar.getInstance();
    switch(cutoff) {
        case ONE_DAY:
            now.add(Calendar.DATE, -1);
            limitCause = DataBaseContract.HomeStats_.COLUMN_NAME_DTM + "  > " + now.getTime().getTime();
            break;
        case ONE_WEEK:
            now.add(Calendar.DATE, -7);
            limitCause = DataBaseContract.HomeStats_.COLUMN_NAME_DTM + "  > " + now.getTime().getTime();
            break;
        case ONE_MONTH:
            now.add(Calendar.MONTH, -1);
            limitCause = DataBaseContract.HomeStats_.COLUMN_NAME_DTM + "  > " + now.getTime().getTime();
            break;
        default:
            Log.e("DB", "Unexpected switch ERROR");
            break;
    }
    // Cursor cursor = db.rawQuery(selectQuery, null);
    Cursor cursor = db.query(DataBaseContract.HomeStats_.TABLE_NAME, new String[] { DataBaseContract.HomeStats_._ID, DataBaseContract.HomeStats_.COLUMN_NAME_DTM, DataBaseContract.HomeStats_.COLUMN_NAME_JSON }, limitCause, // String[] selectionArgs
    null, null, // HAVING
    null, // ORDER BY
    DataBaseContract.HomeStats_.COLUMN_NAME_DTM + " ASC");
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        Gson gson = builder.create();
        do {
            try {
                // Register an adapter to manage the date types as long values
                HomeStats retrieved = gson.fromJson(cursor.getString(cursor.getColumnIndexOrThrow(DataBaseContract.HomeStats_.COLUMN_NAME_JSON)), HomeStats.class);
                // Adding contact to list
                ret.put(retrieved.getNow().getTime(), retrieved);
                cnt++;
            } catch (Exception ce) {
                Log.e(TAG, "Cant read HistoryData entry: " + ce.getMessage());
            }
        } while (cursor.moveToNext());
    }
    Log.i(TAG, "SELECT DONE. HOME HISTORY SIZE: " + cnt);
    cursor.close();
    return ret;
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) Calendar(java.util.Calendar) 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 8 with HomeStats

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

the class MPWService method onStartJob.

@Override
public boolean onStartJob(JobParameters job) {
    final JobParameters jobC = job;
    Log.e(TAG, "SERVICE START");
    final Context ctx = MPWService.this;
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    try {
        final PoolEnum mPool = PoolEnum.valueOf(prefs.getString("poolEnum", ""));
        final CurrencyEnum mCur = CurrencyEnum.valueOf(prefs.getString("curEnum", ""));
        Log.i(TAG, "Miner Pool Watcher Service call:" + Utils.getHomeStatsURL(PreferenceManager.getDefaultSharedPreferences(ctx)));
        Log.i(TAG, "SERVICE working on:" + mPool.toString() + " - " + mCur.toString());
        final PoolDbHelper mDbHelper = new PoolDbHelper(ctx, mPool, mCur);
        final NotificationManager mNotifyMgr = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
        final GsonBuilder builder = new GsonBuilder();
        // gestione UNIX time lungo e non
        builder.registerTypeAdapter(Date.class, new MyDateTypeAdapter());
        builder.registerTypeAdapter(Calendar.class, new MyTimeStampTypeAdapter());
        // load extra
        final String minerAddr = job.getExtras().getString("WALLETURL");
        final Boolean notifyBlock = job.getExtras().getBoolean("NOTIFY_BLOCK", false);
        final Boolean notifyOffline = job.getExtras().getBoolean("NOTIFY_OFFLINE", false);
        final Boolean notifyPayment = job.getExtras().getBoolean("NOTIFY_PAYMENT", false);
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, Utils.getHomeStatsURL(PreferenceManager.getDefaultSharedPreferences(ctx)), null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(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);
                mDbHelper.logHomeStats(retrieved);
                // dati semi grezzi
                LinkedMap<Date, HomeStats> ultimi = mDbHelper.getLastHomeStats(LAST_TWO);
                Log.d(TAG, "data size: " + ultimi.size() + " notifyOffline: " + ultimi.get(ultimi.get(0)).getMaturedTotal());
                // controllo se manca qualcuno
                if (notifyBlock && ultimi.size() > 1 && ultimi.get(ultimi.get(0)).getMaturedTotal().compareTo(ultimi.get(ultimi.get(1)).getMaturedTotal()) > 0) {
                    int diff = ultimi.get(ultimi.get(0)).getMaturedTotal() - ultimi.get(ultimi.get(1)).getMaturedTotal();
                    sendBlockNotification(getApplication(), diff + " new block. " + mPool.toString() + " has found " + ultimi.get(ultimi.get(0)).getMaturedTotal() + " blocks", mPool);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        });
        if (minerAddr != null) {
            Log.i(TAG, "refreshing wallet " + minerAddr + " notify: " + notifyBlock);
            JsonObjectRequest jsonObjReqWallet = new JsonObjectRequest(Request.Method.GET, Utils.getWalletStatsUrl(PreferenceManager.getDefaultSharedPreferences(ctx)) + minerAddr, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    Gson gson = builder.create();
                    // Register an adapter to manage the date types as long values
                    Wallet retrieved = gson.fromJson(response.toString(), Wallet.class);
                    mDbHelper.logWalletStats(retrieved);
                    // dati semi grezzi
                    LinkedMap<Date, Wallet> ultimi = mDbHelper.getLastWallets(LAST_TWO);
                    // controllo se manca qualcuno
                    if (notifyOffline && ultimi.keySet().size() >= LAST_TWO) {
                        if (ultimi.get(ultimi.firstKey()).getWorkersOnline() < ultimi.get(ultimi.get(1)).getWorkersOnline()) {
                            sendOfflineNotification(ctx, "A Worker has gone OFFLINE. Online Workers: " + ultimi.get(ultimi.firstKey()).getWorkersOnline(), mPool);
                        } else if (ultimi.get(ultimi.firstKey()).getWorkersOnline() > ultimi.get(ultimi.get(1)).getWorkersOnline()) {
                            // togli notifiche di offline
                            mNotifyMgr.cancel(NOTIFICATION_MINER_OFFLINE);
                        }
                    // else uguali, fa nulla
                    }
                    if (notifyPayment && ultimi.keySet().size() >= LAST_TWO && ultimi.get(ultimi.firstKey()).getPayments().size() > ultimi.get(ultimi.get(1)).getPayments().size()) {
                        sendPaymentNotification(ctx, "You received a payment: " + Utils.formatEthCurrency(ctx, ultimi.get(ultimi.firstKey()).getPayments().get(0).getAmount()), mCur.toString() + " payment from " + mPool.toString());
                    }
                    Log.e(TAG, "SERVICE END Ok1");
                    MPWService.this.jobFinished(jobC, false);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "SERVICE END KO1");
                    MPWService.this.jobFinished(jobC, true);
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                // hide the progress dialog
                }
            });
            JSONClientSingleton.getInstance(ctx).addToRequestQueue(jsonObjReqWallet);
        } else {
            // job end tutto bene
            MPWService.this.jobFinished(job, false);
        }
        // Adding request to request queue
        JSONClientSingleton.getInstance(ctx).addToRequestQueue(jsonObjReq);
    } catch (Exception se) {
        Log.e(TAG, "SERVICE ERROR: " + se);
        Crashlytics.logException(se);
    }
    // Answers the question: "Is there still work going on?"
    return true;
}
Also used : Context(android.content.Context) VolleyError(com.android.volley.VolleyError) NotificationManager(android.app.NotificationManager) SharedPreferences(android.content.SharedPreferences) GsonBuilder(com.google.gson.GsonBuilder) MyDateTypeAdapter(it.angelic.mpw.model.MyDateTypeAdapter) Wallet(it.angelic.mpw.model.jsonpojos.wallet.Wallet) Gson(com.google.gson.Gson) HomeStats(it.angelic.mpw.model.jsonpojos.home.HomeStats) LinkedMap(org.apache.commons.collections4.map.LinkedMap) Response(com.android.volley.Response) PoolEnum(it.angelic.mpw.model.enums.PoolEnum) JSONObject(org.json.JSONObject) MyTimeStampTypeAdapter(it.angelic.mpw.model.MyTimeStampTypeAdapter) JobParameters(com.firebase.jobdispatcher.JobParameters) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) CurrencyEnum(it.angelic.mpw.model.enums.CurrencyEnum) PoolDbHelper(it.angelic.mpw.model.db.PoolDbHelper)

Example 9 with HomeStats

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

the class WalletActivity method updateCurrentStats.

/**
 * Update header with last persisted DB row
 */
private void updateCurrentStats(final Wallet lastHit, final PoolDbHelper mDbHelper, Long avgPending) {
    Calendar when = Calendar.getInstance();
    try {
        when.setTime(lastHit.getStats().getLastShare());
        when.setTimeZone(TimeZone.getDefault());
        textViewWalLastShareValue.setText(yearFormatExtended.format(when.getTime()));
        textViewWalLastShare.setText(getString(R.string.last_share_found) + " " + Utils.getTimeAgo(when));
        walCurHashrateText.setText(Utils.formatHashrate(Long.parseLong(lastHit.getCurrentHashrate().toString())));
        walCurHashrate3HText.setText(Utils.formatHashrate(Long.parseLong(lastHit.getHashrate().toString())));
        walTotSharesText.setText(Utils.formatBigNumber(lastHit.getRoundShares()));
        walOnlineWorkersText.setText(lastHit.getWorkersOnline().toString());
        textViewWalPaymentsValue.setText("" + lastHit.getPaymentsTotal());
        walletValueText.setText(Utils.formatEthAddress(minerAddr));
        walletValueText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (mCur.getScannerSite() != null) {
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(mCur.getScannerSite() + "/address/" + minerAddr));
                    startActivity(i);
                } else {
                    Snackbar.make(view, "Blockchain explorer not available for " + mCur.toString(), Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                }
            }
        });
    } catch (Exception e) {
        Log.e(Constants.TAG, "Errore refresh: " + e.getMessage());
    }
    try {
        MathContext mc = new MathContext(4, RoundingMode.HALF_UP);
        HomeStats last = mDbHelper.getLastHomeStats(1).getValue(0);
        // bigIntX is a BigInteger
        BigDecimal bigDecX = new BigDecimal(lastHit.getRoundShares());
        BigDecimal bigDecY = new BigDecimal(last.getStats().getRoundShares());
        BigDecimal bd3 = bigDecX.divide(bigDecY, mc);
        // to divide:
        // Formatter formatter = new Formatter();
        Locale current = getResources().getConfiguration().locale;
        // 1 %1$s = %2$s$\n%3+$s%% last 24hr
        // %+10.4f%%
        DecimalFormat df = new DecimalFormat("0%", DecimalFormatSymbols.getInstance(current));
        // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
        df.setMaximumFractionDigits(12);
        textViewWalRoundSharesPercValue.setText(df.format(bd3));
    } catch (Exception e) {
        Log.e(Constants.TAG, "Errore refresh share perc: ", e);
        textViewWalRoundSharesPercValue.setText("NA");
    }
    try {
        textViewPendingBalanceValue.setText(Utils.formatCurrency(WalletActivity.this, lastHit.getStats().getBalance().longValue(), mCur));
    } catch (Exception ie) {
        Log.e(Constants.TAG, "Errore refresh Pending: " + ie.getMessage());
        textViewPendingBalanceValue.setText("NA");
    }
    try {
        textViewPaidValue.setText(Utils.formatCurrency(WalletActivity.this, lastHit.getStats().getPaid(), mCur));
    } catch (Exception ie) {
        Log.e(Constants.TAG, "Errore refresh Paid: " + ie.getMessage());
        textViewPaidValue.setText("NA");
    }
    try {
        textViewAvgPending.setText(avgPending == 0 ? "NA" : Utils.formatCurrency(WalletActivity.this, avgPending, mCur));
    } catch (Exception mie) {
        Log.e(Constants.TAG, "Errore refresh Agerage pending: " + mie.getMessage());
        textViewAvgPending.setText("NA");
    }
}
Also used : Locale(java.util.Locale) Calendar(java.util.Calendar) DecimalFormat(java.text.DecimalFormat) Intent(android.content.Intent) HomeStats(it.angelic.mpw.model.jsonpojos.home.HomeStats) NavigationView(android.support.design.widget.NavigationView) LineView(im.dacer.androidcharts.LineView) View(android.view.View) TextView(android.widget.TextView) AdView(com.google.android.gms.ads.AdView) MathContext(java.math.MathContext) BigDecimal(java.math.BigDecimal)

Example 10 with HomeStats

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

the class KratosInstrumentedTest 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(error.getMessage());
        // 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