Skrolli 2018.4: Google Analytics -näyttö
Linkit
- Google Analytics: https://analytics.google.com/analytics
- Adafruit: https://www.adafruit.com
- Adafruit - Level Shifter: https://www.adafruit.com/product/757
- Adafruit - 7-segmenttinäyttö: https://www.adafruit.com/product/878
- Google Developer Console https://play.google.com/apps/publish
- Rasperi: https://rasperi.fi/tuote-osasto/tuotteet/raspberry-pi-kotelo/
- Jimm's: https://www.jimms.fi/fi/Product/List/000-1K4
Listaus
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from array import array
import math
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
import time
from Adafruit_7Segment import SevenSegment
from random import randint
import threading
import RPi.GPIO as GPIO
# Alustetaan GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Indeksi sille mitä ruudulla näkyy, eli 1, 7 vai 30 päivän luku
resultIndex = 0
# Alustetaan taulukko jonne päivät tallennetaan, tässä voi aluksi olla mitä
# vaan, mutta näillä luvuin erotetaan mitä ruudussa lukee
resultArray = [1,2,3]
# Määritellään segmenttinäytöt
s0 = SevenSegment(address=0x70)
s1 = SevenSegment(address=0x71)
# Määritellään lukujen paikat segmenttinäytöillä
segments = [s0,s0,s0,s0, s1,s1,s1,s1]
# 2 on segmenttinäytöissä välissä oleva kaksoispiste, jätetään pois
digits = [0,1,3,4, 0,1,3,4]
# Google analytics -koodi
def get_service(api_name, api_version, scope, key_file_location,
                service_account_email):
  credentials = ServiceAccountCredentials.from_p12_keyfile(
    service_account_email, key_file_location, scopes=scope)
  http = credentials.authorize(httplib2.Http())
  service = build(api_name, api_version, http=http)
  return service
def get_first_profile_id(service):
  accounts = service.management().accounts().list().execute()
  if accounts.get('items'):
    account = accounts.get('items')[0].get('id')
    properties = service.management().webproperties().list(
        accountId=account).execute()
    if properties.get('items'):
      property = properties.get('items')[0].get('id')
      profiles = service.management().profiles().list(
          accountId=account,
          webPropertyId=property).execute()
      if profiles.get('items'):
        return profiles.get('items')[0].get('id')
  return None
def get_results(service, profile_id, days):
  if int(days) == 1:
    sd = 'today'
  else:
    sd = (days + 'daysAgo')
  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date=sd,
      end_date='today',
      metrics='ga:users').execute()
# Vaihdetaan mitä ruudulla näkyy
def change_visual():
  global resultIndex
  resultIndex = resultIndex + 1
  if resultIndex >= len(resultArray):
    resultIndex = 0
  update_leds()
# Päivitetään 7-segmenttinäytöille mitä näkyy ruudulla
def update_leds():
  result = int(resultArray[resultIndex])
  # Kelataan näytölle tulostettava luku läpi ja kirjoitetaan yksitellen 
  # ruudulle numerot
  for i in range(0,8):
    ci = 7 - i
    po = math.pow(10, ci)
    if result >= (po):
      # Tulosta numero näytölle
      segments[i].writeDigit(digits[i], int(result % (po * 10) // po))
    else:
      # Sammuta numero
      segments[i].setColonState(digits[i], False)
def button_worker():
    while(True):
      input_state = GPIO.input(26)
      # Jos nappia on painettu
      if input_state == False:
        # Vaihda tilaa
        change_visual()
        # Odota hetki että ehtii ottaa sormen pois napilta, voi olla 
	# pidempikin aika
        time.sleep(0.25)
      # Tarkista napin tila 0.1 sekunnin välein
      time.sleep(0.1)
def ga_worker():
    # service_account_email:n ja p12-tiedoston saa googlen developer consolesta
    scope = ['https://www.googleapis.com/auth/analytics.readonly']
    service_account_email = '<OMA_TUNNUS>@appspot.gserviceaccount.com'
    key_file_location = '/home/pi/<OMA_TIEDOSTO>.p12'
    service = get_service('analytics', 'v3', scope, key_file_location, 
	service_account_email)
    profile = get_first_profile_id(service)
    resultArray[0] = get_results(service, profile, '30').get('rows')[0][0]
    resultArray[1] = get_results(service, profile, '7').get('rows')[0][0]
    resultArray[2] = get_results(service, profile, '1').get('rows')[0][0]
    update_leds()
# Pääohjelma, käynnistetään kaksi säiettä joista toinen lukee nappia ja toinen
# käy hakemassa googlesta tilastoja
def main():
  update_leds()
  b = threading.Thread(target=button_worker)
  b.start()
  while(True):
    g = threading.Thread(target=ga_worker)
    g.start()
    # Käynnistetään haulle aina uusi säie tasan 5 minuutin välein, niin
    # saadaan tulokset tasaisin väliajoin. Toinen vaihtoehto olisi laittaa
    # Sleep säikeen sisään, mutta jos tuloksien haussa kestää niin pidetään
    # haun aloittaminen tasaisena
    time.sleep(300)
main()