Soccer World Cup 2018 Average Face by Team

World Cup 2018 Average Player Face by Team
World Cup 2018 Average Player Face by Team

 

We all know that Spain is going to win this world cup ūüėČ, but watching the games is still entertaining. I thought today while watching England vs. Tunisia that soccer players look very much alike, especially within a team, and so I thought I could compute the average face by soccer team for this world cup.

Data

Getting the data, in this case, images for each player in the current soccer world cup is arguably critical. The images need to have a plain background, similar ilumation, and ideally, equal size. Luckly, the FIFA has done all of this, and the images are available online: https://www.fifa.com/worldcup/players/

If you inspect one of the player’s elemtents, you can access the URL for the player’s image, which can then be downloaded programmatically

Inspecting the player element on the browser console shows the URL.

I downloaded the page’s source code, and downloaded the 736 300 pixels squared images.

Averaging a face

There is a naive way of averaging an image, using numpy, and it only takes a few lines:

import numpy as np
import imageio

countries = ['argentina', 'belgium', 'colombia', 'croatia', ...]

for country in countries:
    images_stacked = np.zeros((23, 300, 300, 3))

    for i in range(0, 23):
        images_stacked[i] = imageio.imread('images-input/%s/%s_%s.jpg' % (country, country, i))

    results = np.zeros((300, 300, 3))

    for color in range(0, images_stacked.shape[3]):
        for x_pos in range(0, images_stacked.shape[1]):
            for y_pos in range(0, images_stacked.shape[2]):
                results[x_pos, y_pos, color] = np.mean(images_stacked[:, x_pos, y_pos, color])

    imageio.imwrite('images-output/%s_naive_averager.png' % country, results)

There is room for improving on this code, but I am not interested in that, rather on the actual results. And here is how they show:

Sweden Naive Average Face

Let’s look at another example:

Brazil Naive Average Face

Even though images are standard, averaging the pixel values doesn’t build a compeling image; sure, we can distinguish some features such as color of the t-shirt or hair, but we can’t put a face to it.

Face morpher

Luckily, there are better ways. Meet Face Morpher (FM from now own). FM works in a different way to find the average face, instead of naively averaging the pixel values, it builds a geometry of the face by identifying elements on it such as the eyes. It then proceeds to average those sections across images.

The results are much more compeling, and we are definitely able to put a face to this teams now.

Sweden FM Average Face

Or in the case of Brazil:

It looks great! I love it! And yet, aren’t we missing important and distinctive elements, such as the hair, ears, or even team t-shirt?

Face art

I decided to them combine the two images: naive + FM for a more compeling result. I blended the images using Sketch, used the naive image as background, and overlayed a semi-transparent FM face.

Quite happy with the result:

World Cup 2018 Average Player Face by Team
World Cup 2018 Average Player Face by Team

Extra

How does the average face look across all countries then?

Average face across all countries
Average face across all countries

Phone Insights API

This API can parse, format and find phone numbers in text documents for any phone number worldwide.

These are the endpoints:

Endpoint /parse

Given a phone number with an international prefix, or if you prefer by specifying the ISO country code, and the national phone number instead, we can tell you:

  • number_type: One of the following: FIXED, MOBILE, VOIP, SHORT_NUMBER, PREMIUM, TOLL_FREE, PAGER, etc.
  • location: Where available by prefix.
  • phone_number_e164: Phone number in E164. Perfect to be saved in a database in a standard way.
  • carrier: In countries where blocks of numbers are assigned to carriers. Note that if portability is available in the country, we will return the original carrier.
  • is_valid_number: Using the length, format and prefixes against our 100Mbytes+ database of phone numbers we can asses the validity of the phones. E.g. we can detect fake US numbers if the prefixes don’t exist.
  • country_code_iso: Two letter ISO country code for the phone number.
  • We also give other auxiliary fields such as: number_of_leading_zeros, national_number, etc. If you need more information returned, contact us!

Example request:

curl -X POST --include 'https://f-sm-jorquera-phone-insights-v1.p.mashape.com/parse' \
  -H 'X-Mashape-Key: {my-mashape-key}' \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  --data-binary '{"phone_number":"+34626475849","country_code":"ES"}'

That returns:

{
  "country_code": 34,
  "country_code_iso": "ES",
  "location": "Spain",
  "location_latitude": 40.0028028,
  "location_longitude": -4.003104,
  "national_number": 626475849,
  "number_of_leading_zeros": null,
  "number_type": "MOBILE",
  "is_valid_number": true,
  "carrier": "Movistar",
  "phone_number_e164": "+34626475849"
}

 

Endpoint /format

Given a phone number with an international prefix, or if you prefer by specifying the ISO country code, and the national phone number instead, we can tell you:

  • national: phone number in national format, e.g. (415) 498-8739
  • international: phone number in international format, e.g. +1 (415) 498-8739
  • E164: phone number in E164 format, e.g. +14154988739
  • RFC3966: phone number in E164 format, e.g. tel:+14154988739

Example request:

curl -X POST --include 'https://f-sm-jorquera-phone-insights-v1.p.mashape.com/format' \
  -H 'X-Mashape-Key: {my-mashape-key}' \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  --data-binary '{"phone_number":"+34626475849","country_code":"ES"}'

Response:

{
  "national": "626 47 58 49",
  "international": "+34 626 47 58 49",
  "E164": "+34626475849",
  "RFC3966": "tel:+34-626-47-58-49"
}

Endpoint /find-numbers-in-text Endpoint

Given a text document (max. 512 characters), we can find all phone numbers in it. E.g. for the text: Hey, the office's phone number is (510) 765-9845, my personal one is 4157653478. We will return the begin and end character position for both phone numbers, along with a E164 formatted version of each. We can find phone numbers, even if the format used in the document differs.

curl -X POST --include 'https://f-sm-jorquera-phone-insights-v1.p.mashape.com/find-numbers-in-text' \
  -H 'X-Mashape-Key: {my-mashape-key}' \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  --data-binary '{"text":"Hello, call me at 4154785647 or at (510) 675 8976 if it's after 11PM","country_code":"US"}'

Response:

{
  "matches": [
    {
      "start": 18,
      "end": 28,
      "phone_number": "+14154785647"
    },
    {
      "start": 35,
      "end": 49,
      "phone_number": "+15106758976"
    }
  ]
}

If you want to try it, head to mashape: https://market.mashape.com/f-sm-jorquera/phone-insights. The API is completely free!

Choropleth: percentage of foreigners by US county

Building maps is very easy with Folium. I got my hands on some data from the US Census, specifically, the foreign born population and total population per US county.

To plot it, first download the CSV from the  2011-2015 American Community Survey 5-Year Estimates.

import os
import folium
import pandas as pd

# Load data
data = pd.read_csv('data.csv')

# Add column with ratio of foreign born vs total pop.
data['ratio_foreign_born_vs_total_population'] = 100 * data['Estimate; Foreign born:'] / data['Estimate; Total:']

# Create map
map_1 = folium.Map(location=[39, -96], zoom_start=4)
high_res_county_geo = os.path.relpath('gz_2010_us_050_00_500k.json') # from http://eric.clst.org/Stuff/USGeoJSON

# Add choropleth layer
map_1.choropleth(
 geo_data=high_res_county_geo,
 name='choropleth',
 data=data,
 columns=['Id', 'ratio_foreign_born_vs_total_population'],
 key_on='properties.GEO_ID',
 fill_color='YlGnBu',
 fill_opacity=0.8,
 line_opacity=0.05,
 legend_name='Percentage Foreigners(%)',
 threshold_scale=[0, 5, 10, 15, 20, 25]
)

folium.LayerControl().add_to(map_1)

# Save as index.html
map_1.save('index.html')

The result:

[MAC] Install matplotlib basemap on virtualenv

I am using Python3.6 and MacOS 10.13.2(Beta) but should work with similar setups.

First create and activate your virtual environment, by default mine is created on top of Python3.6.

~ ‚ĚĮ‚ĚĮ‚ĚĮ mkvirtualenv basemap-virtualenv
[...]
Installing setuptools, pip, wheel...done.
[...]
(basemap-virtualenv) ~ ‚ĚĮ‚ĚĮ‚ĚĮ cd Desktop
(basemap-virtualenv) ~/Desktop ‚ĚĮ‚ĚĮ‚ĚĮ curl https://codeload.github.com/matplotlib/basemap/tar.gz/v1.1.0 -o basemap-v1.1.0.tar.gz

Note that I am using the latest version 1.1.0 as of the time of writing this, but you should use the latest available on https://github.com/matplotlib/basemap/releases.

Let’s start the installation

(basemap-virtualenv) ~/Desktop ‚ĚĮ‚ĚĮ‚ĚĮ tar -xvf basemap-v1.1.0.tar.gz
(basemap-virtualenv) ~/Desktop ‚ĚĮ‚ĚĮ‚ĚĮ cd basemap-1.1.0/geos-3.3.3/
(basemap-virtualenv) ~/D/b/geos-3.3.3 ‚ĚĮ‚ĚĮ‚ĚĮ export GEOS_DIR=/usr/local
(basemap-virtualenv) ~/D/b/geos-3.3.3 ‚ĚĮ‚ĚĮ‚ĚĮ ./configure --prefix=$GEOS_DIR
(basemap-virtualenv) ~/D/b/geos-3.3.3 ‚ĚĮ‚ĚĮ‚ĚĮ make; make install

After this geos library is installed, let’s jump onto installing basemap.

(basemap-virtualenv) ~/D/basemap-1.1.0 ‚ĚĮ‚ĚĮ‚ĚĮ pip install numpy
(basemap-virtualenv) ~/D/basemap-1.1.0 ‚ĚĮ‚ĚĮ‚ĚĮ pip install pyproj
(basemap-virtualenv) ~/D/basemap-1.1.0 ‚ĚĮ‚ĚĮ‚ĚĮ pip install pyshp

(basemap-virtualenv) ~/D/basemap-1.1.0 ‚ĚĮ‚ĚĮ‚ĚĮ python setup.py install
[...]
customize UnixCCompiler
customize UnixCCompiler using build_ext
building '_geoslib' extension
compiling C sources
C compiler: clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes

compile options: '-I/usr/local/include -I['/Users/myself/.virtualenvs/basemap-virtualenv/lib/python3.6/site-packages/numpy/core/include'] -I/Users/myself/.virtualenvs/basemap-virtualenv/lib/python3.6/site-packages/numpy/core/include -I/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/include/python3.6m -c'
clang: src/_geoslib.c
zsh:1: no matches found: -I[/Users/myself/.virtualenvs/basemap-virtualenv/lib/python3.6/site-packages/numpy/core/include]
zsh:1: no matches found: -I[/Users/myself/.virtualenvs/basemap-virtualenv/lib/python3.6/site-packages/numpy/core/include]
error: Command "clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I['/Users/myself/.virtualenvs/basemap-virtualenv/lib/python3.6/site-packages/numpy/core/include'] -I/Users/myself/.virtualenvs/basemap-virtualenv/lib/python3.6/site-packages/numpy/core/include -I/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/include/python3.6m -c src/_geoslib.c -o build/temp.macosx-10.12-x86_64-3.6/src/_geoslib.o -MMD -MF build/temp.macosx-10.12-x86_64-3.6/src/_geoslib.o.d" failed with exit status 1

As we can see, the installation out of the box is failing. More specifically, the command

clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes compile options: '-I/usr/local/include -I['/Users/myself/.virtualenvs/basemap-virtualenv/lib/python3.6/site-packages/numpy/core/include'] ...

The reason lies in a bug on setup.py.  If you read the error, you will see how we are trying to include (-I) a path, but instead, we are passing a python array with a single string inside.  To fix this go to this line:

geos_include_dirs = [os.path.join(GEOS_dir,'include'),inc_dirs]

and change it to:

geos_include_dirs = [os.path.join(GEOS_dir,'include'),inc_dirs[0]]

After that python setup.py install succeeds.

Python Stripe Signature Verification Error

Building a Django + Stripe integration today I kept hitting the SignatureVerificationError.

According to their webhook’s documentation, they recommend something like this:

@csrf_exempt
def my_webhook_view(request):
  payload = request.body
  sig_header = request.META['HTTP_STRIPE_SIGNATURE']
  event = None

  try:
    event = stripe.Webhook.construct_event(
      payload, sig_header, endpoint_secret
    )
  except ValueError as e:
    # Invalid payload
    return HttpResponse(status=400)
  except stripe.error.SignatureVerificationError as e:
    # Invalid signature
    return HttpResponse(status=400)

  # Do something with event

  return HttpResponse(status=200)

I think would work fine with python2, but in my case the signature being generated never matched the expected signature hence triggering the exception stripe.error.SignatureVerificationError

The solution is to utf8 decode the payload, on line 3, change:

payload = request.body
payload = request.body.decode('utf-8')

That did the trick, hope it can save someone some time.

Home Temperature Monitor MSP 430 + Raspberry Pi

Introduction

I am going to share a small project I did a few days ago. I wanted to use the Raspberry Pi to monitor the¬†temperature in my house and ideally to do it over the internet, so I started looking for a temperature sensor. The first problem is that the Raspberry Pi doesn¬īt have an Analog to Digital converter, so its GPIO are strictly digital, meaning that simple temperature sensors that output the temperature as a voltage in a range cannot be used directly.

So looking around my house I discovered I had a LaunchPad MSP430 (version G2231) from Texas Instrument, which comes luckily equipped with an internal temperature sensor. I thought I could connect the MSP 430 to the Raspberry Pi so that the latter could read the temperature values from the former. Then I could put the data in a MySQL database on the Rpi side and build a web server to plot that data.

MSP 430

First, we need to set up the MSP 430 to read the temperature values from its internal sensor using an ADC. Then we can set up the i2C  in slave transmitter mode (the RPi can only work as a master). If you are starting with the MSP 430, I would recommend taking a look at its user guide and then to analyze some of the examples that come with Code Composer. It has a great debugger that allows you to stop the execution at any moment, look and modify the registers, step by step execution, etc.

Temperature Sensor + ADC

The temperature sensor is described briefly on page 550 of the user guide. It can be sampled by the ADC if we select the register INCx1010 INCHx=1010. Let’s take a look at the code. I used a lot of it from the examples, is not bad if you know what you are doing, but you need to be careful and can¬īt simply copy and paste different examples.

#include <msp430g2231.h>         // It has the definitions for all the registers, modes, etc.
 
unsigned int temp;               // holds ADC result
char SLV_Data = 0;                     // Variable for transmitted data   
 
int main(void)
{
      WDTCTL = WDTPW + WDTHOLD;            // Stop watchdog
 
      ADC10CTL1 = INCH_10 + ADC10DIV_3;         // Select Channel 10 and clk divided by 4
      ADC10CTL0 = SREF_1 + ADC10SHT_3 + REFON + ADC10ON + ADC10IE;      // Set Reference value Enable interrupts and turns on the ADC10
      TACCR0 = 30;                              // Delay to allow Ref to settle. Definition in the user guide
      TACCTL0 |= CCIE;                          // Interrupt enable for the Capture Compare
      TACTL = TASSEL_2 | MC_1;                  // Source clock TACLK = SMCLK, Count mode :Up
 
      _EINT();                                  // General Interrupt Enable
 
while(1)
  {
     ADC10CTL0 |= ENC + ADC10SC;             // Sampling and conversion start
     temp = ADC10MEM - 50;
  }
}
 
#pragma vector=ADC10_VECTOR
__interrupt void ADC10_ISR (void)
{
        SLV_Data = temp-50;             // To the data readed from the ADC (range 0-1023) substract 50.
}
 
#pragma vector=TIMERA0_VECTOR
__interrupt void ta0_isr(void)
{
    ADC10CTL0 |= ENC;                     // Enable conversion
    TACTL = 0;                            // Clear the Timer A control register
}

This is the code for the ADC conversion. If you have any doubt about what I did you can ask in the comments, and look at the User Guide from Texas Instrument. Also, I found really useful to look at the msp430g2231.h To access that file you can hold the ctrl button while you click on it, and it will open in a new tab. There you can see what all those TACTL, ADC10CTL0, etc. are

There is one thing to be noted and is that the value read by the ADC is 10 bits long, however for 2i2 we need packages of 8 bits of data, of course we could split the package of 10 into two packages of 8 bits, one of them containing 6 dummy zeroes, but here comes the trick: the whole range of the thermometer is not needed. A normal house temperature doesn¬īt range from -50 C to +80 C, so we can omit the two most significant bits (MSB), and make substract or add a value to the variable so a normal temperature stays approx. in the middle range (around 128). That’s why I subtracted 50, so now cold temperatures in the house correspond to 90 while warm ones stay around the 140.

i2C Communication Implementation

Now that we have the value of the temperature in the variable LDta SLVData we need to send it to the Raspberry Pi. We are going to use i2Ci2C for its simplicity. Other protocols such as UART or SPI are somewhat more complicated to implement.

First let’s take a look at the code, here I combined the previous part with this new one so this is the final code:

#include <msp430g2231.h>
 
char SLV_Data = 0;                     // Variable for transmitted data
char SLV_Addr = 0x90;                  // Address is 0x48
int I2C_State = 0;                     // State variable
 
unsigned int temp;            // holds  ADC result
unsigned int IntDegC;
 
int main(void)
{
  WDTCTL = WDTPW + WDTHOLD;            // Stop watchdog
  if (CALBC1_1MHZ==0xFF)               // If calibration constants erased
  {
    while(1);                          // do not load, trap CPU!!
  }
  DCOCTL = 0;                          // Select lowest DCOx and MODx settings
  BCSCTL1 = CALBC1_1MHZ;               // Set DCO
  DCOCTL = CALDCO_1MHZ;
 
  ADC10CTL1 = INCH_10 + ADC10DIV_3;         // Temp Sensor ADC10CLK/4
  ADC10CTL0 = SREF_1 + ADC10SHT_3 + REFON + ADC10ON + ADC10IE;      // Enable interrupts.
  TACCR0 = 30;                              // Delay to allow Ref to settle
  TACCTL0 |= CCIE;                          // Compare-mode interrupt.
  TACTL = TASSEL_2 | MC_1;                  // TACLK = SMCLK, Up mode.
 
  P1OUT = 0xC0;                        // P1.6 & P1.7 Pullups
  P1REN |= 0xC0;                       // P1.6 & P1.7 Pullups
  P1DIR = 0xFF;                        // Unused pins as outputs
  P2OUT = 0;
  P2DIR = 0xFF;
 
  USICTL0 = USIPE6+USIPE7+USISWRST;    // Port & USI mode setup
  USICTL1 = USII2C+USIIE+USISTTIE;     // Enable I2C mode & USI interrupts
  USICKCTL = USICKPL;                  // Setup clock polarity
  USICNT |= USIIFGCC;                  // Disable automatic clear control
  USICTL0 &= ~USISWRST;                // Enable USI
  USICTL1 &= ~USIIFG;                  // Clear pending flag
  _EINT();
 
  while(1)
  {
     ADC10CTL0 |= ENC + ADC10SC;             // Sampling and conversion start
     temp = ADC10MEM - 50;
 
  }
}
 
//******************************************************
// USI interrupt service routine
//******************************************************
#pragma vector = USI_VECTOR
__interrupt void USI_TXRX (void)
{
  if (USICTL1 & USISTTIFG)             // Start entry?
  {
    P1OUT |= 0x01;                     // LED on: Sequence start
    I2C_State = 2;                     // Enter 1st state on start
  }
 
  switch(I2C_State)
    {
      case 0: //Idle, should not get here
              break;
 
      case 2: //RX Address
              USICNT = (USICNT & 0xE0) + 0x08; // Bit counter = 8, RX Address
              USICTL1 &= ~USISTTIFG;   // Clear start flag
              I2C_State = 4;           // Go to next state: check address
              break;
 
      case 4: // Process Address and send (N)Ack
              if (USISRL & 0x01)       // If read...
                SLV_Addr++;            // Save R/W bit
              USICTL0 |= USIOE;        // SDA = output
              if (USISRL == SLV_Addr)  // Address match?
              {
                USISRL = 0x00;         // Send Ack
                P1OUT &= ~0x01;        // LED off
                I2C_State = 8;         // Go to next state: TX data
              }
              else
              {
                USISRL = 0xFF;         // Send NAck
                P1OUT |= 0x01;         // LED on: error
                I2C_State = 6;         // Go to next state: prep for next Start
              }
              USICNT |= 0x01;          // Bit counter = 1, send (N)Ack bit
              break;
 
      case 6: // Prep for Start condition
              USICTL0 &= ~USIOE;       // SDA = input
              SLV_Addr = 0x90;         // Reset slave address
              I2C_State = 0;           // Reset state machine
              break;
 
      case 8: // Send Data byte
              USICTL0 |= USIOE;        // SDA = output
              USISRL = SLV_Data;       // Send data byte
              USICNT |=  0x08;         // Bit counter = 8, TX data
              I2C_State = 10;          // Go to next state: receive (N)Ack
              break;
 
      case 10:// Receive Data (N)Ack
              USICTL0 &= ~USIOE;       // SDA = input
              USICNT |= 0x01;          // Bit counter = 1, receive (N)Ack
              I2C_State = 12;          // Go to next state: check (N)Ack
              break;
 
      case 12:// Process Data Ack/NAck
              if (USISRL & 0x01)       // If Nack received...
              {
                P1OUT |= 0x01;         // LED on: error
              }
              else                     // Ack received
              {
                P1OUT &= ~0x01;        // LED off
                SLV_Data++;            // Increment Slave data
              }
              // Prep for Start condition
              USICTL0 &= ~USIOE;       // SDA = input
              SLV_Addr = 0x90;         // Reset slave address
              I2C_State = 0;           // Reset state machine
              break;
    }
 
  USICTL1 &= ~USIIFG;                  // Clear pending flags
}
 
#pragma vector=ADC10_VECTOR
__interrupt void ADC10_ISR (void)
{
        SLV_Data = temp-50;
}
 
#pragma vector=TIMERA0_VECTOR
__interrupt void ta0_isr(void)
{
    ADC10CTL0 |= ENC;
    TACTL = 0;
}

Now, this part is slightly more complicated. Usually, people rely on a library to ease i2C operations, here the whole implementation of the i2C state machine is displayed. You don’t really need to go through all the operations, but if you are curious, with the user guide you should be able to decode what the code is doing. Is also complicated to debug an i2C slave transmitter code since you need a master to generate the clock signal and to send the address, etc.

Once this code is compiled and pushed into the MSP 430, we are ready to jump to the RPi side.

Raspberry Pi

The first thing to do in the RPi is the interconnection for the i2Ci2C protocol. The pin 1.6 is SCL and the pin 1.7 is SDA so the should be connected respectively to Pin 5 and Pin 3 of the RPi (Model B 512 Mbytes RAM).

SDA and SCL lines inside the square

We should also add a pull-up resistor on those lines to ensure the pins are never floating. I choose values of 2Kő©2Kő© and they are working just fine.

Turn for the software side on the raspberry pi. First is to add the i2Ci2C modules to the kernel. I will not enter on much more detail here. There is an excellent guide that will take you through the process here.

After that, if you run $ i2cdetect -y 1 you should see your MSP430 listening for your orders.

pi@raspberrypi ~ $ sudo i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- 48 -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --

Now is the turn for the python code to obtain the values every minute (you can choose whatever you want). I decided to store the value in a MySQL database. I found this guide, that was perfect! I did mostly the same except for adding the field Zone, as I only had one thermometer, it is not needed.

sudo apt-get install mysql-server python-mysqldb

Once completed we can go ahead:

$ mysql -u root -p
Enter password:
mysql> CREATE DB temps;
mysql> USE temps;
mysql> CREATE USER 'monitor'@'localhost' IDENTIFIED BY 'password';
mysql> GRANT ALL PRIVILEGES ON temps.* TO 'monitor'@'localhost'
mysql> FLUSH PRIVILEGES;
mysql> CREATE TABLE tempdat (tdate DATE, ttime TIME, temperature NUMERIC);
#!/usr/bin/env python
import time
import os
import sys
import MySQLdb
import smbus
 
bus = smbus.SMBus(1)
address = 0x48;
 
db = MySQLdb.connect("localhost", "monitor", "password", "temps")
curs=db.cursor()
 
def readTemp():
        temp = bus.read_byte(address)
        return temp
 
while True:
    time.sleep(60)    # wait for 60 seconds to record next temperature
    temp = readTemp();
     
    print (temp)  # Used for debugging
    time.sleep(1)  
    curs.execute ("""INSERT INTO tempdat values(CURRENT_DATE(), NOW(), %s)""",temp)
 
    db.commit()

All pretty simple stuff. Now are system is mainly completed but data is useless unless we can access it! So I created a web server that will serve a website plotting the data. Now we have our database ready to be populated. Lets then get to our python code.

Web server to plot the data

First, we need to install apache on the RPi. To do so I followed this guide from Instructables. After, you should be able to introduce the local IP address of your RPi, in my case 192.168.0.103 and see the “it works!” website located in the¬†/var/www¬†of your RPi.

To plot the data I used the library Charts.JS I simply downloaded the .js file from GitHub and put it in the folder /var/www. And then I coded this small website.

<!doctype html>
<html>
  <head>
    <?php
        ini_set('display_errors', 'On');
        error_reporting(E_ALL);
        // Create connection
        $con=mysql_connect("localhost","monitor","password","temps");
 
        // Check connection
        if (mysqli_connect_errno())
        {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        
        // Query the data from the last two days of temperatures
        $data = mysql_query("SELECT * FROM temps.tempdat WHERE tdate >= DATE_SUB(CURRENT_DATE, INTERVAL 2 DAY)");
 
        if (!$data) { // add this check.
            die('Invalid query: ' . mysql_error());
        }
 
        $Temp = array();
        $avgTemp = array();
        $contador = 0;
 
        // Get all the temperature records in array
        while($info = mysql_fetch_array( $data ))
        {
            $Temp[$contador] = $info['temperature'];
            $contador = $contador + 1;
        }
        
        $avgTemp = array_fill(0, count($Temp), 0);  // average temperature initialized to zeroes
        $tempData="[";      // This is the way the data should be given to JS [1,2,3,4...]
        $tempLabel = "[";
 
        for ($i = 0; $i < count($Temp) - 10; $i=$i+10) {
            for ($j = 0; $j < 10; $j++){
                $avgTemp[$i] += 0.10 * intval($Temp[$i+$j]);
            }
        
            $tempData .= (string)$avgTemp[$i];
            $tempData .= ",";
  
            $tempLabel .= "\".";  // I dont care about the labels, so I used ".." if you want, you can put the date records in here.
            $tempLabel .= ".\"";
            $tempLabel .= ",";
 
        }
 
        $tempData = substr($tempData, 0, -1); // Remove the last comma of the string    [1,3,5,6,   =>    [1,3,5,6
        $tempLabel= substr($tempLabel, 0, -1);
 
        $tempData .= "]";  // Close the bracket,    [1,3,5,6  =>  [1,3,5,6]
        $tempLabel .= "]";
?>
 
    <title>Temperatura de la Casa</title>
    <script src="./Chart.js" type="text/javascript"></script>
    <meta name = "viewport" content = "initial-scale = 1, user-scalable = no">
      <style>
        canvas{
        }
      </style>
    </head>
  <body>
    <canvas id="canvas" height="600" width="1200"></canvas>
    <script>
 
      var lineChartData = {
      labels :  <?php echo $tempLabel ?>,
      datasets : [
 
      {
      fillColor : "rgba(151,187,205,0.5)",
      strokeColor : "rgba(151,187,205,1)",
      pointColor : "rgba(151,187,205,1)",
      pointStrokeColor : "#fff",
      data : <?php echo $tempData ?>
      }
      ]
 
      }
 
      var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Line(lineChartData);
 
    </script>
  </body>
</html>

Conclusion

This concludes my project. RPi + MSP430 +  i2C + MySQL + PHP + JavaScript, really complete, multidisciplinary and fun project! Comment if you like. Here is a capture of the temperature inside my house!