1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4Copyright (c) 2024 Huawei Device Co., Ltd.
5Licensed under the Apache License, Version 2.0 (the "License");
6you may not use this file except in compliance with the License.
7You may obtain a copy of the License at
8
9    http://www.apache.org/licenses/LICENSE-2.0
10
11Unless required by applicable law or agreed to in writing, software
12distributed under the License is distributed on an "AS IS" BASIS,
13WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14See the License for the specific language governing permissions and
15limitations under the License.
16
17Description: Action words of hdc fport.
18"""
19
20import logging
21import subprocess
22
23
24class Fport(object):
25    retry_times = 3
26    increase_step = 7
27
28    @classmethod
29    def fport_connect_server(cls, port, pid, bundle_name):
30        for _ in range(Fport.retry_times):
31            cmd = ['hdc', 'fport', f'tcp:{port}', f'ark:{pid}@{bundle_name}']
32            logging.info('fport connect server: ' + ' '.join(cmd))
33            result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
34            logging.info(result.stdout.strip())
35            if 'TCP Port listen failed' not in result.stdout.decode('utf-8'):
36                assert result.stdout.decode('utf-8').strip() == 'Forwardport result:OK'
37                return port
38            else:    # The port is occupied
39                port += Fport.increase_step
40        return -1
41
42    @classmethod
43    def fport_debugger_server(cls, port, pid, tid=0):
44        for _ in range(Fport.retry_times):
45            if tid == 0:
46                cmd = ['hdc', 'fport', f'tcp:{port}', f'ark:{pid}@Debugger']
47            else:
48                cmd = ['hdc', 'fport', f'tcp:{port}', f'ark:{pid}@{tid}@Debugger']
49            logging.info('fport_debugger_server: ' + ' '.join(cmd))
50            result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
51            logging.info(result.stdout.strip())
52            if 'TCP Port listen failed' not in result.stdout.decode('utf-8'):
53                assert result.stdout.decode('utf-8').strip() == 'Forwardport result:OK'
54                return port
55            else:    # The port is occupied
56                port += Fport.increase_step
57        return -1
58
59    @classmethod
60    def clear_fport(cls):
61        list_fport_cmd = ['hdc', 'fport', 'ls']
62        list_fport_result = subprocess.run(list_fport_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
63        logging.info(list_fport_result.stdout.strip())
64        list_fport_out = list_fport_result.stdout.decode('utf-8')
65        if 'Empty' in list_fport_out:
66            return
67        for fport_item in [item for item in list_fport_out.split('[Forward]') if item != '\r\n']:
68            un_fport_command = (['hdc', 'fport', 'rm'] + [fport_item.split('    ')[1].split(' ')[0]] +
69                                [fport_item.split('    ')[1].split(' ')[1]])
70            un_fport_result = subprocess.run(un_fport_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
71            logging.info(un_fport_result.stdout.strip())
72            assert 'success' in un_fport_result.stdout.decode('utf-8')
73