Loop Code then Sleep

This is the place for queries that don't fit in any of the other categories.

Loop Code then Sleep

Postby Nu2Java » Thu Jul 04, 2013 3:17 am

Hello, I am very new to Python and I am working with some code I found for checking a USB temp sensor. I want to loop the code and read the temp every 10 seconds but I cannot seem to figure out where to place the time.sleep(10) Thanks for any help!


Code: Select all
import usb
import sys
import struct
import time

VIDPIDs = [(0x0c45L,0x7401L)]
REQ_INT_LEN = 8
REQ_BULK_LEN = 8
TIMEOUT = 2000

class TemperDevice():
    def __init__(self, device):
        self._device = device
        self._handle = None

    def get_temperature(self, format='celsius'):
        try:
            if not self._handle:
                self._handle = self._device.open()
                try:
                    self._handle.detachKernelDriver(0)
                except usb.USBError:
                    pass
                try:
                    self._handle.detachKernelDriver(1)
                except usb.USBError:
                    pass
                self._handle.setConfiguration(1)
                self._handle.claimInterface(0)
                self._handle.claimInterface(1)
                self._handle.controlMsg(requestType=0x21, request=0x09, value=0x0201, index=0x00, buffer="\x01\x01", timeout=TIMEOUT) # ini_control_transfer

            self._control_transfer(self._handle, "\x01\x80\x33\x01\x00\x00\x00\x00") # uTemperatura
            self._interrupt_read(self._handle)
            self._control_transfer(self._handle, "\x01\x82\x77\x01\x00\x00\x00\x00") # uIni1
            self._interrupt_read(self._handle)
            self._control_transfer(self._handle, "\x01\x86\xff\x01\x00\x00\x00\x00") # uIni2
            self._interrupt_read(self._handle)
            self._interrupt_read(self._handle)
            self._control_transfer(self._handle, "\x01\x80\x33\x01\x00\x00\x00\x00") # uTemperatura
            data = self._interrupt_read(self._handle)
            data_s = "".join([chr(byte) for byte in data])
            temp_c = 125.0/32000.0*(struct.unpack('>h', data_s[2:4])[0])
            if format == 'celsius':
                return temp_c
            elif format == 'fahrenheit':
                return temp_c*1.8+32.0
            elif format == 'millicelsius':
                return int(temp_c*1000)
            else:
                raise ValueError("Unknown format")
        except usb.USBError, e:
            self.close()
            if "not permitted" in str(e):
                raise Exception("Permission problem accessing USB. Maybe I need to run as root?")
            else:
                raise

    def close(self):
        if self._handle:
            try:
                self._handle.releaseInterface()
            except ValueError:
                pass
            self._handle = None

    def _control_transfer(self, handle, data):
        handle.controlMsg(requestType=0x21, request=0x09, value=0x0200, index=0x01, buffer=data, timeout=TIMEOUT)

    def _interrupt_read(self, handle):
        return handle.interruptRead(0x82, REQ_INT_LEN)

class TemperHandler():

    def __init__(self):
        busses = usb.busses()
        self._devices = []
        for bus in busses:
            self._devices.extend([TemperDevice(x) for x in bus.devices if (x.idVendor,x.idProduct) in VIDPIDs])

    def get_devices(self):
        return self._devices

if __name__ == '__main__':
    th = TemperHandler()
    devs = th.get_devices()
    print "Found %i devices" % len(devs)

while True:
    for i, dev in enumerate(devs):
        print "Device #%i: %0.1f°C %0.1f°F" % (i, dev.get_temperature(), dev.get_temperature(format="fahrenheit"))
Nu2Java
 
Posts: 3
Joined: Thu Jul 04, 2013 3:06 am

Re: Loop Code then Sleep

Postby metulburr » Thu Jul 04, 2013 5:01 am

i would assume the very last line, in the while loop block, after the the for loop
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1470
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Loop Code then Sleep

Postby Nu2Java » Thu Jul 04, 2013 10:25 pm

Thanks for the reply, I gave that a try and get an error: "IndentationError: expected an indented block". I get this for the sleep line after the for loop. This is how I wrote it:

Code: Select all
while True:
    for i, dev in enumerate(devs):
       time.sleep(10)
        print "Device #%i: %0.1f°C %0.1f°F" % (i, dev.get_temperature(), dev.get_temperature(format="fahrenheit"))


Is this incorrect?
Nu2Java
 
Posts: 3
Joined: Thu Jul 04, 2013 3:06 am

Re: Loop Code then Sleep

Postby micseydel » Thu Jul 04, 2013 10:37 pm

You need to either (1) read a basic tutorial on Python, because something very basic is escaping you, or (2) pay someone to do what you need done. Really, I'd expect someone after their first day in a course, or after an hour or less of reading tutorials to know that that code is malformed.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1357
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Loop Code then Sleep

Postby Nu2Java » Thu Jul 04, 2013 11:13 pm

I am "assuming" you are talking about indentation and how the code is spaced, if not then I am stumped. I have been looking up several examples and have tried them in my code and continue to get errors. I did not write the code and as I mentioned I am very new and trying to learn Python. So any help from someone letting me know what I am doing wrong would of great help to me.
Nu2Java
 
Posts: 3
Joined: Thu Jul 04, 2013 3:06 am

Re: Loop Code then Sleep

Postby metulburr » Thu Jul 04, 2013 11:18 pm

Code: Select all
while True:
    for i, dev in enumerate(devs):
       time.sleep(10)
        print "Device #%i: %0.1f°C %0.1f°F" % (i, dev.get_temperature(), dev.get_temperature(format="fahrenheit"))

I mentioned I am very new and trying to learn Python.

Ok lesson 1:
What is the while loops block?
How many different indentations are there in this code? How many indentations are there suppose to be?
I said for loop, not for loop statement. I also said very last line. Putting it on the very last line should be the first hint.

You can read this for more info regarding indentation:
viewtopic.php?f=25&t=209

This isnt the type of material you should be covering in your inexperience level. You should throw this code aside and start working on basic tutorials. Maybe a month or so from now after doing some tutorials and examples, you can answer this question yourself.
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1470
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Loop Code then Sleep

Postby micseydel » Thu Jul 04, 2013 11:22 pm

You don't have to assume anything, if you run the block of code you showed there Python will complain about indentation explicitly before doing anything else. As I said, you need to through a tutorial. You need to put in some effort here and then ask specific questions that we'd be happy to help with instead of asking for your task. If you have no idea how to modify some code, then you're not a programmer yet, right? So become a programmer, read a tutorial.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1357
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to General Coding Help

Who is online

Users browsing this forum: micseydel and 4 guests