diff options
author | manojgudi | 2013-12-24 21:07:36 +0530 |
---|---|---|
committer | manojgudi | 2013-12-24 21:07:36 +0530 |
commit | 576936961996253c5a7ea27b63e5bb2ce0bb01aa (patch) | |
tree | b7b92b6025a04317ff7972e3a087b278468209a8 /gr-sbhs | |
parent | da744ab20441967db5bc7885fcd5224f7fd75100 (diff) | |
download | gnuradio-576936961996253c5a7ea27b63e5bb2ce0bb01aa.tar.gz gnuradio-576936961996253c5a7ea27b63e5bb2ce0bb01aa.tar.bz2 gnuradio-576936961996253c5a7ea27b63e5bb2ce0bb01aa.zip |
Aded SBHS block
Diffstat (limited to 'gr-sbhs')
-rw-r--r-- | gr-sbhs/CMakeLists.txt | 55 | ||||
-rw-r--r-- | gr-sbhs/doc/CMakeLists.txt | 23 | ||||
-rw-r--r-- | gr-sbhs/doc/README.sbhs | 13 | ||||
-rw-r--r-- | gr-sbhs/doc/sbhs.dox | 29 | ||||
-rw-r--r-- | gr-sbhs/grc/CMakeLists.txt | 30 | ||||
-rw-r--r-- | gr-sbhs/grc/sbhs_controller.xml | 108 | ||||
-rw-r--r-- | gr-sbhs/grc/sbhs_plant.xml | 71 | ||||
-rw-r--r-- | gr-sbhs/python/CMakeLists.txt | 94 | ||||
-rw-r--r-- | gr-sbhs/python/__init__.py | 54 | ||||
-rw-r--r-- | gr-sbhs/python/gr_controller.py | 70 | ||||
-rw-r--r-- | gr-sbhs/python/gr_sbhs.py | 65 | ||||
-rwxr-xr-x | gr-sbhs/python/qa_dsim.py | 68 | ||||
-rw-r--r-- | gr-sbhs/python/que.py | 35 | ||||
-rwxr-xr-x | gr-sbhs/python/sbhs.py | 201 | ||||
-rwxr-xr-x | gr-sbhs/python/scan_machines.py | 59 | ||||
-rwxr-xr-x | gr-sbhs/python/testing.py | 60 |
16 files changed, 1035 insertions, 0 deletions
diff --git a/gr-sbhs/CMakeLists.txt b/gr-sbhs/CMakeLists.txt new file mode 100644 index 000000000..597a2e44a --- /dev/null +++ b/gr-sbhs/CMakeLists.txt @@ -0,0 +1,55 @@ +# Copyright 2012 Free Software Foundation, Inc. +# +# This file is part of GNU Radio +# +# GNU Radio is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3, or (at your option) +# any later version. +# +# GNU Radio is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Radio; see the file COPYING. If not, write to +# the Free Software Foundation, Inc., 51 Franklin Street, +# Boston, MA 02110-1301, USA. + +######################################################################## +# Setup dependencies +######################################################################## +#include(GrBoost) + +#find_package(CONTROLSW3f) + +######################################################################## +# Register component +######################################################################## +include(GrComponent) + +GR_REGISTER_COMPONENT("gr-sbhs" ENABLE_GR_SBHS + ENABLE_GRUEL + ENABLE_VOLK + Boost_FOUND + ENABLE_GR_CORE +) + +######################################################################## +# Begin conditional configuration +######################################################################## +if(ENABLE_GR_SBHS) + +######################################################################## +# Add subdirectories +######################################################################## +if(ENABLE_PYTHON) + add_subdirectory(python) + add_subdirectory(grc) +endif(ENABLE_PYTHON) +#add_subdirectory(examples) +add_subdirectory(doc) + + +endif(ENABLE_GR_SBHS) diff --git a/gr-sbhs/doc/CMakeLists.txt b/gr-sbhs/doc/CMakeLists.txt new file mode 100644 index 000000000..42f073150 --- /dev/null +++ b/gr-sbhs/doc/CMakeLists.txt @@ -0,0 +1,23 @@ +# Copyright 2012 Free Software Foundation, Inc. +# +# This file is part of GNU Radio +# +# GNU Radio is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3, or (at your option) +# any later version. +# +# GNU Radio is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Radio; see the file COPYING. If not, write to +# the Free Software Foundation, Inc., 51 Franklin Street, +# Boston, MA 02110-1301, USA. + +install( + FILES README.sbhs + DESTINATION ${GR_PKG_DOC_DIR} +) diff --git a/gr-sbhs/doc/README.sbhs b/gr-sbhs/doc/README.sbhs new file mode 100644 index 000000000..61e8f6bf8 --- /dev/null +++ b/gr-sbhs/doc/README.sbhs @@ -0,0 +1,13 @@ +This is the gr-scigen package. It contains signal processing blocks to +perform FFTs and FFT-related functionality. + +The Python namespace is in gnuradio.scigen, which would be normally +imported as: + + from gnuradio import scigen + +See the Doxygen documentation for details about the blocks available +in this package. A quick listing of the details can be found in Python +after importing by using: + + help(scigen) diff --git a/gr-sbhs/doc/sbhs.dox b/gr-sbhs/doc/sbhs.dox new file mode 100644 index 000000000..9c65949d6 --- /dev/null +++ b/gr-sbhs/doc/sbhs.dox @@ -0,0 +1,29 @@ +/*! \page page_fft FFT Signal Processing Blocks + +\section Introduction + +This is the gr-sbhs package. It contains signal processing blocks to +perform FFTs and FFT-related functionality. + +The Python namespace is in gnuradio.fft, which would be normally +imported as: + +\code + from gnuradio import sbhs +\endcode + +See the Doxygen documentation for details about the blocks available +in this package. A quick listing of the details can be found in Python +after importing by using: + +\code + help(sbhs) +\endcode + +\section Dependencies + +The sbhs blocks require the following dependencies. + +\li fftw3f (>= 3.0) http://www.fftw.org/download.html + +*/ diff --git a/gr-sbhs/grc/CMakeLists.txt b/gr-sbhs/grc/CMakeLists.txt new file mode 100644 index 000000000..f53930884 --- /dev/null +++ b/gr-sbhs/grc/CMakeLists.txt @@ -0,0 +1,30 @@ +# Copyright 2012 Free Software Foundation, Inc. +# +# This file is part of GNU Radio +# +# GNU Radio is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3, or (at your option) +# any later version. +# +# GNU Radio is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Radio; see the file COPYING. If not, write to +# the Free Software Foundation, Inc., 51 Franklin Street, +# Boston, MA 02110-1301, USA. + +install(FILES + sbhs_plant.xml + DESTINATION ${GRC_BLOCKS_DIR} + COMPONENT "sbhs_python" +) + +install(FILES + sbhs_controller.xml + DESTINATION ${GRC_BLOCKS_DIR} + COMPONENT "sbhs_python" +) diff --git a/gr-sbhs/grc/sbhs_controller.xml b/gr-sbhs/grc/sbhs_controller.xml new file mode 100644 index 000000000..a8729e9a0 --- /dev/null +++ b/gr-sbhs/grc/sbhs_controller.xml @@ -0,0 +1,108 @@ +<?xml version="1.0"?> +<!-- +################################################### +##Add Block: +## all types, 1 output, 2 to inf inputs +################################################### + --> +<block> + <name>sbhs_controller</name> + <key>sbhs_controller</key> + <category>controller</category> + + <import>import gr_controller</import> + <make>gr_controller.sbhs_controller() +self.$(id).set_parameters($P, $I, $d, $a, $b, $window) + </make> + <param> + <name>IO Type</name> + <key>type</key> + <type>enum</type> + <option><name>F32_F32</name><key>f32_f32</key></option> + <option><name>S32_S32</name><key>s32_s32</key></option> + <option><name>S16_S16</name><key>s16_s16</key></option> + <option><name>S8_S8</name><key>s8_s8</key></option> + </param> + + <param> + <name>Num Inputs</name> + <key>num_inputs</key> + <value>1</value> + <type>int</type> + </param> + + <param> + <name>Vec Length</name> + <key>vlen</key> + <value>1</value> + <type>int</type> + </param> + + <param> + <name>Delta T</name> + <key>a</key> + <value>1</value> + <type>real</type> + </param> + + <param> + <name>P Value</name> + <key>P</key> + <value>1</value> + <type>real</type> + </param> + + <param> + <name>I Value</name> + <key>I</key> + <value>1</value> + <type>real</type> + </param> + + <param> + <name>D Value</name> + <key>d</key> + <value>1</value> + <type>real</type> + </param> + + <param> + <name>Set Point</name> + <key>b</key> + <value>1</value> + <type>real</type> + </param> + + + <param> + <name>Window</name> + <key>window</key> + <value>1</value> + <type>int</type> + </param> + + + + <!-- + Check if number of inputs are greater than 0, and if vector length + is greater than 0. + --> + <check>$num_inputs > 0</check> + <check>$vlen > 0</check> + <sink> + <name>in</name> + <type>$(str($type).split('_')[0])</type> + <vlen>$vlen</vlen> + <nports>$num_inputs</nports> + </sink> + <source> + <name>out</name> + <type>$(str($type).split('_')[1])</type> + <vlen>$vlen</vlen> + </source> + <doc> + +SBHS Controller Block +> SBHS Controller Block to implement P I D Algorithms + </doc> +</block> diff --git a/gr-sbhs/grc/sbhs_plant.xml b/gr-sbhs/grc/sbhs_plant.xml new file mode 100644 index 000000000..f6e9c34c1 --- /dev/null +++ b/gr-sbhs/grc/sbhs_plant.xml @@ -0,0 +1,71 @@ +<?xml version="1.0"?> +<!-- +################################################### +##Add Block: +## all types, 1 output, 2 to inf inputs +################################################### + --> +<block> + <name>sbhs</name> + <key>gr_sbhs</key> + <category>sbhs</category> + + <import>import gr_sbhs</import> + <make>gr_sbhs.gr_sbhs() +self.$(id).set_parameters($window) + </make> + <param> + <name>IO Type</name> + <key>type</key> + <type>enum</type> + <option><name>F32_F32</name><key>f32_f32</key></option> + <option><name>S32_S32</name><key>s32_s32</key></option> + <option><name>S16_S16</name><key>s16_s16</key></option> + <option><name>S8_S8</name><key>s8_s8</key></option> + </param> + <param> + <name>Num Inputs</name> + <key>num_inputs</key> + <value>2</value> + <type>int</type> + </param> + + <param> + <name>Vec Length</name> + <key>vlen</key> + <value>1</value> + <type>int</type> + </param> + + <param> + <name>Window</name> + <key>window</key> + <value>1</value> + <type>int</type> + </param> + + <!-- + Check if number of inputs are greater than 0, and if vector length + is greater than 0. + --> + <check>$num_inputs > 0</check> + <check>$vlen > 0</check> + <sink> + <name>in</name> + <type>$(str($type).split('_')[0])</type> + <vlen>$vlen</vlen> + <nports>$num_inputs</nports> + </sink> + <source> + <name>out</name> + <type>$(str($type).split('_')[1])</type> + <vlen>$vlen</vlen> + </source> + <doc> + +SBHS Serial block + +> Check if your scilab function requires multiple inputs +> Make sure you have same n_input_items when you have multiple inputs + </doc> +</block> diff --git a/gr-sbhs/python/CMakeLists.txt b/gr-sbhs/python/CMakeLists.txt new file mode 100644 index 000000000..4c03fb698 --- /dev/null +++ b/gr-sbhs/python/CMakeLists.txt @@ -0,0 +1,94 @@ +# Copyright 2012 Free Software Foundation, Inc. +# +# This file is part of GNU Radio +# +# GNU Radio is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3, or (at your option) +# any later version. +# +# GNU Radio is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Radio; see the file COPYING. If not, write to +# the Free Software Foundation, Inc., 51 Franklin Street, +# Boston, MA 02110-1301, USA. + +######################################################################## +include(GrPython) + +GR_PYTHON_INSTALL( + FILES + __init__.py + DESTINATION ${GR_PYTHON_DIR}/gnuradio/sbhs + COMPONENT "sbhs_python" +) + +### SBHS BLOCKS ### +GR_PYTHON_INSTALL( + FILES + sbhs.py + DESTINATION ${GR_PYTHON_DIR}/gnuradio/sbhs + COMPONENT "sbhs_python" +) + + +GR_PYTHON_INSTALL( + FILES + scan_machines.py + DESTINATION ${GR_PYTHON_DIR}/gnuradio/sbhs + COMPONENT "sbhs_python" +) + +GR_PYTHON_INSTALL( + FILES + gr_sbhs.py + DESTINATION ${GR_PYTHON_DIR}/gnuradio/sbhs + COMPONENT "sbhs_python" +) + +### SBHS CONTROLLER BLOCKS ### +GR_PYTHON_INSTALL( + FILES + que.py + DESTINATION ${GR_PYTHON_DIR}/gnuradio/sbhs + COMPONENT "sbhs_python" +) + +GR_PYTHON_INSTALL( + FILES + gr_controller.py + DESTINATION ${GR_PYTHON_DIR}/gnuradio/sbhs + COMPONENT "sbhs_python" +) + +GR_PYTHON_INSTALL( + FILES + dsim_sci.py + DESTINATION ${GR_PYTHON_DIR}/gnuradio/sbhs + COMPONENT "sbhs_python" +) + + + + +######################################################################## +# Handle the unit tests +######################################################################## +if(ENABLE_TESTING) + +list(APPEND GR_TEST_PYTHON_DIRS + ${CMAKE_BINARY_DIR}/gr-sbhs/python +) +list(APPEND GR_TEST_TARGET_DEPS gnuradio-sbhs) + +include(GrTest) +file(GLOB py_qa_test_files "qa_*.py") +foreach(py_qa_test_file ${py_qa_test_files}) + get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) + GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) +endforeach(py_qa_test_file) +endif(ENABLE_TESTING) diff --git a/gr-sbhs/python/__init__.py b/gr-sbhs/python/__init__.py new file mode 100644 index 000000000..7b719281c --- /dev/null +++ b/gr-sbhs/python/__init__.py @@ -0,0 +1,54 @@ +# +# Copyright 2008,2009 Free Software Foundation, Inc. +# +# This application is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3, or (at your option) +# any later version. +# +# This application is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# + +# The presence of this file turns this directory into a Python package + +''' +This is the GNU Radio SCIMOD module. Place your Python package +description here (python/__init__.py). +''' + +# ---------------------------------------------------------------- +# Temporary workaround for ticket:181 (swig+python problem) +import sys +_RTLD_GLOBAL = 0 +try: + from dl import RTLD_GLOBAL as _RTLD_GLOBAL +except ImportError: + try: + from DLFCN import RTLD_GLOBAL as _RTLD_GLOBAL + except ImportError: + pass + +if _RTLD_GLOBAL != 0: + _dlopenflags = sys.getdlopenflags() + sys.setdlopenflags(_dlopenflags|_RTLD_GLOBAL) +# ---------------------------------------------------------------- + +# import any pure python here +# Dummy File for future use + +from scan_machines import * +print "Scanning Machines" +scan_machines() + +# ---------------------------------------------------------------- +# Tail of workaround +if _RTLD_GLOBAL != 0: + sys.setdlopenflags(_dlopenflags) # Restore original flags +# ---------------------------------------------------------------- diff --git a/gr-sbhs/python/gr_controller.py b/gr-sbhs/python/gr_controller.py new file mode 100644 index 000000000..a661e0b74 --- /dev/null +++ b/gr-sbhs/python/gr_controller.py @@ -0,0 +1,70 @@ +import gras +import numpy +from que import * + +class sbhs_controller(gras.Block): + + def __init__(self): + gras.Block.__init__(self, + name="sbhs_controller", + in_sig=[numpy.float32], + out_sig=[numpy.float32]) + + # Initializing FIFO Queues + # Remember Total_Number(Q_Push) should be equal to Total_Number(Q_Pull) + + self.q1 = Queue(3) # Queue for Error t_0 .. t_2 + self.q2 = Queue(2) # Queue for output o_0 o_1 + + # Initial queue values + self.t_1 = 0 + self.o_0 = 0 + + def set_parameters(self,p,i,d,a,b,f): + self.proportional = p + self.integtime = i + self.derivtime = d + self.delt = a #del_t + self.setpt = b #set_point + self.n = f #window + + def work(self, input_items, output_items): + + in0 = input_items[0][0] + out = output_items[0] + + # Queue structure + # --> |0|0|0| => |in0|t_1|0| + self.q1.push(self.t_1) + self.q1.push(in0) + + # Queue Structure + # --> |0|0| => |self.o_0|0| + self.q2.push(self.o_0) + + # Popping + self.t_0 = in0 + self.t_1 = self.q1.pop() + self.t_2 = self.q1.pop() + + self.o_1 = self.q2.pop() + + # Error propogation + print "E(t=t)", self.t_0 + print "E(t=t-1)", self.t_1 + print "E(t=t-2)", self.t_2 + print "-------------------" + + # Difference Equation + self.o_0 = ((self.proportional * (in0 - self.t_1) + +(self.delt/self.integtime)*in0 + +(self.derivtime/self.delt)*(in0 - 2*self.t_1 + +self.t_2 )) + self.o_1 ) * 0.92 + + out[:1] = self.o_0 + + #print output_items[0] + self.consume(0,1) # Consume from port 0 input_items + self.consume(1,1) + + self.produce(0,1) # Produce from port 0 output_items diff --git a/gr-sbhs/python/gr_sbhs.py b/gr-sbhs/python/gr_sbhs.py new file mode 100644 index 000000000..3441c1f7f --- /dev/null +++ b/gr-sbhs/python/gr_sbhs.py @@ -0,0 +1,65 @@ +import gras +import numpy +import serial +import time +from sbhs import * +from scan_machines import * + +class gr_sbhs(gras.Block): + + def __init__(self): + gras.Block.__init__(self, + name="gr_sbhs", + in_sig=[numpy.float32, numpy.float32], + out_sig=[numpy.float32]) + + # SBHS init + self.new_device = Sbhs() + self.new_device.connect(1) + self.new_device.connect_device(0) + + + def set_parameters(self,window): + self.n = window + + # Check if value of window is integral of length of input source vector + # For cases like -> input = [3 , 4, 5 ,6] & window = 3 + def isIntegralWin(self, input_item, window): + if (len(input_item) % window ): + raise Exception("Value of Window should be an integral value of length of input items") + + + def work(self, input_items, output_items): + + # if len(input_items[0]) != len(input_items[1]): + # raise Exception("Heat value vector and Fan Speed Value vector should be of equal length") + + # Assuming input_items[0] and input_items[1] have same LENGTH + for heat_items, fan_items in zip(input_items[0], input_items[1]): + + print "HEAT WRITTEN", heat_items + + # Set heat as 0 for negative values of heat + if heat_items < 0: + self.new_device.setHeat(0) + else: + self.new_device.setHeat(heat_items) + + time.sleep(0.5) + self.new_device.setFan(fan_items) + time.sleep(0.5) + + # For Zero Temperatures + if not self.new_device.getTemp(): + raise Exception("Check SBHS connection, try re-plugging it and run scan_machines.py") + + # Get temperature + output_items[0][:1] = self.new_device.getTemp() + + print "Temperature",output_items[0][:1] + + #Write a for loop for n_inputs + for i in range(len(input_items)): + self.consume(i,1) # Consume from port 0 input_items + + self.produce(0,self.n) # Produce from port 0 output_items diff --git a/gr-sbhs/python/qa_dsim.py b/gr-sbhs/python/qa_dsim.py new file mode 100755 index 000000000..3d1db0f60 --- /dev/null +++ b/gr-sbhs/python/qa_dsim.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2013 <+YOU OR YOUR COMPANY+>. +# +# This is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3, or (at your option) +# any later version. +# +# This software is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this software; see the file COPYING. If not, write to +# the Free Software Foundation, Inc., 51 Franklin Street, +# Boston, MA 02110-1301, USA. +# + +from gnuradio import gr, gr_unittest +#import mymod_swig as mymod +from dsim import dsim + + +class qa_dsim (gr_unittest.TestCase): + + def setUp (self): + self.tb = gr.top_block () + + def tearDown (self): + self.tb = None + + def test_001_t (self): + + src_data = [0]*10 + src_data1 = [1]*20 + src_data = src_data+src_data1 + + #expected_result = (-2.0, 0.0, 5.0, 8.0, 9.0, 11.0, 14.0, 18.0) + + src0 = gr.vector_source_f(src_data) + sqr = dsim() + sqr.set_parameters(2,0.5,1,.1,10,1) + + #Preload + sqr.input_config(1).preload_items = 1 + dst = gr.vector_sink_f() + + self.tb.connect(src0, (sqr,0)) # src0(vector_source) -> sqr_input_0 + self.tb.connect((sqr,0), (sqr,1)) # sqr_output_0 -> sqr_input_1 + self.tb.connect(sqr,dst) # sqr_output_0 -> dst (vector_source) + + self.tb.run() + + result_data = dst.data() + + + import matplotlib.pyplot as plt + plt.plot(result_data) + #print "result", result_data + plt.show() + #self.assertFloatTuplesAlmostEqual(expected_result, result_data, 6) + + +if __name__ == '__main__': + gr_unittest.main() + #gr_unittest.run(qa_dsim, "qa_dsim.xml") diff --git a/gr-sbhs/python/que.py b/gr-sbhs/python/que.py new file mode 100644 index 000000000..f5031a131 --- /dev/null +++ b/gr-sbhs/python/que.py @@ -0,0 +1,35 @@ +# Data Acquisition list based queue + +class Queue: + """A sample implementation of a First-In-First-Out + data structure.""" + def __init__(self, length): + + # Initializes with empty zeros + self.queue = [0] * length + self.length = length + + def push(self,obj): + if len(self.queue) < self.length: + self.queue.append(obj) + else: + print "Queue full" + ### To discard first in queue and append obj anyway ### + #self.queue.pop(0) + #self.queue.append(obj) + def pop(self): + try: + return (self.queue.pop(0)) + except: + print "queue empty" + + def size(self): + return len(self.queue) + + def discard(self): + self.queue=[] + + def flush(self): + self.return_queue = self.queue + self.queue = [] + return(self.return_queue) diff --git a/gr-sbhs/python/sbhs.py b/gr-sbhs/python/sbhs.py new file mode 100755 index 000000000..b1ff44933 --- /dev/null +++ b/gr-sbhs/python/sbhs.py @@ -0,0 +1,201 @@ +import serial +import os +from time import localtime, strftime, sleep + +MAP_FILE = './map_machine_ids.txt' +#MAP_FILE = '/var/sbhspyserver/sbhshw/map_machine_ids.txt' +LOG_FILE = '/var/sbhspylog/sbhserr.log' + +OUTGOING_MACHINE_ID = 252 +INCOMING_FAN = 253 +INCOMING_HEAT = 254 +OUTGOING_TEMP = 255 + +MAX_HEAT = 100 +MAX_FAN = 100 + +class Sbhs: + """ This is the Single Board Heater System class """ + + def __init__(self): + # status of the board + # 0 = not connected + # 1 = connected + self.machine_id = -1 + self.device_num = -1 + self.boardcon = False + self.status = 0 + + def connect(self, machine_id): + """ Open a serial connection via USB to the SBHS using the machine id """ + # check for valid machine id number + try: + self.machine_id = int(machine_id) + except: + print 'Invalid machine id specified' + return False + + # get the usb device file from the machine map file + try: + map_file = open(MAP_FILE, 'r') + usb_device_file = False + for mapping_str in map_file.readlines(): + mapping = mapping_str.split('=') + # if mapping for the machine id found set the usb device file and break out of loop + if mapping[0] == str(self.machine_id): + usb_device_file = mapping[1].strip() + break + # reached end of file and check if machine id entry is present in the machine map file + map_file.close() + if not usb_device_file: + print 'Error: cannot locate the USB device in the map table for machine id %d' % self.machine_id + self.log('cannot locate the USB device in the map table for machine id %d' % self.machine_id, 'ERROR') + return False + except: + map_file.close() + print 'Error: cannot get the USB device path for the machine id %d' % self.machine_id + self.log('cannot get the USB device path for the machine id %d' % self.machine_id, 'ERROR') + return False + + # check if SBHS device is connected + if not os.path.exists(usb_device_file): + print 'SBHS device file ' + usb_device_file + ' does not exists' + self.log('SBHS device file ' + usb_device_file + ' does not exists', 'ERROR') + return False + try: + self.boardcon = serial.Serial(port=usb_device_file, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=2) + self.status = 1 + return True + except: + print 'Error: cannot connect to machine id %d' % self.machine_id + self.log('cannot connect to machine id %d' % self.machine_id, 'ERROR') + self.machine_id = -1 + self.device_num = -1 + self.boardcon = False + self.status = 0 + return False + + def connect_device(self, device_num): + """ Open a serial connection via USB to the SBHS using USB Device Number""" + # check for valid device number + try: + self.device_num = int(device_num) + except: + print 'Invalid device number specified' + return False + + usb_device_file = '/dev/ttyUSB%d' % self.device_num + # check if SBHS device is connected + if not os.path.exists(usb_device_file): + print 'SBHS device file ' + usb_device_file + ' does not exists' + self.log('SBHS device file ' + usb_device_file + ' does not exists', 'ERROR') + return False + try: + self.boardcon = serial.Serial(port=usb_device_file, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=2) + self.machine_id = self.getMachineId() + return True + except: + print 'Error: cannot connect to device %s' % usb_device_file + self.log('cannot connect to device %s' % usb_device_file, 'ERROR') + return False + + def setHeat(self, val): + """ Set the heat """ + if val > MAX_HEAT or val < 0: + print 'Error: heat value cannot be more than %d' % MAX_HEAT + return False + + try: + self._write(chr(INCOMING_HEAT)) + self._write(chr(val)) + return True + except: + print 'Error: cannot set heat for machine id %d' % self.machine_id + self.log('cannot set heat for machine id %d' % self.machine_id, 'ERROR') + return False + + def setFan(self, val): + """ Set the fan """ + if val > MAX_FAN or val < 0: + print 'Error: fan value cannot be more than %d' % MAX_FAN + return False + try: + self._write(chr(INCOMING_FAN)) + self._write(chr(val)) + return True + except: + print 'Error: cannot set fan for machine id %d' % self.machine_id + self.log('cannot set fan for machine id %d' % self.machine_id, 'ERROR') + return False + + def getTemp(self): + """ Get the temperature """ + try: + self.boardcon.flushInput() + self._write(chr(OUTGOING_TEMP)) + temp = ord(self._read(1)) + (0.1 * ord(self._read(1))) + return temp + except: + print 'Error: cannot read temperature from machine id %d' % self.machine_id + self.log('cannot read temperature from machine id %d' % self.machine_id, 'ERROR') + return 0.0 + + def getMachineId(self): + """ Get machine id from the device """ + try: + self.boardcon.flushInput() + self._write(chr(OUTGOING_MACHINE_ID)) + sleep(0.5) # sleep before reading machine id + machine_id = ord(self._read(1)) + return machine_id + except: + print 'Error: cannot read machine id from %s' % self.boardcon.port + self.log('cannot read machine id from %s' % self.boardcon.port, 'ERROR') + return -1 + + def disconnect(self): + """ Reset the board fan and heat values and close the USB connection """ + try: + self.boardcon.close() + self.boardcon = False + self.status = 0 + return True + except: + print 'Error: cannot close connection to the machine' + self.log('cannot close connection to the machine', 'ERROR') + return False + + def reset_board(self): + self.setFan(100) + self.setHeat(0) + + def _read(self, size): + try: + data = self.boardcon.read(size) + return data + except: + print 'Error: cannot read from machine id %d' % self.machine_id + self.log('cannot read from machine id %d' % self.machine_id, 'ERROR') + raise Exception + + def _write(self, data): + try: + self.boardcon.write(data) + return True + except: + print 'Error: cannot write to machine id %d' % self.machine_id + self.log('cannot write to machine id %d' % self.machine_id, 'ERROR') + raise Exception + + def log(self, msg, level): + try: + errfile = open(LOG_FILE, 'a') # open error log file in append mode + if not errfile: + return + log_msg = '%s %s %s\n' %(level, strftime('%d:%m:%Y %H:%M:%S', localtime()), msg) + errfile.write(log_msg) + errfile.close() + return + except: + return + diff --git a/gr-sbhs/python/scan_machines.py b/gr-sbhs/python/scan_machines.py new file mode 100755 index 000000000..db194e28b --- /dev/null +++ b/gr-sbhs/python/scan_machines.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +import sbhs +import os +import sys + +def scan_machines(): + # erase the old map_machine_ids.txt file + try: + file('map_machine_ids.txt', 'w').close() + except: + print 'Failed to create machine map file file' + sys.exit(1) + + # open the map_machine_ids file for writing + try: + map_machine_file = file('map_machine_ids.txt', 'w') + except: + print 'Failed to create machine map file file' + sys.exit(1) + + # get list of device file names that start with ttyUSB* in the /dev folder + device_files = [] + device_files += [each for each in os.listdir('/dev') if each.startswith('ttyUSB')] + + # if no device filename found then exit + if not device_files: + print 'No USB device found in /dev folder' + sys.exit(1) + + for device in device_files: + s = sbhs.Sbhs() + # getting the number from the device filename + dev_id = device[6:] + try: + dev_id = int(dev_id) + except: + print 'Invalid device name /dev/%s' % device + continue + # connect to device + res = s.connect_device(dev_id) + if not res: + print 'Cannot connect to /dev/%s' % device + s.disconnect() + continue + # get the machine id from the device + machine_id = s.getMachineId() + if machine_id < 0: + print 'Cannot get machine id from /dev/%s' % device + s.disconnect() + continue + print 'Found SBHS device /dev/%s with machine id %d' % (device, machine_id) + map_str = "%d=/dev/%s\n" % (machine_id, device) + map_machine_file.write(map_str) + + #if __name__ == 'main': + #print 'Done. Exiting...' + map_machine_file.close() + #sys.exit(1) + diff --git a/gr-sbhs/python/testing.py b/gr-sbhs/python/testing.py new file mode 100755 index 000000000..a71655b40 --- /dev/null +++ b/gr-sbhs/python/testing.py @@ -0,0 +1,60 @@ +#!/usr/bin/python -tt + +import serial +import time +from time import sleep + +ser = serial.Serial('/dev/ttyUSB0', baudrate=9600, timeout=1) +ser.open() + + +from time import sleep + +import urllib +import urllib2 +from sbhs import * +#from bottle import * +from scan_machines import * + + +new_device = Sbhs() +new_device.connect(252) +new_device.connect_device(0) + + +for i in range(10): + #new_device.setHeat(10) + #new_device.setFan(30) + f=new_device.getTemp() + print f + time.sleep(3) +ser.close() +#f = 10 + +#@route('/temp') +#def hello(): +# return str(f) +#run(host='localhost', port=8080, debug=True) +''' +#writing to google app-engine + data = {} + data['temp'] = '30'#float value not int + data['heat'] = '200' + data['fan'] = '100' + url_val = urllib.urlencode(data) + print url_val + + url = 'http://remote-cloudlabs.appspot.com/hello' + full_url = url + '?' + url_val + data = urllib2.urlopen(full_url) + +#reading from url + req = urllib2.Request('http://remote-cloudlabs.appspot.com/display') + response = urllib2.urlopen(req) + data = response.read() + print data + + + time.sleep(10) + +''' |