#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SIMULATION pour tester simulEHN.py avec bouclage port ttyUSB0 sur ttyAMA0
#
# écriture-lecture rebouclage du port série ttyAMA0 sur port ttyUSB0
# 
import serial
import struct
import time

PV_PLUS = 1
GV_PLUS = 5
Stop_EL = 16
Dec_plus = 18
Dec_moins = 17
Stop_Az = 0
Track = 7


port2 = "/dev/ttyAMA0"
port1 = "/dev/ttyUSB0"
serialPort1 = serial.Serial(port1, 9600, timeout = 2)
print ("Port Série ttyUSB0 ", port1, " ouvert pour le test :")
serialPort2 = serial.Serial(port2, 9600, timeout = 2)
print ("Port ttyAMA0 ", port2, " ouvert pour le test :")


def repondre (code):
    reponse = struct.pack('B',code)
    print("Ecriture ttyUSB0 : ",  reponse)

    bytes_sent = serialPort1.write(reponse)
    if bytes_sent != 1 :
        print("Erreur à l'émission\n")
        print("Octets écrits : ", bytes_sent)
        print("write serialPort : ", reponse)
#

#    byte_received = serialPort2.read()
#    print("Lecture ttyAMA0 : ", byte_received)
    byte_received = serialPort1.read()
    print("Lecture ttyUSB0 : ", byte_received)

while (1):
    repondre(150  % 256)
    repondre(160  % 256)
    repondre(128 % 256)
    repondre(149 % 256)
    repondre(224 % 256)
    repondre(224 % 256)
    repondre(192 % 256)
    repondre(192 % 256)
#
#    repondre(0 % 256)
#    repondre(0 % 256)
#
#    repondre(Track % 256)
    repondre(PV_PLUS % 256)
#    repondre(GV_PLUS % 256)
    repondre(Dec_moins % 256)
#    repondre(16 % 256)
#    repondre(7 % 256)
#   repondre(255 % 256)
    repondre(150  % 256)
# Délai d'envoi

    time.sleep(1)

# Deuxième séquence
    repondre(150  % 256)
    repondre(160  % 256)
    repondre(128 % 256)
    repondre(149 % 256)
    repondre(224 % 256)
    repondre(224 % 256)
    repondre(192 % 256)
    repondre(192 % 256)

    repondre(Track % 256)
# Clock fin de séquence
    repondre(150  % 256)
    time.sleep(1)

