使这个烦恼程序成为多渠道而不是单渠道,并将所有数据导入一个CSV渠道

时间:2018-07-31 17:39:34

标签: python csv logging export-to-csv instrumentation

导入系统 导入时间 从Phidg​​etHelperFunctions导入* 从Phidg​​et22.Devices.TemperatureSensor导入* 从Phidg​​et22.Phidg​​etException导入* 从Phidg​​et22.Phidg​​et导入* 从Phidg​​et22.Net导入*

“”“ *配置设备的DataInterval和ChangeTrigger。 *显示有关附加的phidget通道的信息。 *当具有onAttachHandler注册的Phidg​​et频道附加时触发 * * @param self触发附加事件的Phidg​​et频道 “” def onAttachHandler(self):

ph = self

"""
* Set the DataInterval inside of the attach handler to initialize the device with this value.
* DataInterval defines the minimum time between TemperatureChange events.
* DataInterval can be set to any value from MinDataInterval to MaxDataInterval.
"""
print("\tSetting DataInterval to 5000ms")
try:
    ph.setDataInterval(5000)
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Setting DataInterval: \n\t")
    DisplayError(e)
    return

"""
* Set the TemperatureChangeTrigger inside of the attach handler to initialize the device with this value.
* TemperatureChangeTrigger will affect the frequency of TemperatureChange events, by limiting them to only occur when
* the temperature changes by at least the value set.
"""
print("\tSetting Temperature ChangeTrigger to 0.0")
try:
    ph.setTemperatureChangeTrigger(0.0)
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Set TemperatureChangeTrigger: \n\t")
    DisplayError(e)
    return

try:
    serialNumber = ph.getDeviceSerialNumber()
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Get DeviceSerialNumber: \n\t")
    DisplayError(e)
    return

try:
    channel = ph.getChannel()
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Get Channel: \n\t")
    DisplayError(e)
    return

# Check if this is a VINT device
try:
    hub = ph.getHub()
except PhidgetException as e:
    if(e.code == ErrorCode.EPHIDGET_WRONGDEVICE):
        print("\nAttach Event:\n\t-> Serial Number: " + str(serialNumber) +
                "\n\t-> Channel " + str(channel) + "\n")
    return
try:
    hubPort = ph.getHubPort()
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Get HubPort: \n\t")
    DisplayError(e)
    return

print("\nAttach Event:\n\t-> Serial Number: " + str(serialNumber) +
      "\n\t-> Hub Port: " + str(hubPort) + "\n\t-> Channel " + str(channel) + "\n")
return

“”“ *显示有关分离的phidget通道的信息。 *在注册了onDetachHandler的Phidg​​et频道分离时触发 * * @param self触发附加事件的Phidg​​et频道 “” def onDetachHandler(self):

ph = self

try:
    serialNumber = ph.getDeviceSerialNumber()
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Get DeviceSerialNumber: \n\t")
    DisplayError(e)
    return

try:
    channel = ph.getChannel()
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Get Channel: \n\t")
    DisplayError(e)
    return

 # Check if this is a VINT device
try:
    hub = ph.getHub()
except PhidgetException as e:
    if(e.code == ErrorCode.EPHIDGET_WRONGDEVICE):
        print("\nDetach Event:\n\t-> Serial Number: " + str(serialNumber) +
                "\n\t-> Channel " + str(channel) + "\n")
    return

try:
    hubPort = ph.getHubPort()
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Get HubPort: \n\t")
    DisplayError(e)
    return

print("\nDetach Event:\n\t-> Serial Number: " + str(serialNumber) +
      "\n\t-> Hub Port: " + str(hubPort) + "\n\t-> Channel " + str(channel) + "\n")
return

“”“ *将phidget错误信息写入stderr。 *当注册了onErrorHandler的Phidg​​et频道在库中遇到错误时触发 * * @param self触发附加事件的Phidg​​et频道 * @param errorCode与枚举类型ph.ErrorEventCode的错误相关的代码 * @param errorString字符串,包含触发的错误的描述 “” def onErrorHandler(self,errorCode,errorString):

sys.stderr.write("[Phidget Error Event] -> " + errorString + " (" + str(errorCode) + ")\n")

“”“ *为Phidg​​et Attach,Phidg​​et Detach,Phidg​​et Error事件设置事件处理程序 * * @param ph Phidg​​et通道,用于向其中添加事件处理程序 * @return如果操作成功 * @raise Phidg​​etException如果失败 “” def SetAttachDetachError_Handlers(ph):     打印(“ \ n --------------------------------------”)     print(“ \ nSetting OnAttachHandler ...”)     尝试:         ph.setOnAttachHandler(onAttachHandler)     Phidg​​etException除外,例如e:         sys.stderr.write(“运行时错误->设置附加处理程序:\ n \ t”)         DisplayError(e)         提高

print("Setting OnDetachHandler...")
try:
    ph.setOnDetachHandler(onDetachHandler)
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Set Detach Handler: \n\t")
    DisplayError(e)
    raise

print("Setting OnErrorHandler...")
try:
    ph.setOnErrorHandler(onErrorHandler)
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Set Error Handler: \n\t")
    DisplayError(e)
    raise

return

“”“ *输出TemperatureSensor最近报告的温度。 *当注册了onTemperatureChangeHandler的TemperatureSensor通道满足DataInterval和ChangeTrigger条件时触发 * * @param self触发TemperatureChange事件的TemperatureSensor通道 * @param temperature从TemperatureSensor通道报告的温度 “”“

print(“输入文件名”) filename = input()

,以打开(文件名+“ .csv”,“ a”)作为输出文件:         outfile.write(“ C语言中的温度”) def onTemperatureChangeHandler(self,temperature):

print( str(temperature))N

with open (filename + ".csv","a") as outfile:
    outfile.write("\n"+str(temperature))

“”“ *创建一个TemperatureSensor通道的新实例。 * * @param pvih指向Phidg​​etTemperatureSensorHandle通道的指针以创建 * @return如果操作成功 * @raise Phidg​​etException如果失败 “” def CreateTemperatureSensor(pvih):

global start
global outfile
print("Creating TemperatureSensor Channel...")
try:
    pvih.create()
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Creating TemperatureSensor: \n\t")
    DisplayError(e)
    raise

return

“”“ *为TemperatureSensor的TemperatureChange事件设置事件处理程序 * * @param pvih Phidg​​etTemperatureSensorHandle通道将事件添加到 * @param fptr触发TemperatureChange事件时要调用的回调函数 * @return如果操作成功 * @raise Phidg​​etException如果失败 “” def SetTemperatureHandler(pvih,fptr):

if (not (fptr is None)):
    print("\n--------------------\n"
        "\n  | Temperature change events contain the most recent temperature received from the device.\n"
        "  | The linked TemperatureChange function will run as an event at every DataInterval.\n"
        "  | These events will not occur until a change in temperature >= to the set ChangeTrigger has occurred.\n"
        "  | DataInterval and ChangeTrigger should initially be set in the device AttachHandler function.")

print("")
if (fptr is None):
    print("Clearing OnTemperatureChangeHandler...")
else:
    print("Setting OnTemperatureChangeHandler...")

print("\n--------------------")
try:
    pvih.setOnTemperatureChangeHandler(fptr)
except PhidgetException as e:
    sys.stderr.write("Runtime Error -> Setting TemperatureChangeHandler: \n\t")
    DisplayError(e)
    raise

return

“”“ *创建,配置并打开TemperatureSensor通道。 *显示温度事件10秒钟 *关闭温度传感器通道 * * @return如果程序成功退出,则返回0,如果错误退出,则返回1。 “” def main():     尝试:         “”         *分配一个新的Phidg​​et Channel对象         “”         尝试:             ch = TemperatureSensor()         Phidg​​etException除外,例如e:             sys.stderr.write(“运行时错误->创建TemperatureSensor:\ n \ t”)             DisplayError(e)             提高         除了RuntimeError为e:             sys.stderr.write(“运行时错误->创建TemperatureSensor:\ n \ t” + e)             提高

    """
    * Set matching parameters to specify which channel to open
    """
    #InputSerialNumber(ch)

    #InputVINTProperties(ch)

    #InputChannel(ch)

    #InputupNetwork(ch)

    """
    * Add event handlers before calling open so that no events are missed.
    """
    SetAttachDetachError_Handlers(ch)

    SetTemperatureHandler(ch, onTemperatureChangeHandler)

    """
    * Open the channel with a timeout
    """
    ch.openWaitForAttachment(5000)


    print("Input duration of data collection in seconds...")

    dataduration = input()
    dataduration = int(dataduration)


    #TIME IS IN SECONDS THIS IS THE LINE TO EDIT TO YOUR EXPIRIMENT LENGHT
    time.sleep(int(dataduration))
    #EDIT THE LINE ABOVE TO YOUR EXPIRIMENT LENGHT
    """
     * Perform clean up and exit
     """

    SetTemperatureHandler(ch, None)
    print("\nDone Sampling...")
    print("Cleaning up...")
    ch.close()
    print("\nExiting...")
    print("Press ENTER to end program.")
    readin = sys.stdin.readline(1)
    return 0

except PhidgetException as e:
    sys.stderr.write("\nExiting with error(s)...")
    DisplayError(e)
    print("Press ENTER to end program.")
    readin = sys.stdin.readline(1)
    return 1

main()

0 个答案:

没有答案