#!/usr/bin/env python3 
#coding=utf-8
import sys
import os, re

model = "910-2-748-3kW"

STRUCTsize = [8, 7, 5, 5, 5, 9, 4, 4, 4]
sumStruct = sum(STRUCTsize)

valEEP8 = [
#   Mode Jet  ADC  Izero Idiv Udiv ledS releS
    4,   0,   0,   7,    2,   1,   2,   9]
valEEP16 = [
#   Uo% Ud% Uzap Uvyp fHz E2B E1B
    71, 4,  80,  40,  50, 0,  27044,
#   Ureg Unap Pmax Imax Tmax
    260,   400,   0,   10000,   0,
#   PDms   fImA  DTns  releH releL
    5000,  1000, 2000, 1000, 800,
#   PWMmax OFFpwm OFFms  Tzap Tvyp
    9800,  2000,  30000, 50,  70,
#   MPPTms do1 up1 do2 up2 do3 up3 Izap  Ivyp
    100,   2,  1,  1,  1,  1,  2,  30000,   0, 
#   IcalADC IcalmA UcalADC UcalV  pcb       typ      R9   R18  sdcc
#   400,    9600,  560,    370] # 10-1/2oz  6kW/24A  30k  39k  I24
#   500,    9035,  560,    370] # 10-1/2oz  4kW/16A  43k  51k  I16
    900,    9000,  370,    240] # 9-10/2oz  3kW/12A  27k  33k  I12
#   500,    8700,  560,    380] # 9-10/2oz  3kW/12A  43k  33k  I12
#   400,    9500,  560,    380] #  9-9/2oz  6kW/24A  30k  39k  I24
#   500,    8700,  560,    380] #  9-9/2oz  4kW/16A  43k  47k  I16
#   500,    8700,  560,    380] #  9-9/2oz  3kW/12A  43k  47k  I12
#   500,    8700,  560,    380] #  9-9/2oz  2kW/9A   43k  47k  I9
#   900,    9450,  560,    370] #  9-9/1oz  2kW/9A   43k  47k  I9
#   500,    8800,  560,    370] #  9-8/2oz  3kW/12A  47k  47k  I12
#   600,    7000,  560,    370] #  9-7/2oz  3kW/11A  33k  30k  I11
#   600,    7000,  560,    370] #  9-6/2oz  3kW/11A  33k  30k  I11
#   600,    7000,  560,    370] #  9-5/2oz  3kW/11A  33k  30k  I11
valEEPpid16 = [
#   1P  PmA   DP  DPmA
    2,  500,  15,  100,
#   2P  PmA   DP  DPmA
    30, 9000, 10,  900]
    
textEEP = [
    "-Mode",",Jet",",ADC",",Izero",",Idiv",",Udiv",",ledS",",releS",
    "-Uo%",",Um%",",Uzap",",Uvyp",",fHz",",E2B",",E1B",
    "-Ureg",",Unap",",Pmax",",Imax",",Tmax",
    "-PDms",",fImA",",DT",",releH",",releL",
    "-PWMmax",",OFFpwm",",OFFms",",Tzap",",Tvyp",
    "-MPPTms",",do1",",up1",",do2",",up2",",do3",",up3",",Izap",",Ivyp",
    "-IcalADC",",IcalmA",",UcalADC",",UcalV",
    "-1P",",PmA",",DP",",DPmA",
    "-2P",",PmA",",DP",",DPmA",
    "IWDG\n","START\n","STOP\n","BREAK ","LOAD\n","RESTART\n","SAVE\n","ERASE\n","Iz ","Un ","Ur ","DP-\n",
    "Tl-|>rezim\n","Tl+|>ulozit\n",
    "-test \n","-rucne\n","-sinus\n","-Ufix \n","-mppt \n",'\0']
    
textDefine = [
    "mode","Jet","ADC","Izero","Idiv","Udiv","ledS","releS",
    "Uo","Umpr","Uzap","Uvyp","fHz","Emsb","Elsb",
    "Ureg","Unap","Pmax","Imax","Tmax",
    "DPms","fImA","DTns","releH","releL",
    "PWMmax","OFFpwm","OFFms","Izap","Ivyp",
    "MPPTms","do1","up1","do2","up2","do3","up3","Tzap","Tvyp",
    "IcalADC","IcalmA","UcalADC","UcalV",
    "1P","1PmA","1DP","1DPmA",
    "2P","2PmA","2DP","2DPmA"]

separ = "//----------------------------------------------------------------------------------- "

SOUBNAME = ""
SOUBOR = model + ".bin"
if not os.path.isfile("version.c"):
  print "Nenalezen soubor version.c"
  exit()
else:
  with open("version.c") as f:
    vrs = f.read()
  #print vrs
  pnzv = re.findall(r'RELEASE=([0-9a-zA-Z\-_]*)', vrs)
  if len(pnzv) > 0:
    SOUBNAME = str(pnzv[0])
    model = str(pnzv[0])
  else:
    print "chyba zpracovani version.c"
    exit()


rezim = 0

if len(sys.argv) > 1:
  if sys.argv[1] not in ("eeprom", "text", "define", "all"):
    print "chyba vstupni parametr [eeprom, text, define, all]"
  else:
    tajp = sys.argv[1]
    if tajp == "eeprom":
      rezim = 1
    if tajp == "define":
      rezim = 2
    if tajp == "text":
      rezim = 3
    if tajp == "all":
      rezim = 0

suffix = ""
if len(sys.argv) > 2:
  suffix = sys.argv[2]
  
SOUBOR = "bin/" + SOUBNAME + str(suffix) + ".bin"

souborDefinic = "define.h"
souborText = SOUBNAME + str(suffix) + ".txt"
if rezim in (0, 1):
  f = open(SOUBOR, 'wb')

velikost = 640
startPam = 0x4000
endPam = 0x4280
pocitadlo = 0

def zpracuj2byte(cislo):
  b1 = cislo >> 8
  b2 = cislo & 0x00FF
  rar = [b1, b2]
  
  return bytearray(rar)
  
# sestaveni popisu a kontrola poctu hodnot
definiceT = ""
popis = ""
popisPole = []
poziceTxt = 0
indexStruct = 0

if len(valEEP8) != STRUCTsize[0]:
	print "Nesedi pocet 8bit hodnot"
	os.system("rm define.h")
	exit(1)

if len(valEEP16) != sum(STRUCTsize[1:-2]):
	print "Nesedi pocet 16bit hodnot"
	os.system("rm define.h")
	exit(1)
	
if len(valEEPpid16) != sum(STRUCTsize[-2:]):
	print "Nesedi pocet pid hodnot"
	os.system("rm define.h")
	exit(1)
	
polehodnot = valEEP8 + valEEP16 + valEEPpid16

for stu in STRUCTsize:
	popis += str(indexStruct + 1)
	for it in range(poziceTxt, poziceTxt + STRUCTsize[indexStruct]):
		popisPole.append(str(textEEP[it]) + " " + str(polehodnot[it]))
	popis += "".join(popisPole)
	popis += "\n"
	popisPole = []
	poziceTxt = poziceTxt + STRUCTsize[indexStruct]
	indexStruct += 1

definiceT += separ
definiceT += "\n#define MODEL           \"" + model + "\"\n"
definiceT += separ
definiceT += "\n#define EEPstart        " + hex(startPam) + "\n"
definiceT += "#define EEPend          " + hex(endPam) + "\n"
definiceT += separ

# zapis 8bit #
if rezim in (0, 1):
  f.write(bytearray(valEEP8))


definiceD = ""  
pocitadlo += len(valEEP8)
definiceT += "\n#define EEPsystem8      " + hex(startPam) + " // system8"

#zapis jednotlive texty
cnt = 0
for cislo in valEEP8:
  definiceD += ("\n#define EEP_" + textDefine[cnt]).ljust(25, ' ')  + hex(startPam + cnt) + ""
  cnt += 1

definiceT += "\n#define EEPsystem16     " + hex(startPam + pocitadlo) + " // system16"

#zapis jednotlive texty16
dbl = 0
for cislo in valEEP16:
  definiceD += ("\n#define EEP_" + textDefine[cnt]).ljust(25, ' ') + hex(startPam + pocitadlo + dbl) + ""
  cnt += 1
  dbl += 2

# zapis 16bit #
if rezim in (0, 1):
  for cislo in valEEP16:
    #print cislo, cislo >> 8, cislo & 0x00FF
    f.write(zpracuj2byte(cislo))
pocitadlo += len(valEEP16) * 2 


definiceT += "\n#define EEPpid          " + hex(startPam + pocitadlo) + " // pid"

#zapis jednotlive textypid16
dbl = 0
for cislo in valEEPpid16:
  definiceD += ("\n#define EEP_" + textDefine[cnt]).ljust(25, ' ') + hex(startPam + pocitadlo + dbl) + ""
  cnt += 1
  dbl += 2

if rezim in (0, 1):
  for cislo in valEEPpid16:
    f.write(zpracuj2byte(cislo))
pocitadlo += len(valEEPpid16) * 2
definiceT += "\n#define EEPtext         " + hex(startPam + pocitadlo) + " // text"
definiceT += "\n" + separ

definiceT += definiceD + "\n" + separ

definice = ["#define textWatchdog    ",
            "#define textStart       ",
            "#define textStop        ",
            "#define textBreak       ",
            "#define textLoad        ",
            "#define textReset       ",
            "#define textSave        ",
            "#define textERASE       ",
            "#define textIz          ",
            "#define textUn          ",
            "#define textUr          ",
            "#define textDPdec       ",
            "#define textTLmRezim    ",
            "#define textTLpUlozit   ",
            "#define textTEST        ",
            "#define textRucne       ",
            "#define textSinus       ",
            "#define textUfix        ",
            "#define textMPPT        "]

portxt = 0
pocTexty = 0  
for text in textEEP:
  #print cislo, cislo >> 8, cislo & 0x00FF
  if pocTexty > sumStruct - 1 and text != "\0":
    definiceT += "\n" + definice[portxt] + hex(startPam + pocitadlo) + " // " + (textEEP[sumStruct + portxt]).replace('\n', '')
    portxt += 1
  if rezim in (0, 1):
    f.write(bytearray(text))
    f.write(bytearray("\0"))
  pocitadlo += len(text) + 1
  pocTexty += 1
  

definiceT += "\n" + separ
#define EEPstruct       8      
definiceT += "\n#define EEPstruct       " + str(len(STRUCTsize)) + "      // počet seznamů dat v EEPROM \n"  + separ +"\n"
definiceT += "// const uint8_t  STRUCTsize[EEPstruct] = {" + ", ".join(str(x) for x in STRUCTsize) + "}; // počet hodnot ve strukturách v EEPROM\n" + separ 
definiceT += "\n/*\n" + model + "\n" + popis + "*/"

popis = "\n" + model + "\n" + popis

nuly = []
for i in range(pocitadlo, velikost):
  nuly.append(0)

if rezim in (0, 1):  
  f.write(bytearray(nuly))

definiceT += "\n// eeprom free " + str(len(nuly)) + "\n"

if rezim in (0, 1):
  f.close()

#print definiceT
if rezim in (0, 2):
  with open(souborDefinic, "w") as myfile:
    myfile.write(definiceT)

if rezim in (0, 3):
  with open(souborText, "w") as myfile:
    myfile.write(popis)
  print popis #definiceT


