class PhidgetTemperature(object):
    def __init__(self,
                 hub_port=0,
                 hub_channel=1,
                 serial_number=-1,
                 use_hub=False):

        self.use_hub = use_hub
        self.hub_port = hub_port
        self.hub_channel = hub_channel

        try:
            self.ch = TemperatureSensor()
            self.ch.setDeviceSerialNumber(serial_number)
            if use_hub:
                self.ch.setHubPort(hub_port)
                self.ch.setChannel(hub_channel)
                print('HUB, PORT:%d CHANNEL: %d' % (hub_port, hub_channel))
        except PhidgetException as e:
            sys.stderr.write(
                "Runtime Error -> Creating TemperatureSensor: \n\t")
            DisplayError(e)
            self.ch.close()
            raise
        except RuntimeError as e:
            sys.stderr.write(
                "Runtime Error -> Creating TemperatureSensor: \n\t" + e)
            self.ch.close()
            raise

        logging.info("Phidget: Opening and Waiting for Attachment...")

        try:
            self.ch.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, self.ch)
            self.ch.close()
            raise EndProgramSignal("Program Terminated: Open Failed")
        time.sleep(1)
        logging.info("Phidget: Ready!")

    def getTemperature(self, fahrenheit=False):

        if fahrenheit:
            return (self.ch.getTemperature() * 9 / 5.0) + 32

        else:
            return self.ch.getTemperature()

    def closeConnection(self):
        return self.ch.close()
Пример #2
0
def configure_phidget(phidget):
    """
    :param serial: Serial Number as int
    :param hub: Is this connected to a hub? 1:Yes, 0:No
    :param channel: Channel 0 is Thermocouple. 1 is Board.
    :return: configured phidget
    """
    phidget_channels = []

    for index, sensor in enumerate(phidget["channels"]):
        ch = TemperatureSensor()
        ch.setDeviceSerialNumber(phidget["serial"])
        ch.setHubPort(phidget["hub"])
        ch.setChannel(phidget["channel"][index])
        ch.setOnAttachHandler(onAttachHandler)
        phidget_channels.append((ch, sensor))

    return phidget_channels
Пример #3
0
class MyThermo:
    def __init__(self, hub_serial, hub_port, thermal_channel):
        self.sensor = TemperatureSensor()
        self.sensor.setHubPort(hub_port)
        self.sensor.setChannel(thermal_channel)
        self.sensor.setDeviceSerialNumber(hub_serial)
        self.sensor.openWaitForAttachment(5000)
        self.previous_temp = 0
        self.thermal_channel = thermal_channel

    def get_temp(self):
        try:
            temp = self.sensor.getTemperature()
            self.previous_temp = temp
            return temp
        except PhidgetException as exception:
            print('Error on thermal channel', self.thermal_channel, exception)
            return self.previous_temp

    def __del__(self):
        self.sensor.close()
Пример #4
0
def main():
    try:
        """
        * Allocate a new Phidget Channel object
        """
        try:
            ch = TemperatureSensor()
        except PhidgetException as e:
            sys.stderr.write("Runtime Error -> Creating TemperatureSensor: \n\t")
            DisplayError(e)
            raise
        except RuntimeError as e:
            sys.stderr.write("Runtime Error -> Creating TemperatureSensor: \n\t" + e)
            raise

        """
        * Set matching parameters to specify which channel to open
        """
        
        #You may remove this line and hard-code the addressing parameters to fit your application
        channelInfo = AskForDeviceParameters(ch)
        
        ch.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
        ch.setHubPort(channelInfo.hubPort)
        ch.setIsHubPortDevice(channelInfo.isHubPortDevice)
        ch.setChannel(channelInfo.channel)   
        
        if(channelInfo.netInfo.isRemote):
            ch.setIsRemote(channelInfo.netInfo.isRemote)
            if(channelInfo.netInfo.serverDiscovery):
                try:
                    Net.enableServerDiscovery(PhidgetServerType.PHIDGETSERVER_DEVICEREMOTE)
                except PhidgetException as e:
                    PrintEnableServerDiscoveryErrorMessage(e)
                    raise EndProgramSignal("Program Terminated: EnableServerDiscovery Failed")
            else:
                Net.addServer("Server", channelInfo.netInfo.hostname,
                    channelInfo.netInfo.port, channelInfo.netInfo.password, 0)
        
        """
        * Add event handlers before calling open so that no events are missed.
        """
        print("\n--------------------------------------")
        print("\nSetting OnAttachHandler...")
        ch.setOnAttachHandler(onAttachHandler)
        
        print("Setting OnDetachHandler...")
        ch.setOnDetachHandler(onDetachHandler)
        
        print("Setting OnErrorHandler...")
        ch.setOnErrorHandler(onErrorHandler)
        
        #This call may be harmlessly removed
        PrintEventDescriptions()
        
        print("\nSetting OnTemperatureChangeHandler...")
        ch.setOnTemperatureChangeHandler(onTemperatureChangeHandler)
        
        """
        * Open the channel with a timeout
        """
        
        print("\nOpening and Waiting for Attachment...")
        
        try:
            ch.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch)
            raise EndProgramSignal("Program Terminated: Open Failed")
        
        print("Sampling data for 10 seconds...")
        
        print("You can do stuff with your Phidgets here and/or in the event handlers.")
        
        time.sleep(10)
        
        """
        * Perform clean up and exit
        """

        #clear the TemperatureChange event handler 
        ch.setOnTemperatureChangeHandler(None)
        
        print("\nDone Sampling...")

        print("Cleaning up...")
        ch.close()
        print("\nExiting...")
        return 0

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        DisplayError(e)
        traceback.print_exc()
        print("Cleaning up...")
        ch.setOnTemperatureChangeHandler(None)
        ch.close()
        return 1
    except EndProgramSignal as e:
        print(e)
        print("Cleaning up...")
        ch.setOnTemperatureChangeHandler(None)
        ch.close()
        return 1
    finally:
        print("Press ENTER to end program.")
        readin = sys.stdin.readline()
Пример #5
0
from prometheus_client import start_http_server, Gauge
from Phidget22.PhidgetException import *
from Phidget22.Phidget import *
from Phidget22.Devices.TemperatureSensor import *
import time

TEMPERATURE_FAHRENHEIT = Gauge('current_temperature_fahrenheit',
                               'Current Temperature in FahrenHeit')
TEMPERATURE_CELCIUS = Gauge('current_temperature_celcius',
                            'Current Temperature in Celcius')

tc = TemperatureSensor()
tc.setHubPort(1)
tc.setChannel(0)

tc.openWaitForAttachment(5000)


def c_to_f(c):
    return (9 / 5 * c + 32)


def get_temp(fahrenheit=False):
    temp_celcius = tc.getTemperature()
    if fahrenheit:
        temp = c_to_f(temp_celcius)
    else:
        temp = temp_celcius
    return round(temp, 1)

Пример #6
0
# code for humidity sensor
humidity = HumiditySensor()
humidity.setDeviceSerialNumber(561266)
humidity.setHubPort(5)
humidity.setIsHubPortDevice(False)
humidity.setChannel(0)
humidity.openWaitForAttachment(5000)

try:
    humidity.getHumidity()
except Exception as e:
    pass
time.sleep(2)
print(humidity.getHumidity())

# code for temperature sensor
temp = TemperatureSensor()
temp.setDeviceSerialNumber(561266)
temp.setHubPort(5)
temp.setIsHubPortDevice(False)
temp.setChannel(0)

temp.openWaitForAttachment(5000)

try:
    temp.getTemperature()
except Exception as e:
    pass
time.sleep(2)
print(temp.getTemperature())