Rafael Gomez
Published © GPL3+

CryptoDreams - Hardware Wallet

The goal of the Crypto-Beacon is to provide a multi-purpose device that handles various task associated with cryptocurrency and blockchain.

AdvancedWork in progressOver 1 day4,347

Things used in this project

Hardware components

PICO-PI-IMX6UL
Wandboard PICO-PI-IMX6UL
×1
Nextion - NX3224K024
×1
Jumper wires (generic)
Jumper wires (generic)
×1

Software apps and online services

Android Things
Google Android Things
Firebase
Google Firebase
Nextion GUI

Story

Read more

Code

index.js

JavaScript
Firebase function
const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);
exports.addTransaction = functions.https.onRequest((req, res) => {
    const transaction = req.query.transaction;
    admin.database().ref('/new-transaction').push({ transaction: transaction }).then(snapshot => {
        var message = `${transaction} received`
        res.status(201).send( transaction );
    });
});
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });

Loopback - MainActivity

Java
This is the main java code that does all the magic.
/*
 * Copyright 2016 The Android Open Source Project
 *
 * 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.
 */

package com.example.androidthings.loopback;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import com.google.android.things.pio.PeripheralManagerService;
import com.google.android.things.pio.UartDevice;
import com.google.android.things.pio.UartDeviceCallback;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;


import org.json.JSONObject;

import java.io.IOException;

/**
 * Example activity that provides a UART loopback on the
 * specified device. All data received at the specified
 * baud rate will be transferred back out the same UART.
 */
public class LoopbackActivity extends Activity {
    private static final String TAG = "LoopbackActivity";
    //private var mDatabaseRef: DatabaseReference? = null
    // UART Configuration Parameters
    private static final int BAUD_RATE = 9600;
    private static final int DATA_BITS = 8;
    private static final int STOP_BITS = 1;
    private DatabaseReference mDatabaseRef;
    private static final int CHUNK_SIZE = 7;

    private PeripheralManagerService mService = new PeripheralManagerService();

    private HandlerThread mInputThread;
    private Handler mInputHandler;

    private UartDevice mLoopbackDevice;

    private Runnable mTransferUartRunnable = new Runnable() {
        @Override
        public void run() {
            transferUartData();
        }
    };
    private void sendCommand(String command) throws IOException {
        String strCommand = command;
        String strEndCommand = "";
        byte[] payload = strCommand.getBytes();
        byte endByte = (byte) 0xFF;
        byte[] payloadEnd = {endByte,endByte,endByte};
        mLoopbackDevice.write(payload,payload.length);
        mLoopbackDevice.write(payloadEnd, payloadEnd.length);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "Loopback Created");

        mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("new-transaction");
        mDatabaseRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG,"something added: " + s);
                Log.d(TAG,"as a string: " + dataSnapshot.getValue().toString());
                String str = dataSnapshot.getValue().toString();
                //JSONObject jsonObj = new JSONObject();
               // jsonObj.getJSONArray()
                try {
                    String result = str.substring(str.indexOf("=") + 1, str.indexOf("}"));
                    sendCommand("page 2");
                    sendCommand("t1.txt=\"" +  result + "\"");
                } catch (IOException e) {
                    Log.e(TAG, "Error", e);
                }

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG,"something changed");
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                Log.d(TAG,"something removed");
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG,"something moved");
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG,"something broke");
            }
        });

        // Create a background looper thread for I/O
        mInputThread = new HandlerThread("InputThread");
        mInputThread.start();
        mInputHandler = new Handler(mInputThread.getLooper());

        // Attempt to access the UART device
        try {
            openUart(BoardDefaults.getUartName(), BAUD_RATE);
            // Read any initially buffered data
            mInputHandler.post(mTransferUartRunnable);
            sendCommand("page 0");

        } catch (IOException e) {
            Log.e(TAG, "Unable to open UART device", e);
        }


    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Loopback Destroyed");

        // Terminate the worker thread
        if (mInputThread != null) {
            mInputThread.quitSafely();
        }

        // Attempt to close the UART device
        try {
            closeUart();
        } catch (IOException e) {
            Log.e(TAG, "Error closing UART device:", e);
        }
    }

    /**
     * Callback invoked when UART receives new incoming data.
     */
    private UartDeviceCallback mCallback = new UartDeviceCallback() {
        @Override
        public boolean onUartDeviceDataAvailable(UartDevice uart) {
            // Queue up a data transfer
            transferUartData();
            //Continue listening for more interrupts
            return true;
        }

        @Override
        public void onUartDeviceError(UartDevice uart, int error) {
            Log.w(TAG, uart + ": Error event " + error);
        }
    };

    /* Private Helper Methods */

    /**
     *
     * @param command
     */

    /**
     * Access and configure the requested UART device for 8N1.
     *
     * @param name Name of the UART peripheral device to open.
     * @param baudRate Data transfer rate. Should be a standard UART baud,
     *                 such as 9600, 19200, 38400, 57600, 115200, etc.
     *
     * @throws IOException if an error occurs opening the UART port.
     */

    private void openUart(String name, int baudRate) throws IOException {
        mLoopbackDevice = mService.openUartDevice(name);
        // Configure the UART
        mLoopbackDevice.setBaudrate(baudRate);
        mLoopbackDevice.setDataSize(DATA_BITS);
        mLoopbackDevice.setParity(UartDevice.PARITY_NONE);
        mLoopbackDevice.setStopBits(STOP_BITS);
        mLoopbackDevice.flush(UartDevice.FLUSH_IN_OUT);
        //sendCommand("page 2");
        mLoopbackDevice.registerUartDeviceCallback(mCallback, mInputHandler);

    }

    /**
     * Close the UART device connection, if it exists
     */
    private void closeUart() throws IOException {
        if (mLoopbackDevice != null) {
            mLoopbackDevice.unregisterUartDeviceCallback(mCallback);
            try {
                mLoopbackDevice.close();
            } finally {
                mLoopbackDevice = null;
            }
        }
    }
    /**
     * Try to parse the byte array to something we can deal with
     */
    private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
    /**
     * Command Processor
     */
    private void processCommand(String cmd) throws IOException {
        switch (cmd){
            case "65010100FFFFFF":
                //Do Something Here
                sendCommand("t0.txt=\"213.00\"");
                Log.d(TAG, "Updated Balance");
                break;
            case "65010400FFFFFF":
                //Lock The Screen
                sendCommand("page 0");
                Log.d(TAG, "Locked Wallet");
                break;
            case "65020300FFFFFF":
                //Lock The Screen
                sendCommand("page 0");
                Log.d(TAG, "OK");
            default:
                //Default
                Log.d(TAG, "Command not found!");
                break;
        }
    }
    /**
     * Loop over the contents of the UART RX buffer, transferring each
     * one back to the TX buffer to create a loopback service.
     *
     * Potentially long-running operation. Call from a worker thread.
     */
    private void transferUartData() {
        if (mLoopbackDevice != null) {
            // Loop until there is no more data in the RX buffer.
            try {
                byte[] buffer = new byte[CHUNK_SIZE];
                int read;
                while ((read = mLoopbackDevice.read(buffer, buffer.length)) > 0) {
                    //mLoopbackDevice.write(buffer, read);
                    String cmd = bytesToHex(buffer);
                    Log.d(TAG, "Data was received: " + cmd);
                    processCommand(cmd);
                }
            } catch (IOException e) {
                Log.w(TAG, "Unable to transfer data over UART", e);
            }
        }
    }
}

Credits

Rafael Gomez

Rafael Gomez

0 projects • 12 followers
Network Administrator by day, Father of 3 by night. Coding gets squeezed somewhere in between!

Comments