universalpad.py 38 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
# -*- coding: utf-8 -*-
import sys
import time
import socket
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont
from threading import Thread, RLock, Event
import select, queue
import platform

# --- celme imports
modulename = 'celme'
if modulename in dir():
    del celme
if modulename not in dir():
    import celme
    
from mountastro_astromecca import Mountastro_Astromecca
from mountaxis import Mountaxis
from mounttools import Mounttools
from mountchannel import Mountchannel

# #####################################################################
# #####################################################################
# #####################################################################
# Class Universalpad
# #####################################################################
# #####################################################################
# This class provides a pad
# #####################################################################

lock = RLock()

class UniversalPadServer(Thread):
    """
    For SERIAL or TCP connections
    """
    
    def __init__(self, *args, **kwargs):
        Thread.__init__(self)
        self._myself = args[0]
        #print("*args={}".format(args))
        #print("**kwargs={}".format(kwargs))
        # --- Dico of optional parameters for all axis_types
        param_optionals = {}
        param_optionals["PROTOCOL"] = (str, "LX200")
        # --- Dico of axis_types and their parameters
        remote_transport_protocols = {}
        remote_transport_protocols["SERIAL"] = {"MANDATORY" : {"PORT":[str,"//./COM1"]}, "OPTIONAL" : {"BAUD":[int,9600]} }
        remote_transport_protocols["TCP"]    = {"MANDATORY" : {"PORT":[int,1111]}, "OPTIONAL" : {} }
        # --- Decode args and kwargs parameters
        mounttools = Mounttools()
        params = mounttools.decode_args_kwargs(1,remote_transport_protocols, param_optionals, *args, **kwargs)
        self._remote_transport_protocol = params["SELECTED_ARG"]
        self._remote_command_protocol = params["PROTOCOL"]
        if self._remote_transport_protocol=="SERIAL":
            self._port = params["PORT"]
            self._baud_rate = params["BAUD"]
            #msg = "port={} baud={}".format(self._port,self._baud_rate)
            #self._myself._themount.log.print(msg)
        elif self._remote_transport_protocol=="TCP":
            self._port = params["PORT"]
            #msg = "port={}".format(self._port)
            #self._myself._themount.log.print(msg)
        # ---
        self._stopevent = Event( )        

    def run(self):
        """Code à exécuter pendant l'exécution du Thread"""
        msg = "The thread UniversalPadServer is started"
        self._myself._themount.log.print(msg)
        if self._remote_transport_protocol=="SERIAL":
            self._channel = None
            while not self._stopevent.isSet():
                # --- Open the serial server if needed
                if self._channel==None: 
                    try:
                        if self._remote_command_protocol=="LX200":
                            self._channel = Mountchannel("SERIAL", port=self._port, baud_rate=self._baud_rate, delay_init_chan=0.1, end_of_command_to_send="#".encode('utf8'), end_of_command_to_receive="#".encode('utf8'), delay_put_read=0.06)
                            self._channel.verbose_chan = False
                        if self._remote_command_protocol=="ASTROMECCA":
                            self._channel = Mountchannel("SERIAL", port=self._port, baud_rate=self._baud_rate, delay_init_chan=0.1, end_of_command_to_send="#".encode('utf8'), end_of_command_to_receive="#".encode('utf8'), delay_put_read=0.06)
                            self._channel.verbose_chan = False
                    except:
                        time.sleep(0.1)
                        continue
                    msg = "{} server listening port {} for protocol {}".format(self._remote_transport_protocol, self._port, self._remote_command_protocol)
                    self._myself._themount.log.print(msg)
                    self._myself.pad_cbk_disp_message(msg+"\n","remote")
                # --- read the commands from the client
                command = ""
                msg = ""
                try:
                    err, commands = self._channel.read_chan()
                    #print("lignes = {}".format(lignes))
                    command = str(commands[0])
                except:
                    # --- connexion problem
                    try:
                        self._channel.close()
                    except:
                        pass
                    self._channel = None
                # --- process the received message
                try:
                    if err==self._channel.NO_ERROR and command != "":
                        self._myself._themount.log.print("command = {}".format(command))
                        msg = self._myself.remote_command_processing(command)
                        message = command + " -> " + msg
                        self._myself.pad_cbk_disp_message(message+"\n", "remote")
                    # --- send the answer to client
                    self._myself._themount.log.print("result = {}".format(msg))
                    self._myself.put_chan(msg)
                except:
                    pass
                time.sleep(0.01)
        elif self._remote_transport_protocol=="TCP":        
            self._channel = None
            # --- Open the serial server if needed
            try:
                self._channel = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self._channel.setblocking(0)
                self._channel.bind((socket.gethostname(), self._port))
                self._channel.listen(5)
                inputs = [self._channel]
                outputs = []
                message_queues = {}
            except:
                # --- connexion problem
                try:
                    self._channel.close()
                except:
                    pass
                self._channel = None 
                msg = "Unexpected error: {}".format(sys.exc_info())
                self._myself._themount.log.print(msg)
                return
            msg = "{} server listening port {} for protocol {}".format(self._remote_transport_protocol, self._port, self._remote_command_protocol)
            self._myself._themount.log.print(msg)
            self._myself.pad_cbk_disp_message(msg+"\n","remote")
            # --- read the commands from the client
            try:
                while inputs:
                    if self._stopevent.isSet():
                        break
                    time_out = 0.5
                    readable, writable, exceptional = select.select(inputs, outputs, inputs, time_out)
                    # ---
                    for s in readable:
                        if s is self._channel:
                            connection, client_address = s.accept()
                            connection.setblocking(0)
                            inputs.append(connection)
                            message_queues[connection] = queue.Queue()
                        else:
                            data = s.recv(1024)
                            #print("data={}".format(data))
                            if data:
                                #print("step 1")
                                message = data.decode("utf-8")
                                response = data
                                response = self._myself._themount.remote_command_processing(message)
                                msg = message + " => " + response
                                response = response.encode("utf-8")
                                self._myself._themount.log.print(msg)
                                self._myself.pad_cbk_disp_message(msg+"\n","remote")
                                message_queues[s].put(response)
                                if s not in outputs:
                                    outputs.append(s)
                            else:
                                #print("step 2")
                                if s in outputs:
                                    outputs.remove(s)
                                inputs.remove(s)
                                s.close()
                                del message_queues[s]
                    # ---
                    for s in writable:
                        try:
                            #print("step 3 s.fileno()={}".format(s.fileno()))
                            if s.fileno()==-1:
                                continue
                            next_msg = message_queues[s].get_nowait()
                        except queue.Empty:
                            outputs.remove(s)
                        else:
                            s.send(next_msg)
                
                    for s in exceptional:
                        inputs.remove(s)
                        if s in outputs:
                            outputs.remove(s)
                        s.close()
                        del message_queues[s]
            except:
                pass
            # ---
            if self._channel != None:
                self._channel.close()
        msg = "The thread UniversalPadServer termined properly"
        self._myself._themount.log.print(msg)

    def stop(self):
        self._stopevent.set( )

class UniversalPadRepeat(Thread):
    
    def __init__(self, myself):
        Thread.__init__(self)
        # ---
        self._stopevent = Event( )        
        self._myself = myself

    def run(self):
        """Code à exécuter pendant l'exécution du Thread"""
        msg = "The thread UniversalPadRepeat is started"
        self._myself._themount.log.print(msg)
        while not self._stopevent.isSet():
            try:
                self._myself.pad_cbk_compute_lst()
                self._myself.pad_cbk_compute_coord()
                #print("ok 1001")
            except:
                #print("pb 1001")
                pass
            time.sleep(0.5)
        msg = "The thread UniversalPadRepeat termined properly"
        self._myself._themount.log.print(msg)

    def stop(self):
        self._stopevent.set( )


class UniversalPad():

    # === Constant for error codes
    NO_ERROR = 0
    ERR_UNKNOWN = 1

    _side_items = ['Auto','Tube West','Tube East']

    def __init__(self):
        self._pad_type = None
        self.tkroot = None
        self._command_history = []
        self._command_history_index = 0

    def configuration(self, mount_model):
        #cwd = os.getcwd()
        hostname = socket.gethostname()
        # --- configuration depending the computer
        if hostname == "titanium":
            print("Configuration = {}".format(hostname))
            port_serial_scx11='//./com12' ; # '//./com4'
            port_serial_aux='//./com1'
        elif hostname == "rapido2":
            print("Configuration = {}".format(hostname))
            port_serial_scx11='/dev/ttyAMA0'
            port_serial_aux='/dev/ttyAMA1'
        else:
            print("Attention, pas de configuration pour {}".format(hostname))
            port_serial_scx11='//./com1'
            port_serial_aux='//./com2'
        print("port_scx11    = {}".format(port_serial_scx11))
        print("port_aux      = {}".format(port_serial_aux))
        # ==========
        self._themount = None
        if mount_model=="astromecca":
            self._pad_type = mount_model
            home = celme.Home("GPS 2.25 E 43.567 148")
            site = celme.Site(home)
            # === SCX11 connection
            self._themount = Mountastro_Astromecca("HADEC", name="Guitalens Mount", manufacturer="Astro MECCA", model="TM350", serial_number="beta001", site=site, CONTROLLER_BASE_ID=1, CONTROLLER_POLAR_ID=2)
            self._themount.set_channel_params("SERIAL", port=port_serial_scx11, baud_rate=115200, delay_init_chan=0.1, end_of_command_to_send="\r\n".encode('utf8'), end_of_command_to_receive="\r\n".encode('utf8'), delay_put_read=0.06)
            self._themount.verbose_chan = False
            # --- shortcuts
            self._themount_axisb = self._themount.axis[Mountaxis.BASE]
            self._themount_axisp = self._themount.axis[Mountaxis.POLAR]
            # --- simulation or not       
            mount_mode = self.padconfig['mount_mode']
            if mount_mode=="simulation":
                mount_mode_real = False
            else:
                mount_mode_real = True
            print("mount_mode={}".format(mount_mode))
            self._themount_axisb.real = mount_mode_real
            self._themount_axisb.ratio_wheel_puley = 6.32721
            self._themount_axisb.inc_per_motor_rev = 1540 # DPR for -490000 to +490000
            self._themount_axisb.senseinc = 1
            self._themount_axisp.real = mount_mode_real
            self._themount_axisp.ratio_wheel_puley = 6.8262
            self._themount_axisp.inc_per_motor_rev = 1421
            self._themount_axisp.senseinc = -1
            # --- Initial ha,dec for encoders
            self._themount_axisb.update_inc0(-17800,-90,self._themount_axisb.PIERSIDE_POS1)
            self._themount_axisp.update_inc0(2345,90,self._themount_axisp.PIERSIDE_POS1) 
            # --- first read of encoders (zero values the first time)
            incsimus = ["" for kaxis in range(Mountaxis.AXIS_MAX)] 
            self._themount.enc2cel(incsimus, save=self._themount.SAVE_ALL)        
            # --- second read of encoders (valid values)
            time.sleep(0.05)
            self._themount.enc2cel(incsimus, save=self._themount.SAVE_ALL)        
            # --- Init the simulation values according the real ones
            self._themount_axisb.synchro_real2simu()
            # --- Get the initial position
            res = self._themount.hadec_coord()
            self._themount.log.print("Initial position = {}".format(res))            
            # ======= SCX11
            self._themount.speedslew(10.0,10.0)
            self._themount.hadec_speeddrift(0,0)
            self._themount.disp()
        # =========
        if self._pad_type == None:
            return

    # ==========================================    
    # ==========================================    
    # === pad_dev
    # ==========================================    
    # ==========================================    

    def pad_cbk_stop(self):
        if self._themount!=None:
            with lock:
                self._themount.hadec_stop()

    def pad_cbk_goto(self):
        ha =self.pad_var_ha.get()
        dec = self.pad_var_dec.get()
        side_item = self._pad_combobox_side_hadec.get()
        side_index = self._side_items.index(side_item)
        if self._themount!=None:
            with lock:
                self._themount.hadec_speeddrift(0,0)
                if side_index==0:
                    theside = self._themount.axis[0].PIERSIDE_AUTO
                else:
                    if side_index==1:
                        theside = self._themount.axis[0].PIERSIDE_POS1
                    else:
                        theside = self._themount.axis[0].PIERSIDE_POS2
                #print("side_index={} theside={}".format(side_index, theside))
                self._themount.hadec_goto(ha, dec, side=theside, blocking=False)

    def pad_cbk_name2coord(self):
        with lock:
            name =self.pad_var_object_name.get()
            tools = Mounttools()
            found, ra, dec= tools.name2coord(name)
            if found==1:
                self.pad_var_radec_ra.set(ra)
                self.pad_var_radec_dec.set(dec)

    def pad_cbk_radec_goto(self):
        ra =self.pad_var_radec_ra.get()
        dec = self.pad_var_radec_dec.get()
        side_item = self._pad_combobox_side_radec.get()
        side_index = self._side_items.index(side_item)
        if self._themount!=None:
            with lock:
                self._themount.radec_speeddrift("diurnal",0)
                if side_index==0:
                    theside = self._themount.axis[0].PIERSIDE_AUTO
                else:
                    if side_index==1:
                        theside = self._themount.axis[0].PIERSIDE_POS1
                    else:
                        theside = self._themount.axis[0].PIERSIDE_POS2
                #print("side_index={} theside={}".format(side_index, theside))
                self._themount.radec_goto(ra, dec, side=theside, blocking=False)

    def pad_cbk_compute_coord(self):
        # --- do not lock this function !!!
        err = self.NO_ERROR
        try:
            if self._themount!=None:
                with lock:
                    ha, dec, side = self._themount.hadec_coord()
            else:
                ha, dec, side = (0, 0, 0)
            coord = "H.A.="+str(ha)+" Dec="+str(dec)+" "+str(side)
            self.pad_var_coord.set(coord)
            #
            if self._themount!=None:
                with lock:
                    ra2000, dec2000, side_radec = self._themount.radec_coord(EQUINOX="J2000")
            else:
                ra2000, dec2000, side_radec = (0, 0, 0)
            coord = "R.A.="+str(ra2000)+" Dec="+str(dec2000)+" "+str(side_radec)
            self.pad_var_radec_coord.set(coord)
            print("pad_cbk_compute_coord={}".format(coord))
        except:
            print("pb coord")
            ha, dec, side = (0,0,0)
            err= self.ERR_UNKNOWN
        return err, ha, dec, side

    def pad_cbk_coord_detailed(self):
        err, ha, dec, side = self.pad_cbk_compute_coord()
        if err==self.NO_ERROR:
            if self._themount!=None:
                self._themount.disp()
        
    def pad_cbk_move_n_event(self,event):
        with lock:
            if event.type==tk.EventType.ButtonPress:
                ha_drift_deg_per_sec = 0
                dec_drift_deg_per_sec = -self.pad_var_speed_drift.get()
                duration_s = 0
                if self._themount!=None:
                    self._themount.hadec_move(ha_drift_deg_per_sec, dec_drift_deg_per_sec, duration_s)
            if event.type==tk.EventType.ButtonRelease:
                if self._themount!=None:
                    self._themount.hadec_move_stop()

    def pad_cbk_move_e_event(self,event):
        with lock:
            if event.type==tk.EventType.ButtonPress:
                ha_drift_deg_per_sec = -self.pad_var_speed_drift.get()
                dec_drift_deg_per_sec = 0
                duration_s = 0
                if self._themount!=None:
                    self._themount.hadec_move(ha_drift_deg_per_sec, dec_drift_deg_per_sec, duration_s)
            if event.type==tk.EventType.ButtonRelease:
                if self._themount!=None:
                    self._themount.hadec_move_stop()
            
    def pad_cbk_move_w_event(self,event):
        with lock:
            if event.type==tk.EventType.ButtonPress:
                ha_drift_deg_per_sec = self.pad_var_speed_drift.get()
                dec_drift_deg_per_sec = 0
                duration_s = 0
                if self._themount!=None:
                    self._themount.hadec_move(ha_drift_deg_per_sec, dec_drift_deg_per_sec, duration_s)
            if event.type==tk.EventType.ButtonRelease:
                if self._themount!=None:
                    self._themount.hadec_move_stop()
            
    def pad_cbk_move_s_event(self,event):
        with lock:
            if event.type==tk.EventType.ButtonPress:
                ha_drift_deg_per_sec = 0
                dec_drift_deg_per_sec = self.pad_var_speed_drift.get()
                duration_s = 0
                if self._themount!=None:
                    self._themount.hadec_move(ha_drift_deg_per_sec, dec_drift_deg_per_sec, duration_s)
            if event.type==tk.EventType.ButtonRelease:
                if self._themount!=None:
                    self._themount.hadec_move_stop()

    def pad_cbk_park(self):
        with lock:
            if False:
                ha = 90
                dec = 90
                theside = self._themount.axis[0].PIERSIDE_POS1
                self._themount.hadec_goto(ha, dec, side=theside, blocking=False)
            else:
                self._themount.goto_park()
    
    def pad_cbk_quit(self):
        try:
            self._themount.close_chan()
        except:
            pass
        self.pad_gui_delete()

    def pad_cbk_console(self, event):
        command =self.pad_var_console.get()
        self.pad_cbk_command(command)        
        
    def pad_cbk_command(self, command): 
        res = ""
        with lock:
            try:
                exec(f"""locals()['temp'] = {command}""")
                res = locals()['temp']
                #exec(f"""globals()['temp'] = {command}""")
                #res = globals()['temp']
                #print("res={}".format(res))
            except Exception as err:
                res = err
            #print("type(res)={}".format(type(res)))
            #print("(2) res={}".format(res))
            self.text_console.insert(tk.END,command+"\n","command")
            self.text_console.yview_moveto(1.0)
            res = "# "+str(res)+"\n"
            self.text_console.insert(tk.END,res,"result")
            self.text_console.yview_moveto(1.0)
            self._command_history.append(command)
            self._command_history_index = len(self._command_history)
            command =self.pad_var_console.set("")
        return res
        
    def pad_cbk_disp_message(self, message, tag):
        with lock:
            self.text_console.insert(tk.END, message, tag)
            self.text_console.yview_moveto(1.0)
            self.tkroot.update()
    
    def pad_cbk_command_prev(self, event):
        k = self._command_history_index
        k -= 1
        if k>=0:
            self._command_history_index = k
            command = self._command_history[k]
            self.pad_var_console.set(command)
    
    def pad_cbk_command_next(self, event):
        n = len(self._command_history)
        k = self._command_history_index
        k += 1
        if k<n:
            self._command_history_index = k
            command = self._command_history[k]
            self.pad_var_console.set(command)

    def pad_cbk_compute_lst(self):
        with lock:
            if self._themount!=None:
                angle = str(self._themount.site.longitude)
            else:
                angle = str(0)
            date = celme.Date("now")
            jd = date.jd()
            dateiso = date.iso(0," ")
            longuai = celme.Angle(angle).rad()
            meca = celme.Mechanics()
            lst = meca._mc_tsl(jd,-longuai)
            ang = celme.Angle(str(lst)+"r")
            lst_hms = ang.sexagesimal("H0.0")
            self.pad_var_date.set("UTC {}".format(dateiso))
            self.pad_var_lst.set("Local Sideral Time {}".format(lst_hms))
        lock.release()
        
    def pad_gui_delete(self):
        # --- kill the threads
        try:
            self._pad_repeat.stop()
        except:
            pass
        #time.sleep(1.0)        
        try:
            self._pad_server.stop()
        except:
            pass
        #time.sleep(0.5)
        # --- quit() makes the exit of the Tk mainloop
        #self.tkroot.quit()
        # --- We can destroy the windows of the gui
        self.tkroot.destroy()

    def pad_gui_create(self):
        self.tkroot = tk.Tk()
        fontStyle_1 = tkFont.Font(family="Arial", size=14, weight="bold")
        fontStyle_2 = tkFont.Font(family="Arial", size=12, weight="bold")
        fontStyle_3 = tkFont.Font(family="Arial", size=10, weight="bold")
        
        # === Frame of Date & Local Sideral Time
        self.pad_var_date = tk.StringVar()
        self.pad_var_lst = tk.StringVar()
        frame_lst = tk.Frame(self.tkroot)
        label_date = tk.Label(frame_lst, textvariable=self.pad_var_date, font=fontStyle_2)
        label_date.pack(side = tk.TOP)
        label_lst = tk.Label(frame_lst, textvariable=self.pad_var_lst, font=fontStyle_2)
        label_lst.pack(side = tk.TOP)
        frame_lst.pack(side = tk.TOP, pady=5)

        # === Frame of HA,Dec COORD
        self.pad_var_coord=tk.StringVar()
        frame_coord = tk.Frame(self.tkroot)
        label_coord = tk.Label(frame_coord, textvariable=self.pad_var_coord, font=fontStyle_1)
        label_coord.pack(side = tk.LEFT)
        button_coord = tk.Button(frame_coord, text="DETAILS", command=self.pad_cbk_coord_detailed, font=fontStyle_3)
        button_coord.pack(side = tk.LEFT)
        frame_coord.pack(side = tk.TOP, pady=5)
        
        # === Frame of HA,Dec GOTO
        self.pad_var_ha = tk.StringVar()
        self.pad_var_dec = tk.StringVar()
        frame_goto = tk.Frame(self.tkroot)
        label_ha = tk.Label(frame_goto, text="HA", font=fontStyle_3)
        label_ha.pack(side = tk.LEFT)
        entry_ha = tk.Entry(frame_goto, textvariable=self.pad_var_ha, font=fontStyle_3)
        entry_ha.pack(side = tk.LEFT)
        label_dec = tk.Label(frame_goto, text="Dec", font=fontStyle_3)
        label_dec.pack(side = tk.LEFT)
        entry_dec = tk.Entry(frame_goto, textvariable=self.pad_var_dec, font=fontStyle_3)
        entry_dec.pack(side = tk.LEFT)
        label_side = tk.Label(frame_goto, text="Side", font=fontStyle_3)
        label_side.pack(side = tk.LEFT)
        self._pad_combobox_side_hadec = ttk.Combobox(frame_goto,values=self._side_items)
        self._pad_combobox_side_hadec.current(0)
        self._pad_combobox_side_hadec.pack(side = tk.LEFT)
        button_goto = tk.Button(frame_goto, text="GOTO", command=self.pad_cbk_goto, font=fontStyle_3)
        button_goto.pack(side = tk.LEFT)
        frame_goto.pack(side = tk.TOP, pady=5)
        self.pad_var_ha.set("Oh")
        self.pad_var_dec.set("Od")

        # === Frame of RA,Dec COORD
        self.pad_var_radec_coord=tk.StringVar()
        frame_radec_coord = tk.Frame(self.tkroot)
        label_radec_coord = tk.Label(frame_radec_coord, textvariable=self.pad_var_radec_coord, font=fontStyle_1)
        label_radec_coord.pack(side = tk.LEFT)
        frame_radec_coord.pack(side = tk.TOP, pady=5)
        self.pad_var_radec_coord.set("")

        # === Frame of name resolver
        self.pad_var_object_name = tk.StringVar()
        frame_name2coord = tk.Frame(self.tkroot)
        label_name2coord_name = tk.Label(frame_name2coord, text="Object name", font=fontStyle_3)
        label_name2coord_name.pack(side = tk.LEFT)
        entry_name2coord_name = tk.Entry(frame_name2coord, textvariable=self.pad_var_object_name, font=fontStyle_3)
        entry_name2coord_name.pack(side = tk.LEFT)
        button_name2coord_resolver = tk.Button(frame_name2coord, text="Get coordinates", command=self.pad_cbk_name2coord, font=fontStyle_3)
        button_name2coord_resolver.pack(side = tk.LEFT)
        frame_name2coord.pack(side = tk.TOP, pady=5)
        self.pad_var_object_name.set("vega")

        # === Frame of RA,Dec GOTO
        self.pad_var_radec_ra = tk.StringVar()
        self.pad_var_radec_dec = tk.StringVar()
        frame_radec_goto = tk.Frame(self.tkroot)
        label_radec_ra = tk.Label(frame_radec_goto, text="RA", font=fontStyle_3)
        label_radec_ra.pack(side = tk.LEFT)
        entry_radec_ra = tk.Entry(frame_radec_goto, textvariable=self.pad_var_radec_ra, font=fontStyle_3)
        entry_radec_ra.pack(side = tk.LEFT)
        label_radec_dec = tk.Label(frame_radec_goto, text="Dec", font=fontStyle_3)
        label_radec_dec.pack(side = tk.LEFT)
        entry_radec_dec = tk.Entry(frame_radec_goto, textvariable=self.pad_var_radec_dec, font=fontStyle_3)
        entry_radec_dec.pack(side = tk.LEFT)
        label_radec_side = tk.Label(frame_radec_goto, text="Side", font=fontStyle_3)
        label_radec_side.pack(side = tk.LEFT)
        self._pad_combobox_side_radec = ttk.Combobox(frame_radec_goto,values=self._side_items)
        self._pad_combobox_side_radec.current(0)
        self._pad_combobox_side_radec.pack(side = tk.LEFT)
        button_radec_goto = tk.Button(frame_radec_goto, text="GOTO", command=self.pad_cbk_radec_goto, font=fontStyle_3)
        button_radec_goto.pack(side = tk.LEFT)
        frame_radec_goto.pack(side = tk.TOP, pady=5)
        self.pad_var_radec_ra.set(self.pad_var_lst.get())
        self.pad_var_radec_dec.set("Od")

        # === Frame of HA,Dec MOVE
        self.pad_var_speed_drift=tk.DoubleVar()
        self.pad_var_speed_drift.set(1)
        frame_move = tk.Frame(self.tkroot)
        # Configuration of the grid manager
        self.tkroot.rowconfigure(0, weight=1)
        self.tkroot.columnconfigure(0, weight=1)
        button_N = tk.Button(frame_move, text="N", height=3, width=10, font=fontStyle_1)
        button_N.grid(row=0, column=1, sticky="nsew")
        button_N.bind('<Button-1>',self.pad_cbk_move_n_event)
        button_N.bind('<ButtonRelease>',self.pad_cbk_move_n_event)
        button_E = tk.Button(frame_move, text="E", height=3, width=10, font=fontStyle_1)
        button_E.bind('<Button-1>',self.pad_cbk_move_e_event)
        button_E.bind('<ButtonRelease>',self.pad_cbk_move_e_event)
        button_E.grid(row=1, column=0, sticky="nsew")
        entry_speed_drift = tk.Entry(frame_move, textvariable=self.pad_var_speed_drift, width=10, justify='center', font=fontStyle_1)
        entry_speed_drift.grid(row=1, column=1, sticky="nsew")
        button_W = tk.Button(frame_move, text="W", height=3, width=10, font=fontStyle_1)
        button_W.bind('<Button-1>',self.pad_cbk_move_w_event)
        button_W.bind('<ButtonRelease>',self.pad_cbk_move_w_event)
        button_W.grid(row=1, column=2, sticky="nsew")
        button_S = tk.Button(frame_move, text="S", height=3, width=10, font=fontStyle_1)
        button_S.bind('<Button-1>',self.pad_cbk_move_s_event)
        button_S.bind('<ButtonRelease>',self.pad_cbk_move_s_event)
        button_S.grid(row=2, column=1, sticky="nsew")
        frame_move.pack(side = tk.TOP, pady=5)
        
        frame_stop = tk.Frame(self.tkroot)
        button_stop = tk.Button(frame_stop, text="STOP", command=self.pad_cbk_stop, font=fontStyle_3)
        button_stop.pack(side = tk.LEFT)
        frame_stop.pack(side = tk.TOP, pady=5)
            
        frame_bottom = tk.Frame(self.tkroot)        
        button_park = tk.Button(frame_bottom, text="Park", command=self.pad_cbk_park, font=fontStyle_3)
        button_park.pack(side = tk.LEFT, padx=5, pady=5)
        button_quit = tk.Button(frame_bottom, text="Quit", command=self.pad_cbk_quit, font=fontStyle_3)
        button_quit.pack(side = tk.LEFT, padx=5, pady=5)
        frame_bottom.pack(side = tk.TOP, pady=5)

        self.pad_var_console = tk.StringVar()
        frame_console = tk.Frame(self.tkroot)        
        self.text_console = tk.Text(frame_console, height=6, wrap="word", font=fontStyle_3)
        self.text_console.pack(side = tk.TOP, padx=5, pady=1)
        self.text_console.tag_config('command', foreground="red")
        self.text_console.tag_config('result', foreground="blue")
        self.text_console.tag_config('remote', foreground="green")
        entry_console = tk.Entry(frame_console, textvariable=self.pad_var_console, font=fontStyle_3)
        entry_console.pack(side = tk.TOP, padx=5, pady=1, fill="both")
        entry_console.bind("<Return>", self.pad_cbk_console)
        entry_console.bind("<Up>", self.pad_cbk_command_prev)
        entry_console.bind("<Down>", self.pad_cbk_command_next)
        frame_console.pack(side = tk.TOP, pady=5)

        self._pad_repeat = UniversalPadRepeat(self)
        self._pad_repeat.start()
        self._pad_server = UniversalPadServer(self, "TCP", port=1111)
        self._pad_server.start()
        try:
            self.tkroot.mainloop()
        except:
            pass

    def padconfig_gui_delete(self):
        """
        Dico padconfig gives you the values chosen of the configuration
        """
        # --- 
        config = self.config
        config_keys = config.keys()
        for config_key in config_keys:
            subconfig_keys = config[config_key].keys()
            for subconfig_key in subconfig_keys:
                dico = config[config_key][subconfig_key]
                widget = dico['widget']
                wname = config_key + "_" + subconfig_key
                if widget=="select":
                    self.padconfig[wname] = self.widgets[wname].get()
                elif widget=="entry":
                    wname_var = wname + "_var"
                    self.padconfig[wname] = self.widgets[wname_var].get()
        # --- 
        self.tkconfig.destroy()
        return self.padconfig
        
    def padconfig_gui_bind(self, event):
        print("New Element Selected")
        wname = "remote" + "_" + "role"
        if self.widgets[wname].get()=="client":
            self.widgets["mount"].pack_forget()
        else:
            self.widgets["mount"].pack(side = tk.TOP, pady=5)
        
    def padconfig_gui_create(self):
        # --
        if platform.system()=="Windows":
            port = "//./com1"
        else:
            port = "/dev/ttyAMA0"
        # --
        config = {}
        # --
        subconfig = {}
        subconfig["role"] = {"widget":"select", "params":["server", "client"], "label":"Role"}
        subconfig["transport"] = {"widget":"select", "params":["serial", "TCP"], "label":"Transport"}
        subconfig["commands"] = {"widget":"select", "params":["LX200"], "label":"Commands"}
        subconfig["port"] = {"widget":"entry", "params":1111, "label":"Port"}
        subconfig["baud"] = {"widget":"select", "params":[9600,115200], "label":"Bauds"}
        config["remote"] = subconfig
        # --
        subconfig = {}
        subconfig["model"] = {"widget":"select", "params":["astromecca"], "label":"Model"}
        subconfig["mode"] = {"widget":"select", "params":["simulation", "real"], "label":"Mode"}
        subconfig["port"] = {"widget":"entry", "params":port, "label":"Port"}
        config["mount"] = subconfig
        self.config = config
        # --
        if False:
            config_keys = config.keys()
            for config_key in config_keys:
                print("======= config_key={}".format(config_key))
                subconfig_keys = config[config_key].keys()
                for subconfig_key in subconfig_keys:
                    dico = config[config_key][subconfig_key]
                    label = dico['label']
                    widget = dico['widget']
                    params = dico['params']                
                    #print("   config={} subconfig={} = {}".format(config_key, subconfig_key, config[config_key][subconfig_key]))
                    print("{}_{} widget={}".format(config_key, subconfig_key, widget))
        # --
        self.tkconfig = tk.Tk()
        fontStyle_1 = tkFont.Font(family="Arial", size=14, weight="bold")
        fontStyle_2 = tkFont.Font(family="Arial", size=12, weight="bold")
        fontStyle_3 = tkFont.Font(family="Arial", size=10, weight="bold")
        config_keys = config.keys()
        self.padconfig = {}
        self.widgets = {}
        self.widgets["title"] = tk.Label(self.tkconfig, text="Configuration", font=fontStyle_1)
        self.widgets["title"].pack(side = tk.TOP)
        for config_key in config_keys:
            #print("config_key={}".format(config_key))
            self.widgets[config_key] = tk.Frame(self.tkconfig)
            tname = config_key + "_title"
            self.widgets[tname] = tk.Label(self.widgets[config_key], text=config_key, font=fontStyle_2)
            self.widgets[tname].pack(side = tk.TOP)
            subconfig_keys = config[config_key].keys()
            for subconfig_key in subconfig_keys:
                dico = config[config_key][subconfig_key]
                wname = config_key + "_" + subconfig_key
                lname = wname + "_label"
                fname = wname + "_frame"
                label = dico['label']
                widget = dico['widget']
                params = dico['params']                
                self.widgets[fname] = tk.Frame(self.tkconfig)
                self.widgets[lname] = tk.Label(self.widgets[config_key], text=label, font=fontStyle_3)
                self.widgets[lname].pack(side = tk.LEFT)
                if widget=="select":
                    self.widgets[wname] = ttk.Combobox(self.widgets[config_key],values=params)
                    self.widgets[wname].pack(side = tk.LEFT)
                    self.widgets[wname].current(0)
                    if config_key=="remote" and subconfig_key=="role":
                        self.widgets[wname].bind("<<ComboboxSelected>>", self.padconfig_gui_bind)
                elif widget=="entry":
                    wname_var = wname + "_var"
                    self.widgets[wname_var] = tk.StringVar()
                    self.widgets[wname_var].set(params)
                    self.widgets[wname] = tk.Entry(self.widgets[config_key],textvariable=self.widgets[wname_var], font=fontStyle_3)
                    self.widgets[wname].pack(side = tk.LEFT)                    
                self.widgets[fname].pack(side = tk.TOP, pady=5)
            self.widgets[config_key].pack(side = tk.TOP, pady=5)
        self.widgets["ok"] = tk.Button(self.tkconfig, text="OK", command=self.padconfig_gui_delete, font=fontStyle_3)
        self.widgets["ok"].pack(side = tk.TOP, padx=5, pady=5)
        try:
            self.tkconfig.mainloop()
        except:
            pass

            
if __name__ == "__main__":

    example = 0
    print("Example       = {}".format(example))

    if example == 0:
        # --- decode arv
        # python universalpad.py --console --configfile <fullfilename>
        # configfile must contain
        # --
        pad = UniversalPad()
        pad.padconfig_gui_create()
        mount_model = pad.padconfig["mount_model"]
        pad.configuration(mount_model)
        try:
            pad.pad_gui_create()
            try:
                pad.pad_gui_delete()
                #print("Cas 1")
            except:
                pass
                #print("Unexpected error:", sys.exc_info()[0])
                #print("Cas 2")
        except:
            print("Unexpected error:", sys.exc_info()[0])
            
    if example == 1:

        # --- try to catch the Ctrl+C interrupt
        try:
            # --- We launch the pad
            pad = UniversalPad()
            pad.configuration("astromecca")
            pad.pad_gui_create()
            try:
                pad.pad_gui_delete()
                #print("Cas 1")
            except:
                pass
                #print("Unexpected error:", sys.exc_info()[0])
                #print("Cas 2")
        except:
            print("Unexpected error:", sys.exc_info()[0])