mountchannel.py 24.1 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
# -*- coding: utf-8 -*-
import time
import serial
import socket
import serial.tools.list_ports
import traceback
import sys

#import RPi.GPIO as io

# #####################################################################
# #####################################################################
# #####################################################################
# Class Mountchannel for communication clients
# #####################################################################
# #####################################################################
# #####################################################################

class Mountchannel():
    
    # === Constant for error codes
    NO_ERROR = 0
    
    ERR_FILE_NOT_EXISTS = 101
    
    ERR_CHAN_OPEN = 201
    ERR_CHAN_UNKNOWN = 202
    ERR_CHAN_PORT_NOT_FOUND = 203
    ERR_CHAN_CLOSE = 204
    ERR_CHAN_NOT_OPENED = 205
    ERR_CHAN_PORT_NOT_DEFINED = 206
    ERR_CHAN_EVER_OPENED = 207
    ERR_CHAN_HOSTNAME_NOT_DEFINED = 208
    ERR_CHAN_TCP_RECV_TIMEOUT = 209

    # --- main communication
    _fid_chan   = None
    _port_chan  = None
    _delay_put_read = 0.05 ; # seconds between put-get communication
    _delay_init_chan = 1.5 ; # seconds to wait after open communication
    _end_of_message = ""    
    _verbose_chan = False

    # =====================================================================
    # methods
    # =====================================================================

    def _set_last_error_msg(self):
        self._error_msg = sys.exc_info()[1]
        #traceback.print_exc(file=sys.stdout)

    def get_last_error_msg(self):
        return self._error_msg
        
    def set_channel_params(self, *args, **kwargs): 
        #argc = len(args)
        #kwargc = len(kwargs)
        #print("3.*args={} argc={}".format(args,argc))
        #print("3.**kwargs={} kwargc={}".format(kwargs,kwargc))        
        # --- Dico of optional parameters for all axis_types
        param_optionals = {}
        param_optionals["END_OF_COMMAND_TO_SEND"] = (str, "")
        param_optionals["END_OF_COMMAND_TO_RECEIVE"] = (str, "")
        param_optionals["DELAY_INIT_CHAN"] = (float, 0.0)
        param_optionals["END_OF_MESSAGE"] = (str, "")
        param_optionals["DELAY_PUT_READ"] = (float, 0.05)
        # --- Dico of axis_types and their parameters
        channel_types = {}
        channel_types["SERIAL"]= {"MANDATORY" : {"PORT":[str,"//./COM1"]}, "OPTIONAL" : {"BAUD_RATE":[int,9600]} }
        channel_types["TCP"]= {"MANDATORY" : {"PORT":[int,"5000"], "HOSTNAME":[str,"127.0.0.1"]}, "OPTIONAL" : {} }
        # --- 
        argc = len(args)
        # kwargc = len(kwargs)
        # ========= valid *args
        valid = 1
        if (argc==0):
            valid = 0
            msg = "No channel type specified ({})".format(channel_types.keys())
        else:
            # --- Identify the selected type
            selected_channel_type = args[0].upper()
            if selected_channel_type in channel_types:
                parameters = channel_types[selected_channel_type]
            else:
                valid = 0
                msg = "{} not found amongst channel types ({})".format(selected_channel_type,channel_types.keys())
        if valid==0:
            raise Exception(msg)
        # ========= valid **kwargs
        valid = 0
        # ====== change keys into upper strings
        dics = dict()
        for k,v in kwargs.items():
            ku = str(k).upper()
            if (type(v) is str):
                v = v.strip()
            dic = { ku : v }
            dics.update(dic)
        selected_parameters = dics
        #print("dics={}".format(dics))
        # ====== decode **kwargs
        valid = 0
        self._channel_params = {}
        # --- input values of mandatory parameters
        params = parameters["MANDATORY"]
        for param_key in params:
            if param_key in selected_parameters:
                raw_value = selected_parameters[param_key]
                type_conv = params[param_key][0]
                if type_conv==float:
                    value = float(raw_value)
                elif type_conv==int:
                    value = int(raw_value)
                else:
                    value = raw_value
                self._channel_params[param_key] = value
            else:
                msg = "{} not found amongst mandatory parameters ({})".format(param_key,params.keys())
                raise Exception(msg)
        # --- input or default values of optional parameters
        params = param_optionals
        for parameter_key in parameters["OPTIONAL"]:
            params[parameter_key] = parameters["OPTIONAL"][parameter_key]            
        for param_key in params:
            if param_key in selected_parameters:
                raw_value = selected_parameters[param_key]
                type_conv = params[param_key][0]
            else:
                raw_value = params[param_key][1]
                type_conv = params[param_key][0]
            if type_conv==float:
                value = float(raw_value)
            elif type_conv==int:
                value = int(raw_value)
            else:
                value = raw_value
            self._channel_params[param_key] = value
        # ===
        self._channel_type = selected_channel_type
        self._end_of_command_to_send    = self._channel_params["END_OF_COMMAND_TO_SEND"]
        if type(self._end_of_command_to_send)==bytes:
            self._end_of_command_to_send = self._end_of_command_to_send.decode()
        self._end_of_command_to_receive = self._channel_params["END_OF_COMMAND_TO_RECEIVE"]
        if type(self._end_of_command_to_receive)==bytes:
            self._end_of_command_to_receive = self._end_of_command_to_receive.decode()
        self._delay_init_chan           = self._channel_params["DELAY_INIT_CHAN"]
        self._delay_put_read            = self._channel_params["DELAY_PUT_READ"]
        if self._channel_type=="SERIAL":
            self._port_chan = self._channel_params["PORT"]
            self._baud_rate = self._channel_params["BAUD_RATE"]
        if self._channel_type=="TCP":
            self._port_chan = self._channel_params["PORT"]
            self._hostname_chan = self._channel_params["HOSTNAME"]
            
    def _set_port_chan(self, port:str):
        self._port_chan = port
        return self._port_chan

    def _get_port_chan(self):
        return self._port_chan

    def _set_hostname_chan(self, hostname:str):
        self._hostname_chan = hostname
        return self._hostname_chan

    def _get_hostname_chan(self):
        return self._hostname_chan

    def _my_open_chan(self):
        # --- abstract method 
        # --- Please overload it according your language protocol
        return self.NO_ERROR

    def open_chan(self):
        err = self.NO_ERROR
        if self._channel_type=="SERIAL":
            fid = self._fid_chan
            port  = self._port_chan
            if self._port_chan == None:
                err = self.ERR_CHAN_PORT_NOT_DEFINED
                return (err, fid)
            if self._fid_chan != None:
                return (err, fid)
            # --- pass here only if the port was closed
            try:
               fid = serial.Serial(
                  port=port,
                  baudrate = self._baud_rate,
                  parity = serial.PARITY_NONE,
                  stopbits = serial.STOPBITS_ONE,
                  bytesize = serial.EIGHTBITS,
                  timeout = 0
               )
               if fid.isOpen():
                  err = self.NO_ERROR              
               else:
                  err = self.ERR_CHAN_OPEN
            except:
                self._set_last_error_msg()
                err = self.ERR_CHAN_UNKNOWN
            # --- some inits
            if err == self.NO_ERROR:
                self._fid_chan = fid
                time.sleep(self._delay_init_chan)
                fid.flush()
        elif self._channel_type=="TCP":
            fid = self._fid_chan
            port  = self._port_chan
            if self._port_chan == None:
                err = self.ERR_CHAN_PORT_NOT_DEFINED
                return (err, fid)
            hostname  = self._hostname_chan
            if self._hostname_chan == None:
                err = self.ERR_CHAN_HOSTNAME_NOT_DEFINED
                return (err, fid)
            if self._fid_chan != None:
                return (err, fid)
            # --- pass here only if the port was closed
            try:
                fid = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                fid.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                # Connect to server and send data
                fid.connect((hostname, port))
                fid.settimeout(1)
                print("mountchannel: CLIENT Channel fid = {}".format(fid))                
            except:
                self._set_last_error_msg()
                err = self.ERR_CHAN_UNKNOWN
            # --- some inits
            if err == self.NO_ERROR:
                self._fid_chan = fid
        err = self._my_open_chan()
        return err, fid       

    def _my_close_chan(self):
        # --- abstract method 
        # --- Please overload it according your language protocol
        return self.NO_ERROR
    
    def close_chan(self):
        err = self.NO_ERROR
        fid = self._fid_chan
        if self._fid_chan == None:
            return (err, fid)
        try:
            err = self._my_close_chan()
            fid.close()
            self._fid_chan = None
        except:
            self._set_last_error_msg()
            err = self.ERR_CHAN_CLOSE
        return (err, fid)        

    def check_chan(self):
        err = self.NO_ERROR
        fid = self._fid_chan
        if fid == None:
            err, fid = self.open_chan()
            if fid == None or err != self.NO_ERROR:
                err = self.ERR_CHAN_NOT_OPENED
        return (err, fid)

    def put_chan(self, cmd):
        # --- check the opening of the serial port
        #print("PUT {} = {}".format(self._port_chan,cmd))
        err, fid = self.check_chan()
        #print("err={} fid={}".format(err,fid))
        if err != self.NO_ERROR:
            raise Exception("Error {}".format(err))
        if self._channel_type=="SERIAL":
            # --- serial port buffer reset for the next read
            fid.reset_input_buffer() 
            # --- serial port is ready to put message
            cmd = cmd + self._end_of_command_to_send
            fid.write(cmd.encode())
            fid.flush()
        elif self._channel_type=="TCP":
            cmd = cmd + self._end_of_command_to_send
            fid.sendall(cmd.encode())
        return (err, cmd)
        
    def _read_chan_old(self):
        # --- check the opening of the serial port
        err, fid = self.check_chan()
        if err != self.NO_ERROR:
            raise Exception("Error {}".format(err))        
        # --- serial port is ready to put message
        lignes = fid.readlines()
        # --- format la sortie
        res = []
        for ligne in lignes:    
            if self._end_of_command_to_receive!="":
                re = ligne.decode('utf8').split(self._end_of_command_to_receive)[0]
            else:
                re = ligne.decode('utf8')
            res.append(re)
        return (err, res)

    def read_chan(self):
        # --- check the opening of the serial port
        err, fid = self.check_chan()
        if err != self.NO_ERROR:
            raise Exception("Error {}".format(err))        
        lignes = "" ; # fid.readlines()
        t0 = time.time()
        dt = 0
        nn = 0
        if self._channel_type=="SERIAL":
            while True:
                n = 0
                for car in fid.read():
                    n += 1
                    car = chr(car)
                    lignes += car
                    nn = 0
                    t0 = time.time()
                    #print("car={} n={} nn={}".format(car,n,nn))
                if n==0:
                    nn += 1
                    if nn==2:
                        #print("n={} nn={} Time out".format(n,nn))
                        break
                    time.sleep(0.01)
                dt = time.time()-t0
                if dt>10.0:
                    break
        elif self._channel_type=="TCP":
            try:
                lignes = fid.recv(1024)
            except:
                err = self.ERR_CHAN_TCP_RECV_TIMEOUT
        #print("dt={} lignes={} type={}".format(dt,lignes,type(lignes)))
        # --- format la sortie
        if type(lignes)==bytes:
            # --- TCP case
            lignes = lignes.decode("utf-8")
        if self._end_of_command_to_receive!="":
            res = lignes.split(self._end_of_command_to_receive)
        else:
            res = lignes
        #print("READ {} = {}".format(self._port_chan,res))
        return (err, res)
        
    def _set_delay_chan(self, delay_s:float):
        if delay_s<=0:
            raise Exception("delay must be strictly positive")
        self._delay_chan = delay_s
        return self.NO_ERROR

    def _get_delay_chan(self):
        return self._delay_chan

    def _set_delay_init_chan(self, delay_s:float):
        if delay_s<=0:
            raise Exception("delay must be strictly positive")
        self._delay_init_chan = delay_s
        return self.NO_ERROR

    def _get_delay_init_chan(self):
        return self._delay_init_chan

    def _set_verbose_chan(self, verbose:bool):
        if type(verbose) is not bool:
            raise Exception("verbose must be boolean")
        self._verbose_chan = verbose
        return self.NO_ERROR

    def _get_verbose_chan(self):
        return self._verbose_chan

# =====================================================================
# =====================================================================
# Methods for users
# =====================================================================
# =====================================================================
    
    port_chan        = property(_get_port_chan,        _set_port_chan)
    delay_chan       = property(_get_delay_chan,       _set_delay_chan)
    delay_init_chan  = property(_get_delay_init_chan,  _set_delay_init_chan)
    verbose_chan     = property(_get_verbose_chan,     _set_verbose_chan)
    
    def putread_chan(self, cmd, index=-1):
        if self.verbose_chan==True:
            self.log.print("Putread: "+cmd)
        self.put_chan(cmd)
        time.sleep(self._delay_put_read)
        err, res = self.read_chan()
        if err != self.NO_ERROR:
            return (err, res)
        if index>=0:
            n = len(res)
            if index>n-1:
                index = n-1
            return (err, res[index])
        return (err, res)

# =====================================================================
# =====================================================================
# Special methods
# =====================================================================
# =====================================================================
        
    def __init__(self, *args, **kwargs): 
        """
        Communication channel manager
        Usage : Mountchannel("SERIAL", port="//./COM1")
        """
        self._error_msg = ""
        self.set_channel_params(*args, **kwargs)
        self.verbose_chan = False

    def __del__(self):
        """
        fggf
        """
        self.close_chan()
        
        
# #####################################################################
# #####################################################################
# #####################################################################
# Main
# #####################################################################
# #####################################################################
# #####################################################################

if __name__ == "__main__":

    example = 3
    print("Example       = {}".format(example))
    
    # === Available COM ports
    def get_available_serial_ports():
        """
        Just a tool for examples.
        Return a list of available serial ports of the local computer
        """
        # --
        prefix_myserial_ports = ""
        if sys.platform.startswith('win'):
            prefix_myserial_ports = "//./"
        elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
            prefix_myserial_ports = "/dev/tty"
        elif sys.platform.startswith('darwin'):
            prefix_myserial_ports = "/dev/tty."
        # --
        serial_ports = serial.tools.list_ports.comports(include_links=False)
        # --
        available_serial_ports = []
        for serial_port in serial_ports:
            available_serial_port = prefix_myserial_ports + serial_port.device 
            available_serial_ports.append(available_serial_port)
        return available_serial_ports    
    available_serial_ports = get_available_serial_ports()
    print("Available com ports:")
    k = 0
    for available_serial_port in available_serial_ports:
        print("Available com port [{}]: {}".format(k,available_serial_port))
        k+=1
    # ============================
    
    if example == 1:
        """
        Test opening a serial Channel
        """
        #port_serial='//./com8'
        port_serial=available_serial_ports[0]
        # --
        print("Open com port {}".format(port_serial))
        chan = Mountchannel("SERIAL", port=port_serial, baud_rate=115200, delay_init_chan=0.1, end_of_command_to_send="#".encode('utf8'), end_of_command_to_receive="#".encode('utf8'), delay_put_read=0.06)
        # --
        command = "READ_RA"
        err, res = chan.putread_chan(command,0)
        if err == chan.NO_ERROR:
            print("Command {}".format(command))
            print("Response {}".format(res))
            print(res)
        else:
            print("Error code={}. {}".format(err,res))
        # --
        print("Close com port {}".format(port_serial))
        chan.close_chan()

    if example == 2:
        """
        Test opening a TCP Channel
        """
        port = 80
        hostname = "https://www.google.com"
        # --        
        print("Define a TCP channel on port {} of host {}".format(port, hostname))
        chan = Mountchannel("TCP", port=port, hostname=hostname, delay_init_chan=0.1, end_of_command_to_send="".encode('utf8'), end_of_command_to_receive="".encode('utf8'), delay_put_read=0.2)
        # --
        print("Open the TCP channel")
        err, fid = chan.open_chan()
        if err != chan.NO_ERROR:
            print("Error code={}. {}".format(err,res))
        # --
        print("close the TCP channel")
        chan.close_chan()

    if example == 3:
        """
        Sniffer of COM Channel
        """
        # --- COM port sniffer 
        # 'Device' is the hardware with a specific protocol langage
        # 'Client' is the software as ASCOM or any other pilot
        # 'Sniffer' is the current software placed between 'Client' and 'Device'
        # --- CASE Direct link:
        # 'Client'<port_client> --linked to-- 'Device'       
        # --- CASE Sniffer link:
        # 'Client'<port_client> --linked to-- <port_sniffer_client>'Sniffer'<port_sniffer_device> -- linked to -- 'Device'       
        # the PC need three COM port COM is 'Client' is installed in the same PC than the 'Sniffer'
        # ------------------------------
        import os
        # --- Name of the file where the sniffer store the messages
        cwd = os.getcwd()
        fichier = cwd + "/sniffer.txt"
        print("Sniffer file is {}".format(fichier))
        # --- Attribution of the serial ports
        np = len(available_serial_ports)
        if np<2:
            print("You need at less 2 COM ports to snif !")
        else:
            # --- change here the order of the available list
            port_sniffer_client = available_serial_ports[1]
            port_sniffer_device = available_serial_ports[0]
            print("'Client'<port_client> ---- <{}>'Sniffer'<{}> ---- 'Device'".format(port_sniffer_client,port_sniffer_device))
        # --- Close the concerned serial ports
        if 'chan_sniffer_device' in globals():
            del(chan_sniffer_device)
        if 'chan_sniffer_client' in globals():
            del(chan_sniffer_client)
        # --- set the baud rate (bits/s)
        baud_rate = 115200
        # --- Open the concerned serial ports
        chan_sniffer_device = Mountchannel("SERIAL", port=port_sniffer_device, baud_rate=baud_rate, delay_init_chan=0.01, end_of_command_to_send="".encode('utf8'), end_of_command_to_receive="".encode('utf8'), delay_put_read=0.01)
        chan_sniffer_device.verbose_chan = False
        chan_sniffer_client = Mountchannel("SERIAL", port=port_sniffer_client, baud_rate=baud_rate, delay_init_chan=0.01, end_of_command_to_send="".encode('utf8'), end_of_command_to_receive="".encode('utf8'), delay_put_read=0.01)
        chan_sniffer_client.verbose_chan = False
        # --- Infinite loop of the sniffing
        t0 = time.time()
        tendseries = 1e10
        buffer = ""
        try:
            while True:
                lignes = ""
                try:
                    # --- read the 'Client' commands
                    err, lignes = chan_sniffer_client.read_chan()
                except:
                    pass
                # --- Test if a command  was received from the 'Client'
                if err==chan_sniffer_client.NO_ERROR and lignes != "":
                    t = time.time()
                    dt = t-t0
                    # --- put the 'Client' commands to the channel of the 'Device'
                    chan_sniffer_device.put_chan(lignes)
                    # --- Wait for the device response
                    time.sleep(0.03)
                    # --- read the 'Device' response
                    # --- get the EQMOD answer
                    err, msg = chan_sniffer_device.read_chan()
                    # --- Isolate the good answer
                    #msg = str(msg[0])
                    # --- put the 'Device' answer to the channel of the 'Client'
                    chan_sniffer_client.put_chan(msg)
                    # --- format the result
                    result = "{:.2f} {} ==> {}".format(dt,lignes,msg)
                    buffer += result + "\n"
                    display = 1
                    if display==1:
                        print(result)
                        tendseries = t
                    dtendseries = t-tendseries
                    if dtendseries>=0:
                        # --- save buffer
                        with open(fichier, 'a') as fid:
                            fid.write(buffer)
                            buffer = ""
                        tendseries = t
                        print("="*15)
                    # ---
                time.sleep(0.1)
        except:
            traceback.print_exc(file=sys.stdout)
            print("Close com port {}".format(port_sniffer_device))
            del(chan_sniffer_device)
            print("Close com port {}".format(port_sniffer_client))
            del(chan_sniffer_client)

    if example == 4:
        """
        Send a Json to device
        """
        # ------------------------------
        # --- Attribution of the serial ports

        port_sniffer_device = available_serial_ports[2]
        print("'Clien'<{}> ---- 'Device'".format(port_sniffer_client,port_sniffer_device))
        # --- Close the concerned serial ports
        if 'chan_sniffer_device' in globals():
            del(chan_sniffer_device)
        # --- set the baud rate (bits/s)
        baud_rate = 115200
        # --- Open the concerned serial ports
        chan_sniffer_device = Mountchannel("SERIAL", port=port_sniffer_device, baud_rate=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.1)
        chan_sniffer_device.verbose_chan = False
        time.sleep(2)
        
        # --- Send some commands
        # --- put the 'Client' commands to the channel of the 'Device'
        lignes = '{"req":{"get": ""}}'
        chan_sniffer_device.put_chan(lignes)
        # --- Wait for the device response
        time.sleep(0.3)
        # --- read the 'Device' response
        # --- get the EQMOD answer
        err, msg = chan_sniffer_device.read_chan()
        # --- format the result
        result = "{:3.0f} {} ==> {}".format(dt,lignes,msg)
        print(result)
        time.sleep(1)
        # ----