Ticket #13620: tutorial.py

File tutorial.py, 7.7 KB (added by rcrdnalor, 2 months ago)

Simple tutorial showing the usage

Line 
1# -*- coding: utf-8 -*-
2
3# For logging use
4# python3 tutorial.py --nodblog --loglevel debug --verbose all --logfile /tmp/my_logfile
5
6
7from MythTV import MythTVService
8from MythTV import datetime
9from datetime import timedelta
10
11import logging                         # optional the services-api transfers
12import os
13from pprint import pprint
14from lxml   import etree
15
16
17if __name__ == "__main__":
18
19    host=("127.0.0.1")             # backend
20    hostname = os.uname()[1]       # backend's hostname
21   
22    ## enable logging for debug messages of the services-api transfers:
23    #logging.basicConfig(level=logging.DEBUG)
24    #logging.getLogger('requests.packages.urllib3').setLevel(logging.WARNING)
25    #logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING)   
26   
27    # Use cases:
28   
29    if 1:
30        """
31        Use case: toggle 'DVBEITScan' value for the first capture card.
32        Note: 'DVBEITScan' is a boolean
33        """
34        # Initialize the service:
35        service = 'Capture'
36        s = MythTVService(service, host)
37
38        print("Available operations: %s" %(s.list_operations()))
39        ## Available operations: ['AddCaptureCard', 'AddCardInput', 'GetCaptureCard',....]
40        ## 'GetCaptureCardList', 'RemoveCaptureCard', 'RemoveCardInput', 'UpdateCaptureCard',
41        ## 'UpdateCardInput']
42       
43        # The long way: make every step in a chain sequentially:
44        operation = 'GetCaptureCardList'
45        defop = s.get_operation(operation)
46        print(defop)
47        ## {'opname': 'GetCaptureCardList', 'optype': 'GET', 'opdata': {'HostName': '', 'CardType': ''}}
48       
49        defop['opdata']['HostName'] = hostname
50        defop_stripped = s.strip_operation_defaults(operation, defop)
51        print(defop_stripped)
52        ## {'opname': 'GetCaptureCardList', 'optype': 'GET', 'opdata': {'HostName': 'localhost'}}
53       
54        # Note: no need to translate opdata dictionary from python types to strings
55       
56        if s.perform_operation(defop_stripped):
57            # 's' is now like an object of type 'CaptureCardList':       
58            DVBEITScan_s1 = s.capturecards[0].dvbeitscan
59            print("DVBEITScan_s1 : %s" %DVBEITScan_s1)
60            ## DVBEITScan_s1 : True
61       
62       
63        # now update the 'DVBEITScan' value:
64        operation = 'UpdateCaptureCard'
65        defop = s.get_operation(operation)
66        print(defop)
67        ## {'opname': 'UpdateCaptureCard', 'optype': 'POST',
68        ##  'opdata': {'CardId': 0, 'Setting': '', 'Value': ''}}
69       
70        # Fill in the correct values:
71        defop['opdata']['CardId'] = 1
72        defop['opdata']['Setting'] = 'dvb_eitscan'
73        defop['opdata']['Value'] = not DVBEITScan_s1
74
75        # Translate 'POST' operations before sending:
76        encop = s.encode_operation(defop)
77        print(defop)
78        ## {'opname': 'UpdateCaptureCard', 'optype': 'POST',
79        ##  'opdata': {'CardId': '1', 'Setting': 'dvb_eitscan', 'Value': '0'}}
80           
81        res = s.perform_operation(encop)
82        print("POST operation returned '%s'" %res)
83        ## POST operation returned 'True'
84       
85       
86        # Check the setting by using the fast way:
87        opdata = { 'HostName' : hostname }
88
89        sq = MythTVService(service, host, opname='GetCaptureCardList', optype="GET", **opdata)
90        # 'sq' is now like an object of type 'CaptureCardList':
91        #pprint(sq.capturecards)
92        assert DVBEITScan_s1 is not sq.capturecards[0].dvbeitscan, "Quick way and long way results are not equal!"
93       
94       
95    if 1:
96        """
97        Use case: get the program list for the next day with a defined pagesize.
98        Note: page size is defined by the number of entries
99        """
100        service = 'Guide'
101        operation = 'GetProgramList'
102
103        s = MythTVService(service, host)
104       
105        # get the default operations's dictionary:
106        def_optdict = s.get_operation(operation)
107        print(def_optdict)
108        ## {'opname': 'GetProgramList', 'optype': 'GET',
109        ## 'opdata': {'StartIndex': 0, 'Count': 0, 'StartTime': datetime(1900, 1, 1, 0, 0, tzinfo=<....>),
110        ##            'EndTime': datetime(1900, 1, 1, 0, 0, tzinfo=<.....>), 'ChanId': 0, 'TitleFilter': '',
111        ##            'CategoryFilter': '', 'PersonFilter': '', 'KeywordFilter': '', 'OnlyNew': '0',
112        ##            'Details': '0', 'Sort': '', 'Descending': '0', 'WithInvisible': '0'}}
113
114        starttime = datetime.now()
115        endtime   = starttime + timedelta(days=1, hours=1)
116        # convert to mythtv's 'datetime' class:
117        endtime   = datetime.duck(endtime)
118       
119        # define the operation's dict based on the default operation's dictionary
120        opdict = {}
121        opdict['opname'] = operation
122        opdict['optype'] = 'GET'
123        opdict['opdata'] =  {}
124        opdict['opdata']['StartIndex'] = 0
125        opdict['opdata']['Count'] = 200              # this defines the page size
126        opdict['opdata']['StartTime'] = starttime
127        opdict['opdata']['EndTime'] = endtime
128        opdict['opdata']['Details'] = True
129
130        # get_pages returns an iterator
131        progs = s.get_pages(opdict, 'Programs')
132        while True:
133            try:
134                ps = next(progs)
135                for p in ps:
136                    print(p.title)
137            except StopIteration:
138                break     
139               
140        # One will get something like this:
141        ## How I Met Your Mother
142        ## Young Sheldon       
143        ## .....
144
145       
146    if 1: 
147        """
148        Use Case: Get a 'program' like object of a recorded entry.
149        Evaluate the recstatus of the recorded entry.
150        """
151       
152        service = 'Dvr'                 # uses enumeration RecStatus.Type
153        operation = 'GetRecorded'       # GET  # returns a 'Program'
154
155        s = MythTVService(service, host)
156
157        opdict = {}
158        opdict['opname'] = operation
159        opdict['optype'] = 'GET'
160        opdict['opdata'] =  {}
161        opdict['opdata']['RecordedId'] = 16
162
163        result = s.perform_operation(opdict)
164        print(result)          # True
165       
166        # Get the version of this operation:
167        print("Operation Version : %s" %s.operation_version)             #  1.11
168
169        print(s._field_order)      # this prints all availabble properties ['StartTime', 'EndTime', 'Title', ....}
170        print(s.title)             # 'ZaB Night'
171        print(s.starttime)         # 2020-02-21 22:54:13+01:00    # local time plus offset to UTC
172        print(s.channel.chanid)    # 10101
173        print(s.videoprops)        # 46  0x2E   # defined as "xs:int" in the xsd
174        print(s.audioprops)        # 0          # defined as "xs:int" in the xsd
175        print(s.programflags)      # 72         # defined as "xs:int" in the xsd
176        print(s.recording)         # class of type "RecordingInfo"
177        print(s.recording.status)  # 'Recorded'
178       
179        # get the definition of the 'RecStatus':
180        print(s.schema_dict["RecStatus.Type"])       # {'Pending': -15, 'Failing': -14, 'MissedFuture': -11,....}
181        print(s.schema_dict["RecStatus.Type"][s.recording.status])        # -3
182               
183               
184    if 0:
185        """
186        Use Case: Display the wsdl file, the schema (xsd) and the corresponding
187        schema dictionary of a service.
188        Note: This creates a huge amount of data.
189        """
190       
191        service = 'Dvr'
192        s = MythTVService(service, host)
193       
194        print(etree.tostring(s.wsdl, pretty_print=True, encoding='unicode'))
195        print(s.list_schema())
196        pprint(s.schema_dict)
197