c324c5fc50d2cdb38d7cfe6f0cadce05c88c66a9
[plcapi.git] / PLC / Methods / AddPCUProtocolType.py
1 # $Id$
2 # $URL$
3 from PLC.Faults import *
4 from PLC.Method import Method
5 from PLC.Parameter import Parameter, Mixed
6 from PLC.PCUProtocolTypes import PCUProtocolType, PCUProtocolTypes
7 from PLC.PCUTypes import PCUType, PCUTypes
8 from PLC.Auth import Auth
9
10 can_update = lambda (field, value): field in \
11              ['pcu_type_id', 'port', 'protocol', 'supported']
12
13 class AddPCUProtocolType(Method):
14     """
15     Adds a new pcu protocol type.
16
17     Returns the new pcu_protocol_type_id (> 0) if successful, faults otherwise.
18     """
19
20     roles = ['admin']
21
22     protocol_type_fields = dict(filter(can_update, PCUProtocolType.fields.items()))
23
24     accepts = [
25         Auth(),
26         Mixed(PCUType.fields['pcu_type_id'],
27               PCUType.fields['model']),
28         protocol_type_fields
29         ]
30
31     returns = Parameter(int, 'New pcu_protocol_type_id (> 0) if successful')
32
33     def call(self, auth, pcu_type_id_or_model, protocol_type_fields):
34
35         # Check if pcu type exists
36         pcu_types = PCUTypes(self.api, [pcu_type_id_or_model])
37         if not pcu_types:
38             raise PLCInvalidArgument, "No such pcu type"
39         pcu_type = pcu_types[0]
40
41
42         # Check if this port is already used
43         if 'port' not in protocol_type_fields:
44             raise PLCInvalidArgument, "Must specify a port"
45         else:
46             protocol_types = PCUProtocolTypes(self.api, {'pcu_type_id': pcu_type['pcu_type_id']})
47             for protocol_type in protocol_types:
48                 if protocol_type['port'] == protocol_type_fields['port']:
49                     raise PLCInvalidArgument, "Port alreay in use"
50
51         protocol_type_fields = dict(filter(can_update, protocol_type_fields.items()))
52         protocol_type = PCUProtocolType(self.api, protocol_type_fields)
53         protocol_type['pcu_type_id'] = pcu_type['pcu_type_id']
54         protocol_type.sync()
55         self.event_object = {'PCUProtocolType': [protocol_type['pcu_protocol_type_id']]}
56
57         return protocol_type['pcu_protocol_type_id']