# -*- coding: cp1252 -*-
"""
Convierte texto de un datasheet en código c para programar los
registros de configuración de un microcontrolador PIC cualquiera.
Entrada: copiar texto del datasheet y pegarlo en un archivo de texto
Por ejemplo: "timer1.txt"
Salida: archivo de texto con el código: "timer1.c"
"""
import re
import os
class empty_class:
"""empty class"""
out = []
bit = empty_class()
estado = 0
line_lenght_max = 80
# Función principal
def main():
for filename in os.listdir("."):
if filename[-4:].lower() == ".txt":
print filename
procesa(filename)
# Procesado de datos
def procesa(filename):
global estado, bit
lines = read(filename)
for line in lines:
line = line.strip("\n\t ")
if estado == 0:
if is_new_register(line):
estado = 1
out_reg(line)
elif estado == 1:
if is_new_bit(line):
estado = 2
out_bit(line)
elif is_new_register(line):
out_reg(line)
elif estado == 2:
if len(line) < 2 or re.match("Legend:", line):
estado = 0
elif is_new_bit(line):
out_bit(line)
elif is_new_register(line):
out_reg(line)
print "Error, bit inacabado"
estado = 1
else:
out_bit_comment(line);
write(filename, out)
# Comprueba si es el comienzo de un nuevo registro
def is_new_register(line):
if re.match("REGISTER [0-9]{1,2}-[1-9]{1,2}: ", line):
return True
return False
# Imprime el comienzo de un registro nuevo
def out_reg(line):
line = line.split(":", 1)[1].strip(" \t")
register = line.split(" ")[0].strip(":")
register_comment = line.split(" ", 1)[1]
out.append("\n\n")
out.append(" // %s: %s" % (register, register_comment))
out.append(" %s = (unsigned char)" % register)
print " Register =", register
# Comprueba si es el comienzo de un nuevo bit
def is_new_bit(line):
if re.match("bit[ \t]+[0-9]+(-[0-9]{1,2})? ", line) and not re.match("bit [715] bit 0", line):
return True
return False
def out_bit(line):
global bit, estado
bit.pos = line.split(" ")[1].split("-")[-1]
bit.name = line.split(" ", 3)[-2]
if len(re.findall("[0-9]:", bit.name)) > 1:
bit.name = bit.name.split(":")[0][:-1] + ":"
bit.comment = line.split(" ", 3)[-1]
if (int(bit.pos) > 9):
out.append(" +(0<<%s)// %s %s" % (bit.pos, bit.name, bit.comment))
elif (int(bit.pos) > 0):
out.append(" +(0<<%s) // %s %s" % (bit.pos, bit.name, bit.comment))
else:
out.append(" +(0); // %s %s" % (bit.name, bit.comment))
if re.search("unimplemented", line.lower()) and bit.pos == "0":
bit = empty_class()
estado = 1
def out_bit_comment(line):
if re.match("[01]+ = ", line):
out.append(" // %s" % bin_dec(line))
else:
out[-1] = out[-1] + " %s" % line
while len(out[-1]) > line_lenght_max:
string = out[-1]
i = line_lenght_max - 1
while i > 20:
if string[i] == " ":
break
i = i - 1
out[-1] = string[:i]
out.append(" // %s" % string[i+1:])
# Leer fichero de entrada
def read(filename):
fi = open(filename, "rt")
lines = [line for line in fi]
fi.close()
return lines
# Escribir lineas en un fichero de salida
def write(filename, lines):
filename = re.sub(".txt$", ".c", filename.lower())
fo = open(filename, "wt")
fo.write("\n".join(lines))
fo.write("\n");
fo.close()
# Traducir de binario a decimal
def bin_dec(string):
strbin_dec = [["00", 0], ["01", 1], ["10", 2], ["11", 3]]
for i in range(4):
new = []
for b, d in strbin_dec:
new.append( ["0" + b, d] )
new.append( ["1" + b, d + 2**len(b)] )
for n in new:
strbin_dec.append(n)
for b, d in strbin_dec:
if re.match("%s =" % b, string):
string = re.sub("%s = " % b, "%d = " % d, string, 1)
return string
main()