1#!/usr/bin/python -u
2
3import gobject
4import dbus
5import dbus.service
6import dbus.mainloop.glib
7import os
8import obmc.dbuslib.propertycacher as PropertyCacher
9from obmc.dbuslib.bindings import DbusProperties, DbusObjectManager, get_dbus
10import obmc.enums
11import obmc_system_config as System
12import obmc.mapper.utils
13
14DBUS_NAME = 'org.openbmc.managers.System'
15OBJ_NAME = '/org/openbmc/managers/System'
16INTF_SENSOR = 'org.openbmc.SensorValue'
17INTF_ITEM = 'org.openbmc.InventoryItem'
18
19
20class SystemManager(DbusProperties, DbusObjectManager):
21    def __init__(self, bus, obj_name):
22        DbusProperties.__init__(self)
23        DbusObjectManager.__init__(self)
24        dbus.service.Object.__init__(self, bus, obj_name)
25        self.bus = bus
26
27        bus.add_signal_receiver(
28            self.NewObjectHandler,
29            signal_name="InterfacesAdded", sender_keyword='bus_name')
30        bus.add_signal_receiver(
31            self.SystemStateHandler, signal_name="GotoSystemState")
32
33        self.Set(DBUS_NAME, "current_state", "")
34
35        ## replace symbolic path in ID_LOOKUP
36        for category in System.ID_LOOKUP:
37            for key in System.ID_LOOKUP[category]:
38                val = System.ID_LOOKUP[category][key]
39                new_val = val.replace(
40                    "<inventory_root>", System.INVENTORY_ROOT)
41                System.ID_LOOKUP[category][key] = new_val
42
43        self.SystemStateHandler(System.SYSTEM_STATES[0])
44
45        print "SystemManager Init Done"
46
47    def SystemStateHandler(self, state_name):
48        print "Running System State: "+state_name
49
50        self.Set(DBUS_NAME, "current_state", state_name)
51
52        waitlist = System.EXIT_STATE_DEPEND.get(state_name, {}).keys()
53        if waitlist:
54            self.waiter = obmc.mapper.utils.Wait(
55                self.bus, waitlist,
56                callback=self.gotoNextState)
57
58    def gotoNextState(self):
59        s = 0
60        current_state = self.Get(DBUS_NAME, "current_state")
61        for i in range(len(System.SYSTEM_STATES)):
62            if (System.SYSTEM_STATES[i] == current_state):
63                s = i+1
64
65        if (s == len(System.SYSTEM_STATES)):
66            print "ERROR SystemManager: No more system states"
67        else:
68            new_state_name = System.SYSTEM_STATES[s]
69            print "SystemManager Goto System State: "+new_state_name
70            self.SystemStateHandler(new_state_name)
71
72    @dbus.service.method(DBUS_NAME, in_signature='', out_signature='s')
73    def getSystemState(self):
74        return self.Get(DBUS_NAME, "current_state")
75
76    def doObjectLookup(self, category, key):
77        obj_path = ""
78        intf_name = INTF_ITEM
79        try:
80            obj_path = System.ID_LOOKUP[category][key]
81            parts = obj_path.split('/')
82            if (parts[3] == 'sensors'):
83                intf_name = INTF_SENSOR
84        except Exception as e:
85            print "ERROR SystemManager: "+str(e)+" not found in lookup"
86
87        return [obj_path, intf_name]
88
89    @dbus.service.method(DBUS_NAME, in_signature='ss', out_signature='(ss)')
90    def getObjectFromId(self, category, key):
91        return self.doObjectLookup(category, key)
92
93    @dbus.service.method(DBUS_NAME, in_signature='sy', out_signature='(ss)')
94    def getObjectFromByteId(self, category, key):
95        byte = int(key)
96        return self.doObjectLookup(category, byte)
97
98    # Get the FRU area names defined in ID_LOOKUP table given a fru_id.
99    # If serval areas are defined for a fru_id, the areas are returned
100    # together as a string with each area name seperated with ','.
101    # If no fru area defined in ID_LOOKUP, an empty string will be returned.
102    @dbus.service.method(DBUS_NAME, in_signature='y', out_signature='s')
103    def getFRUArea(self, fru_id):
104        ret_str = ''
105        fru_id = '_' + str(fru_id)
106        area_list = [
107            area for area in System.ID_LOOKUP['FRU_STR'].keys()
108            if area.endswith(fru_id)]
109        for area in area_list:
110            ret_str = area + ',' + ret_str
111        # remove the last ','
112        return ret_str[:-1]
113
114    def NewObjectHandler(self, obj_path, iprops, bus_name=None):
115        current_state = self.Get(DBUS_NAME, "current_state")
116        if current_state not in System.EXIT_STATE_DEPEND:
117            return
118
119        if obj_path in System.EXIT_STATE_DEPEND[current_state]:
120            print "New object: "+obj_path+" ("+bus_name+")"
121
122    @dbus.service.method(DBUS_NAME, in_signature='s', out_signature='sis')
123    def gpioInit(self, name):
124        gpio_path = ''
125        gpio_num = -1
126        r = ['', gpio_num, '']
127        if name not in System.GPIO_CONFIG:
128            # TODO: Error handling
129            print "ERROR: "+name+" not found in GPIO config table"
130        else:
131
132            gpio_num = -1
133            gpio = System.GPIO_CONFIG[name]
134            if 'gpio_num' in System.GPIO_CONFIG[name]:
135                gpio_num = gpio['gpio_num']
136            else:
137                if 'gpio_pin' in System.GPIO_CONFIG[name]:
138                    gpio_num = System.convertGpio(gpio['gpio_pin'])
139                else:
140                    print "ERROR: SystemManager - GPIO lookup failed for "+name
141
142            if (gpio_num != -1):
143                r = [obmc.enums.GPIO_DEV, gpio_num, gpio['direction']]
144        return r
145
146
147if __name__ == '__main__':
148    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
149    bus = get_dbus()
150    obj = SystemManager(bus, OBJ_NAME)
151    mainloop = gobject.MainLoop()
152    obj.unmask_signals()
153    name = dbus.service.BusName(DBUS_NAME, bus)
154
155    print "Running SystemManager"
156    mainloop.run()
157