Advertisement
yOPERO

sser

Jan 24th, 2012
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.69 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # pfh 6/15/09
  4. # Starting from http://itamarst.org/writings/etech04/twisted_internet-22.html
  5. # Goal: Listen to arduino, save data in engineering units, to CSV, also present
  6. # in twisted.web or similar. Socket server?
  7. #
  8. # Design: For now, have arduino send raw ADC counts over and we'll do the
  9. # calibration - seems smarter. I can then use config file parser to move
  10. # all the constants into a config file.
  11. #
  12. # I really want something like rrdtool-based graphs with different timescales.
  13. # Maybe graphite?
  14. # http://somic.org/2009/05/21/graphite-rabbitmq-integration/
  15. # Or even AMQP for fun?
  16. # Serial code from http://twistedmatrix.com/projects/core/documentation/examples/gpsfix.py
  17.  
  18. from twisted.protocols.basic import LineReceiver
  19.  
  20. from twisted.internet import reactor
  21. from twisted.internet.serialport import SerialPort
  22. from twisted.web import server, resource, client
  23.  
  24. from twisted.python import usage
  25. import logging
  26. import sys
  27. import time
  28.  
  29. lastTemp = 0.0
  30. lastRH = 0.0
  31. lastTimestamp = 0
  32.  
  33. class THOptions(usage.Options):
  34.     optParameters = [
  35.         ['baudrate', 'b', 9600, 'Serial baudrate'],
  36.         ['port', 'p', 3, 'Serial port to use'],
  37.         ]
  38.  
  39. class indexPage(resource.Resource):
  40.     isLeaf = True
  41.  
  42.     def render_GET(self, request):
  43.         ccStr = ' Temp:%f Humidity:%f\n' % (lastTemp, lastRH)
  44.         return ccStr
  45.  
  46. class Echo(LineReceiver):
  47.     def processData(self, data):
  48.         """Convert raw ADC counts into SI units as per datasheets"""
  49.         # Skip bad reads
  50.         if len(data) != 2:
  51.             return
  52.  
  53.         global lastTemp, lastRH, lastTimestamp
  54.  
  55.         tempCts = int(data[0])
  56.         rhCts = int(data[1])
  57.  
  58.         rhVolts = rhCts * 0.0048828125
  59.         # 10mV/degree, 1024 count/5V
  60.         temp = tempCts * 0.48828125
  61.         # RH temp correction is -0.7% per deg C
  62.         rhcf = (-0.7 * (temp - 25.0)) / 100.0
  63.  
  64.         # Uncorrected humidity
  65.         humidity = (rhVolts * 45.25) - 42.76
  66.  
  67.         # Add correction factor
  68.         humidity = humidity + (rhcf * humidity)
  69.  
  70.  
  71.         lastTemp = tempCts
  72.         lastRH = rhCts
  73.         #lastTemp = temp
  74.         #lastRH = humidity
  75.         # Update screen now and then
  76.         if (time.time() - lastTimestamp) > 20.0:
  77.             logging.info('Temp: %f C Relative humidity: %f %%' % (temp, humidity))
  78.             logging.debug('Temp: %f counts: %d RH: %f counts: %d volts: %f' % (temp, tempCts, humidity, rhCts, rhVolts))
  79.             lastTimestamp = time.time()
  80.  
  81.         return temp, humidity
  82.  
  83.     def connectionMade(self):
  84.         logging.info('Serial connection made!')
  85.  
  86.     def lineReceived(self, line):
  87.         try:
  88.             data = line.split()
  89.             logging.debug(data)
  90.             self.processData(data)
  91.         except ValueError:
  92.             logging.error('Unable to parse data %s' % line)
  93.             return
  94.  
  95. if __name__ == '__main__':
  96.     logging.basicConfig(level=logging.INFO, \
  97.                 format='%(asctime)s %(levelname)s [%(funcName)s] %(message)s')
  98.  
  99.     o = THOptions()
  100.     try:
  101.         o.parseOptions()
  102.     except usage.UsageError, errortext:
  103.         logging.error('%s %s' % (sys.argv[0], errortext))
  104.         logging.info('Try %s --help for usage details' % sys.argv[0])
  105.         raise SystemExit, 1
  106.  
  107.     if o.opts['baudrate']:
  108.         baudrate = int(o.opts['baudrate'])
  109.  
  110.     port = o.opts['port']
  111.  
  112.     logging.debug('About to open port %s' % port)
  113.     s = SerialPort(Echo(), port, reactor, baudrate=baudrate)
  114.  
  115.     # HTTP interface
  116.     logging.debug('Setting up webserver on http://localhost:2000/')
  117.     root = indexPage()
  118.     site = server.Site(root)
  119.     reactor.listenTCP(2000, site)
  120.  
  121.     reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement