lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

Bus.py for WebIOPi

Sun Mar 09, 2014 3:11 am

Code: Select all

FUNCTIONS = {
    "I2C": {"enabled": False, "gpio": {0:"SDA", 1:"SCL", 2:"SDA", 3:"SCL"}, "modules": ["i2c-bcm2708", "i2c-dev"]},
    "SPI": {"enabled": False, "gpio": {7:"CE1", 8:"CE0", 9:"MISO", 10:"MOSI", 11:"SCLK"}, "modules": ["spi-bcm2708", "spidev"]},
    "UART": {"enabled": False, "gpio": {14:"TX", 15:"RX"}},
    "ONEWIRE": {"enabled": False, "gpio": {4:"DATA"}, "modules": ["w1-gpio"], "wait": 2}
}




def loadModule(module):
    debug("Loading module : %s" % module)
    subprocess.call(["modprobe", module])
    
def unloadModule(module):
    subprocess.call(["modprobe", "-r", module])
    
def loadModules(bus):
    if FUNCTIONS[bus]["enabled"] == False and not modulesLoaded(bus):
        info("Loading %s modules" % bus)
        for module in FUNCTIONS[bus]["modules"]:
            loadModule(module)
        if "wait" in FUNCTIONS[bus]:
            info("Sleeping %ds to let %s modules load" % (FUNCTIONS[bus]["wait"], bus))
            time.sleep(FUNCTIONS[bus]["wait"])

    FUNCTIONS[bus]["enabled"] = True

def unloadModules(bus):
    info("Unloading %s modules" % bus)
    for module in FUNCTIONS[bus]["modules"]:
        unloadModule(module)
    FUNCTIONS[bus]["enabled"] = False
        
def __modulesLoaded__(modules, lines):
    if len(modules) == 0:
        return True
    for line in lines:
        if modules[0].replace("-", "_") == line.split(" ")[0]:
            return __modulesLoaded__(modules[1:], lines)
    return False

def modulesLoaded(bus):
    if not bus in FUNCTIONS or not "modules" in FUNCTIONS[bus]:
        return True

    f = open("/proc/modules")
    c = f.read()
    f.close()
    lines = c.split("\n")
    return __modulesLoaded__(FUNCTIONS[bus]["modules"], lines)

def checkAllBus():
    for bus in FUNCTIONS:
        if modulesLoaded(bus):
            FUNCTIONS[bus]["enabled"] = True

class Bus():
    def __init__(self, busName, device, flag=os.O_RDWR):
        loadModules(busName)
        self.busName = busName
        self.device = device
        self.flag = flag
        self.fd = 0
        self.open()
        
    def __str__(self):
        return "Bus(%s, %s)" % (self.busName, self.device)
        
    def open(self):
        self.fd = os.open(self.device, self.flag)
        if self.fd < 0:
            raise Exception("Cannot open %s" % self.device)

    def close(self):
        if self.fd > 0:
            os.close(self.fd)
    
    def available(self):
        raise NotImplementedError
    
    def read(self, size=1):
        if self.fd > 0:
            return os.read(self.fd, size)
        raise Exception("Device %s not open" % self.device)
    
    def readBytes(self, size=1):
        return bytearray(self.read(size))
    
    def readByte(self):
        return self.readBytes()[0]

    def write(self, string):
        if self.fd > 0:
            return os.write(self.fd, string)
        raise Exception("Device %s not open" % self.device)
    
    def writeBytes(self, data):
        return self.write(bytearray(data))

    def writeByte(self, value):
        self.writeBytes([value])
This is WebIOPi
1)What's this function does?
__modulesLoaded__(modules, lines):
if len(modules) == 0:
return True
for line in lines:
if modules[0].replace("-", "_") == line.split(" ")[0]:
return __modulesLoaded__(modules[1:], lines)
return False

2)and what's modulesLoaded?
def modulesLoaded(bus):
if not bus in FUNCTIONS or not "modules" in FUNCTIONS[bus]:
return True

f = open("/proc/modules")
c = f.read()
f.close()
lines = c.split("\n")
return __modulesLoaded__(FUNCTIONS[bus]["modules"], lines)

3)what's the definition of bus ? I don't see instantiation of Bus class
def checkAllBus():
for bus in FUNCTIONS:
if modulesLoaded(bus):
FUNCTIONS[bus]["enabled"] = True

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Bus.py for WebIOPi

Sun Mar 09, 2014 7:30 am

I'm not going to explain how the functions work but I can say what I think they do.

First off, FUNCTIONS defined a dictionary of various buses. Some buses require modules to work, and the dictionary includes the names of these modules. The methods seem to read the /proc/modules file and, if the necessary modules are found then the bus is marked as enabled.

As for your last question, I don't think Bus is initialized in this code. I suspect bus.py is imported into another python file.

It would also be nice to hear if the above is helpful. My reply to your previous post had no reply...
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

Re: Bus.py for WebIOPi

Sun Mar 09, 2014 4:37 pm

elParaguayo wrote:I'm not going to explain how the functions work but I can say what I think they do.

First off, FUNCTIONS defined a dictionary of various buses. Some buses require modules to work, and the dictionary includes the names of these modules. The methods seem to read the /proc/modules file and, if the necessary modules are found then the bus is marked as enabled.

As for your last question, I don't think Bus is initialized in this code. I suspect bus.py is imported into another python file.

It would also be nice to hear if the above is helpful. My reply to your previous post had no reply...
Thanks for your insight. Anything would help for newbie like me.

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Bus.py for WebIOPi

Sun Mar 09, 2014 7:41 pm

Lilzz,

You've got a lot of posts recently asking how some code works. It might be helpful if you explain what you're trying to do and then we can provide some more helpful answers.

El_P
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

Re: Bus.py for WebIOPi

Mon Mar 10, 2014 6:24 am

elParaguayo wrote:Lilzz,

You've got a lot of posts recently asking how some code works. It might be helpful if you explain what you're trying to do and then we can provide some more helpful answers.

El_P

I am trying to understand as much as possible on WebIOPi. Do you understand 90% of the codes there? I try ask on their support forum but sometimes there are no answer to my questions.

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Bus.py for WebIOPi

Mon Mar 10, 2014 6:47 am

Ok, but my question is why are you trying to understand it? Is there something you want to use it for?

I've never seen any of the code before and have just provided some answers based on the code in your posts.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

Re: Bus.py for WebIOPi

Mon Mar 10, 2014 7:39 am

elParaguayo wrote:Ok, but my question is why are you trying to understand it? Is there something you want to use it for?

I've never seen any of the code before and have just provided some answers based on the code in your posts.
It's one of the most important project for the Pi as far as I concerned. I am trying to modifying it. In Order to do that, I will try understand as much as possible.

Here's some more codes, it supposed to turn it to HTTP REST Request using decorator functions in python but I don't see HOW it's become. I only know the end result is HTTP REST Request being send out. Do you how digitalRead has modified.
Taking a look at this diagram

http://code.google.com/p/webiopi/wiki/Tutorial_Basis

Code: Select all

def request(method="GET", path="", data=None):
    def wrapper(func):
        func.routed = True
        func.method = method
        func.path = path
        func.data = data
        return func
    return wrapper

def response(fmt="%s", contentType="text/plain"):
    def wrapper(func):
        func.format = fmt
        func.contentType = contentType
        return func
    return wrapper


 @request("GET", "%(channel)d/value")
    @response("%d")
    def digitalRead(self, channel):
    self.checkDigitalChannel(channel)
    return self.__digitalRead__(channel)

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Bus.py for WebIOPi

Mon Mar 10, 2014 9:32 am

OK. I suspect, then, that I am out of my depth and won't really be able to provide the level of help that you're looking for. I'm not familiar with web scripts or decorator functions so I suspect I won't be much use to you!!
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

Return to “Python”