# (C) Fabrice Sincere
# python 3

# communication RS232 avec un thermomètre numérique à capteur numérique DS1620
# http://fabrice.sincere.free.fr/cm_electronique/projet_pic/thermometreLCD_DS1620htm/thermometreLCD_DS1620.htm

# test : OK windows 10 ; Linux/Ubuntu 24.04

import time
import serial

__version__ = (0, 0, 1)
__author__ = "Fabrice Sincère <fabrice.sincere@ac-grenoble.fr>"

print('Communication avec le port COM')

filename = 'temperature.txt'
print('\nFichier de sauvegarde : '+filename)
Fichier = open(filename, 'a')

Port = serial.Serial()

Port.baudrate = 9600
Port.bytesize = 8
Port.parity = 'N'  # none
Port.stopbits = 1
Port.xonxoff = 0
Port.rtscts = 0
Port.timeout = 0.1  # en seconde

print("""
# Sous Windows :   'COM1'
# Sous Linux :     '/dev/ttyS0'
""")

nomport = input('Nom du port COM ? ')
Port.port = nomport
Port.open()
print(Port)

print("CTRL+C pour quitter")
try:
    while True:
        # écriture
        Port.write(b'\xAA\x00\x00')

        # lecture
        MSB = Port.read()  # octet de poids fort
        MSB = MSB.decode(encoding="ascii")
        LSB = Port.read()  # octet de poids faible
        LSB = LSB.decode(encoding="ascii")

        if (MSB != '' and LSB != ''):
            temperature = ord(LSB) + 256*ord(MSB)
            if temperature >= 256:
                temperature = temperature - 512
            temperature *= 0.5
            affichage = time.strftime('%H:%M:%S', time.localtime()) + '  ' + str(temperature) + ' °C'
            print(affichage)
            Fichier.write(affichage+'\n')

        # pause 1 seconde
        time.sleep(1.0)

except KeyboardInterrupt:
    # CTRL + C
    Port.close()
    Fichier.close()
