Wednesday, August 14, 2019

python

Here is my  python script. Let me know if you have any ideas why it crashes when log_data() is called?

import time
import serial
import smtplib

from email.message import EmailMessage

def log_data(filename, line):
    file_handle = open(filename, 'a+')
    file_handle.write(line)
    file_handle.close()


print('Hello World!')

ser = serial.Serial(
    '/dev/ttyAMA0',
    baudrate=57600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS)

time.sleep(.1)

try:
    ser.write('H\r')
    time.sleep(.25)
    ser.write('2\r')
    time.sleep(.25)
    ser.write('6\r')
    ser.reset_input_buffer()
    kludge = 0
    while True:
        data = ser.read_until('\n', 120)
        if kludge > 2 and len(data) > 12:
            log_data('log.txt', data)
            parse = data.split()
            print(parse[0]
                  + ' ' + parse[1]
                  + ' Amps ' + parse[8]
                  + ' ~ ' + parse[9]
                  + ' Volts ' + str(int(parse[10]) * 9.0 / 5 + 32)
                  + ' ~ ' + str(int(parse[11]) * 9.0 / 5 + 32)
                  + ' degF')
        kludge = kludge + 1

except BaseException:

    # email logged data before quitting
    print("Emailing data...")
    textfile = 'log.txt'
    with open(textfile) as fp:
        # Create a text/plain message
        msg = EmailMessage()
        msg.set_content(fp.read())

    msg['Subject'] = 'The contents of %s' % textfile
    msg['From'] = 'chrisdarilek@gmail.com'
    msg['To'] = 'chrisdarilek@gmail.com'

    username = 'chrisdarilek@gmail.com'

    # Send the message via our own SMTP server.
    s = smtplib.SMTP('smtp.gmail.com:587')
    s.starttls()
    s.login(username, password)
    s.send_message(msg)

    s.quit()
    print('Blow up the spacestation!')


finally:
    ser.close()
    pass

No comments:

Post a Comment