# File name: CountMe.py
# Copyright: The AustSTEM Foundation Limited
# Author: Tony Strasser
# Date created: 19 August 2018
# Date last modified: 18 Jun 2019
# MicroPython Version: 1.10 for the Kookaberry V4-05
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
# To the fullest extent permitted by law, AustSTEM absolutely disclaims 
# all warranties, expressed or implied, including, but not limited to, 
# implied warranties of merchantability and fitness for any particular purpose. 
# AustSTEM gives no warranty that this software will be free of errors, 
# or that defects in the software will be corrected,  
# See the GNU General Public License for more details.
#
# This is a totaliser program which counts key presses on an attached
# Gravity AD Keyboard.  The keyboard has 5 coloured keys: Y G B R W
# The totals of each key pressed displayed
# Controls are provided to Exit, Reset, Pause, and Save the totals to a file
# Lesson plan designator added to the radio message.

import machine, kooka, fonts, time
from Kapputils import config    # utility to read the configuration file

lesson = 'KLP001'    # lessonplan designation
k_plug = 'P4' # input port to use for the AD Keyboard - change this to suit
k_vals = [3197, 3328, 3484, 3656, 3897, 4095]    # threshholds for keys
k_ids = ['Y','G','B','R','W','-']    # key identities
k_last = 5    # set last key read as none
k_pressed = 0    # indicates new key press
k_count = [0,0,0,0,0,0]    # totaliser for each key (and no key)
k_pause = 0    # flag to pause counting
pause = ['Pse','Res']    # display strings for pause control

key = machine.ADC(machine.Pin(k_plug))  # create the analogue input for the keyboard
disp = kooka.display
params = config('Kappconfig.txt')   # read the configuration file
chan = int(params['CHANNEL'])      # use channel from the configuration file
baud = int(params['BAUD'])      # use data rate from the configuration file
pwr = int(params['POWER'])      # use transmit power from the configuration file
kooka.radio.enable()
kooka.radio.config(channel=chan, data_rate=baud, power=pwr) # set up the radio

while not kooka.button_a.was_pressed():
    k_read = key.read()    # read the keyboard
    for k_ptr in range(0,6):
        if k_read < k_vals[k_ptr]: break    # identify the key
    if k_ptr != k_last: # work out if a new key press
        k_pressed = 1
        k_last = k_ptr
        if not k_pause: k_count[k_ptr] += 1    # update the totaliser
    disp.fill(0)
    disp.setfont(fonts.mono8x8)
    disp.text('Count Me', 0, 6)
    disp.text('Kbd:%s' % (k_plug), 80, 6)
    disp.setfont(fonts.mono6x7)
#    if k_pause: disp.text('ADC = %d' % k_read, 20, 48)    # debug
    disp.text('X', 6, 60)	    # A Key = Exit
    disp.text('Rst', 24, 60)	    # C Key = Reset totals
    disp.text('%s' % pause[k_pause], 64, 60)	    # D Key = Pause counting
    disp.text('Sav', 108, 60)	    # B Key = Save results
# Adjust controls by means of Kookaberry keys
    if kooka.button_c.was_pressed(): 
        for x in range(0,6): k_count[x] = 0    # reset totals
    if kooka.button_d.was_pressed(): k_pause = not k_pause    # pause counting
    if kooka.button_b.was_pressed(): 
        f = open(params['FILE'],'w+')         # open a text file for writing
        f.write('Kookaberry Log for %s\n' % params['NAME'])
        f.write('%s,%s,%s,%s,%s\n' % (k_ids[0],k_ids[1],k_ids[2],k_ids[3],k_ids[4]))   # write the heading line
        f.write('%d,%d,%d,%d,%d\n' % (k_count[0],k_count[1],k_count[2],k_count[3],k_count[4]))   # write the counts
        f.close()    # close file to guard against corruption
        print('%s,%d,%d,%d,%d,%d' % (params['NAME'],k_count[0],k_count[1],k_count[2],k_count[3],k_count[4]))
        kooka.radio.send('%s,%s,%d,%d,%d,%d,%d' % (lesson,params['NAME'],k_count[0],k_count[1],k_count[2],k_count[3],k_count[4]))

    disp.setfont(fonts.mono8x13)
    for x in range(0,5):
        disp.text('%s' % (k_ids[x]), (8 + 24 * x), 21)
        disp.text('%d' % (k_count[x]), (8 + 24 * x), 34)
    disp.show()
    time.sleep_ms(50)

