Installing a custom ROM on Xiaomi Redmi 2

I've been installing and testing a lot of custom ROMs recently on my Redmi 2. This is a brief tutorial describing all the steps involved in installing a custom ROM (with specific steps required for Redmi 2).

Before proceeding, make sure you have backed up all your important data to another device.

Custom Recovery

Most custom ROMs require a custom recovery. In this section, I will provide the steps for installing the most popular recovery nowadays - TWRP.

  • First step is to install the Android SDK platform tools which include the fastboot command. fastboot is necessary for installing the custom recovery. You can get the platform tools for most OS here. If you are on Ubuntu, there is a very convenient package.

    If you have downloaded the platform tools manually, extract the archive to a directory of your choice, and open up your command line/terminal in the said directory.

  • Switch off your phone, and enter fastboot mode by pressing the volume down button and power button simultaneously. Connect the phone to your computer using a USB cable.

    In your terminal, type fastboot devices to make sure your phone is being detected. The output of the command should list your device. If not, check your USB cable connection. If it is still not being detected, you may have a broken USB port on your phone or a broken USB cable.

  • Download the TWRP image from dl.twrp.me/wt88047/. (Note that the image is for wt88047 which includes the following models - 20148(11/17/18/19). I'm not sure if this image works on wt86047 (2014813). You can find an appropriate TWRP image on MIUI or XDA forums. Note down the path to where you have downloaded the image.) It will be convenient to copy it to your current working directory.

  • Now, flash the recovery using the following command:

fastboot flash recovery /path/to/twrp/image
  • If you restart your phone now, MIUI may rewrite your recovery. Instead, you should reboot directly to your new recovery once before rebooting to MIUI. This can be done by
fastboot boot /path/to/twrp/image
  • That's it. You have successfully installed a custom recovery. You can now reboot into MIUI from the recovery.

Firmware

  • You have to ensure that your phone has the correct firmware version. Some (actually, most) ROMs require the Lollipop (Android 5.x) bootloader. If your MIUI is already on Lollipop, you can skip this section. If your MIUI is on Kitkat (Android 4.x) or lower, you need to flash the Lollipop bootloader. The requisite zip files can be found in the Lineage OS thread at XDA by nicknitewolf. I'm reproducing the links here - wt88047, wt86047.
  • Copy the zip file onto your phone's SD card. Reboot to your custom recovery (Switch off your phone, and press volume up, volume down, and power buttons simultaneously). Choose the Install option which will take you to a file browser. Find the zip file you just copied and select it. In the next screen, confirm that you want to flash this file. That's it. You have successfully updated your firmware.

ROM

Whichever custom ROM you have chosen should have detailed installation instructions. I will provide the general steps involved in flashing a new ROM here.

  • Download the zip file for the ROM, and get the appropriate Google apps (GApps) from opengapps.org. Copy both zip files to your phone's SD card. Reboot into recovery (power off, and press vol. up + vol. down + power).
  • Choose the Wipe option in recovery. Choose the Advanced wipe option in the next screen. In the following screen, select Dalvik/ART Cache, System, Data, and Cache. Confirm that you want to wipe the selected partitions.
  • Next, go back to the home screen of your recovery, and choose the Install option. In the file browser, find your ROM zip and confirm its installation. Once the installation is done, choose Install again, and select your GApps zip in the file browser. Wait for the installation to finish, and reboot. You should now be greeted by the boot animation of your new ROM.
  • That's it. Enjoy your new ROM!

Python script for logging in to IIT Madras netaccess

This is a small python script which I wrote for easy login to netaccess at IIT Madras. The script is pretty self-explanatory. I wrote this when I was trying to learn the requests module for python. The script uses the requests module to communicate with the netaccess site. It also uses the user agent string of a browser to make the netaccess site think that it's dealing with a browser. Note that you can set a default username in get_login_data() function. Set it to your roll number so that you don't have to enter it every time you call the script. The password has to be entered manually because I didn't want to store it in plain text.

PS: Remember to put the script in your $PATH for ease of use.

#!/usr/bin/env python
from __future__ import print_function, division
import requests
import getpass
import sys


def get_login_data():
    '''Asks the user for the username and password. Returns a dictionary to be
    passed to the /account/login post request.
    '''

    username = input('Enter username (Empty input defaults to "am12d013"): ')

    if not username:
        username = 'am12d013'

    password = ''

    while not password:
        password = getpass.getpass('Enter password (Cannot be empty): ')

    #return {'username': username, 'password': password}
    return {'userLogin': username, 'userPassword': password}


def get_approve_data():
    '''Asks the user for the duration to be logged in for. Returns a dictionary
    to be passed to the /account/approve post request.
    '''

    duration = input('Enter session duration (1: 1 hour, 2: 1 day, empty defaults to 1): ')

    if (not duration) or (duration!='2'):
        duration = '1'

    if duration == '1':
        print('You have requested approval for 1 hour')
    else:
        print('You have requested approval for 1 day')

    return {'duration': duration, 'approveBtn': ''}


def has_logged_in(response):
    '''Checks if login request is successful. Returns false if not.
    '''
    # If response is not 200 OK, raise error
    if response.status_code != requests.codes.ok:
        response.raise_for_status()
    # Check if login has failed by searching for a substring in the response
    # content
    elif '/account/approve' not in response.content:
        return False

    return True


def main():

    # User agent string from Firefox 49 running on a Linux machine
    headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0'}

    login_data = get_login_data()
    approve_data = get_approve_data()

    with requests.Session() as s:

        # Login request
        p = s.post('https://netaccess.iitm.ac.in/account/login',
                data=login_data, headers=headers)

        # Check if login is successful.
        if has_logged_in(p):
            print('Login successful.')
        else:
            print('Wrong username or password provided. Login failed!')
            sys.exit(0)

        # Approve machine request
        p = s.post('https://netaccess.iitm.ac.in/account/approve',
                data=approve_data, headers=headers)

        # If response is not 200 OK, approval has failed. Exit.
        if p.status_code != requests.codes.ok:
            p.raise_for_status()
        else:
            print('Machine approved successfully.')

        sys.exit(0)


if __name__ == '__main__':

    # If python2.x, use 'raw_input' else use 'input'
    try:
        input = raw_input
    except NameError:
        pass

    main()

Letting Spotlight find Brew Apps on Mac OS X

Say, you want spotlight to find MacVim. Doing

$ brew linkapps macvim

creates a symlink in /Applications. But Spotlight seems to ignore it. Instead, remove the symlink

$ rm /Applications/MacVim.app

and do

$ osascript -e 'tell application "Finder" to make alias file to POSIX file "/usr/local/opt/macvim/MacVim.app" at POSIX file "/Applications"'

How to Compile and Install Vim 8.0 on Ubuntu

  • Install build dependencies
$ sudo apt-get build-dep vim
  • Clone git repo
$ git clone https://github.com/vim/vim.git``
  • Change to src directory
$ cd vim/src
  • Remove files from previous compilation (skip if compiling for the first time)
$ sudo make distclean
  • Path to install vim (optional. omit --prefix option in next step if not set)
export PREFIX='/path/to/vim/install'
  • Configure with required options ($ configure --help for other config. options).

    • For python 2.x
    $ ./configure --with-features=huge \
                --enable-multibyte \
                --enable-rubyinterp \
                --enable-pythoninterp \
                --with-python-config-dir=/usr/lib/python2.7/config-x86\_64-linux-gnu \
                --enable-perlinterp \
                --enable-luainterp \
                --enable-cscope \
                --enable-gui=auto \
                --enable-gtk2-check \
                --with-x \
                --with-compiledby="j.jith" \
                --prefix=$PREFIX
    
    • For python 3.x
    $ ./configure --with-features=huge \
                --enable-multibyte \
                --enable-rubyinterp \
                --enable-python3interp \
                --with-python3-config-dir=/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu \
                --enable-perlinterp \
                --enable-luainterp \
                --enable-cscope \
                --enable-gui=auto \
                --enable-gtk2-check \
                --with-x \
                --with-compiledby="j.jith" \
                --prefix=$PREFIX
    
  • Compile

$ make
  • Run tests
$ make test
  • Install (may need to use sudo if you don't have write permission in $PREFIX)
$ make install
  • Make default editor/vim/vi/gvim
$ sudo sh -c "update-alternatives --install /usr/bin/editor editor $PREFIX/bin/vim 1;
update-alternatives --set editor $PREFIX/bin/vim;
update-alternatives --install /usr/bin/vim vim $PREFIX/bin/vim 1;
update-alternatives --set vim $PREFIX/bin/vim;
update-alternatives --install /usr/bin/vi vi $PREFIX/bin/vim 1;
update-alternatives --set vi $PREFIX/bin/vim;
update-alternatives --install /usr/bin/gvim gvim $PREFIX/bin/gvim 1;
update-alternatives --set gvim $PREFIX/bin/gvim"

How to flash MIUI Fastboot ROM from Linux

  • Download the ROM suitable for your device from the MIUI site and extract the downloaded archive
  • Download and extract the Android SDK Platform Tools
  • Make sure adb and fastboot (components of platform-tools) are in your path
$ export PATH=path/to/android/sdk/platform-tools:$PATH
  • Connect your device to your computer using a USB cable and enable USB Debugging in your device's settings. Check if your device is detected.
$ adb devices
  • If device is listed, reboot to bootloader
$ adb reboot bootloader
  • Check if your device is detected by fastboot
$ fastboot devices
  • You may need to use sudo before fastboot if you get a permission denied error
  • There are two scripts for flashing the ROM:
    1. flash_all.sh - Flash ROM and erase user data
    2. flash_all_except_data_storage.sh - Flash ROM without erasing user data
  • Whichever script you decide to use, make sure that the interpreter is mentioned at the top of the script like
#!/bin/sh
  • If the above line is missing, add it to the top of the script
  • Make the script executable (I've chosen flash_all.sh)
$ cd path/to/extracted/ROM/archive
$ chmod a+x ./flash_all.sh
  • Run the script
$ ./flash_all.sh
  • You may need to run sudo ./flash_all.sh if you had to use sudo with fastboot
  • Sit back and relax. The script needs no user interaction. After flashing the ROM, the scipt will reboot your device.
  • Reboot will take quit a bit of time. Don't panic.