Advertisement
Guest User

Untitled

a guest
Jun 19th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 25.90 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. import sys, os
  4. import serial
  5. import time, datetime
  6. import threading, thread
  7. import socket
  8. from collections import deque
  9. import random
  10. import pyaudio
  11. import math
  12. import struct
  13.  
  14. ##############################################################################
  15. #  pyRadMon - logger for Geiger counters                                     #
  16. #  Original Copyright 2013 by station pl_gdn_1                               #
  17. #  Copyright 2014 by Auseklis Corporation, Richmond, Virginia, U.S.A.        #
  18. #                                                                            #
  19. #  This file is part of The PyRadMon Project                                 #
  20. #  https://sourceforge.net/p/pyradmon                                        #
  21. #                                                                            #
  22. #  PyRadMon is free software: you can redistribute it and/or modify it under #
  23. #  the terms of the GNU General Public License as published by the Free      #
  24. #  Software Foundation, either version 3 of the License, or (at your option) #
  25. #  any later version.                                                        #
  26. #                                                                            #
  27. #  PyRadMon is distributed in the hope that it will be useful, but WITHOUT   #
  28. #  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or     #
  29. #  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for #
  30. #  more details.                                                             #
  31. #                                                                            #
  32. #  You should have received a copy of the GNU General Public License         #
  33. #  along with PyRadMon.  If not, see <http://www.gnu.org/licenses/>.         #
  34. #                                                                            #
  35. #  @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>                     #
  36. ##############################################################################
  37. #  version is a.b.c, change in a or b means new functionality/bugfix,        #
  38. #  change in c = bugfix                                                      #
  39. #  do not uncomment line below, it's currently used in HTTP headers          #
  40. VERSION="1.1.9"
  41. #  To see your online los, report a bug or request a new feature, please     #
  42. #  visit http://www.radmon.org and/or https://sourceforge.net/p/pyradmon     #
  43. ##############################################################################
  44.  
  45.  
  46. ##############################################################################
  47. # Part 1 - configuration procedures
  48. #
  49. # Read configuration from file + constants definition
  50. ##############################################################################
  51. class config():
  52.     # used as enums
  53.     UNKNOWN=0
  54.     DEMO=1
  55.     MYGEIGER=2
  56.     GMC=3
  57.     NETIO=4
  58.     AUDIO=5
  59.  
  60.     def __init__(self):
  61.         # define constants
  62.         self.CONFIGFILE="config.txt"
  63.         self.UNKNOWN=0
  64.         self.DEMO=1
  65.         self.MYGEIGER=2
  66.         self.GMC=3
  67.         self.NETIO=4
  68.         self.AUDIO=5
  69.  
  70.         self.user="not_set"
  71.         self.password="not_set"
  72.  
  73.         self.portName=None
  74.         self.portSpeed=2400
  75.         self.timeout=40 # not used for now
  76.         self.protocol=self.UNKNOWN
  77.         self.deviceIndex=0
  78.  
  79.     def readConfig(self):
  80.         print "Reading configuration:\r\n\t"
  81.         # if file is present then try to read configuration from it
  82.         try:
  83.             f = open(self.CONFIGFILE)
  84.             line=" "
  85.             # analyze file line by line, format is parameter=value
  86.             while (line):
  87.                 line=f.readline()
  88.                 params=line.split("=")
  89.  
  90.                 if len(params)==2:
  91.                     parameter=params[0].strip().lower()
  92.                     value=params[1].strip()
  93.                    
  94.                     if parameter=="user":
  95.                         self.user=value
  96.                         print "\tUser name configured\r\n\t"
  97.  
  98.                     elif parameter=="password":
  99.                         self.password=value
  100.                         print "\tPassword configured\r\n\t"
  101.  
  102.                     elif parameter=="serialport":
  103.                         self.portName=value
  104.                         print "\tSerial port name configured\r\n\t"
  105.  
  106.                     elif parameter=="speed":
  107.                         self.portSpeed=int(value)
  108.                         print "\tSerial port speed configured\r\n\t"
  109.                            
  110.                     elif parameter=="device":
  111.                         self.deviceIndex=int(value)
  112.                         print "\tDevice number configured\r\n\t"
  113.  
  114.                     elif parameter=="protocol":
  115.                         value=value.lower()
  116.                         if value=="mygeiger":
  117.                             self.protocol=self.MYGEIGER
  118.                         elif value=="demo":
  119.                             self.protocol=self.DEMO
  120.                         elif value=="gmc":
  121.                             self.protocol=self.GMC
  122.                         elif value=="netio":
  123.                             self.protocol=self.NETIO
  124.                         elif value=="audio":
  125.                             self.protocol=self.AUDIO
  126.  
  127.                     if self.protocol!=self.UNKNOWN:
  128.                         print "\tProtocol configured\r\n\t"
  129.                 # end of if
  130.             # end of while
  131.             f.close()
  132.         except Exception as e:
  133.             print "\tFailed to read configuration file:\r\n\t",str(e), "\r\nExiting\r\n"
  134.             exit(1)
  135.         # well done, configuration is ready to use
  136.         print ""
  137.  
  138. ################################################################################
  139. # Part 2 - Geiger counter communication
  140. #
  141. # It should be easy to add different protocol by simply
  142. # creating new class based on baseGeigerCommunication, as it's done in
  143. # classes Demo and myGeiger
  144. ################################################################################
  145.  
  146. class baseGeigerCommunication(threading.Thread):
  147.  
  148.     def __init__(self, cfg):
  149.         super(baseGeigerCommunication, self).__init__()
  150.         self.sPortName=cfg.portName
  151.         self.sPortSpeed=cfg.portSpeed
  152.         self.timeout=cfg.timeout
  153.         self.stopwork=0
  154.         self.queue=deque()
  155.         self.queueLock=0
  156.         self.is_running=1
  157.  
  158.     def run(self):
  159.         try:
  160.             print "Gathering data started => geiger 1\r\n"
  161.             self.serialPort = serial.Serial(self.sPortName, self.sPortSpeed, timeout=1)
  162.             self.serialPort.flushInput()
  163.            
  164.             self.initCommunication()
  165.  
  166.             while(self.stopwork==0):
  167.                 result=self.getData()
  168.                 while (self.queueLock==1):
  169.                     print "Geiger communication: quene locked! => geiger 1\r\n"
  170.                     time.sleep(0.5)
  171.                 self.queueLock=1
  172.                 self.queue.append(result)
  173.                 self.queueLock=0
  174.                 print "Geiger sample => geiger 1:\tCPM =",result[0],"\t",str(result[1])
  175.                 print "hereB"
  176.                
  177.  
  178.             self.serialPort.close()
  179.             print "Gathering data from Geiger stopped => geiger 1\r\n"
  180.         except serial.SerialException as e:
  181.             print "Problem with serial port => geiger 1:\r\n\t", str(e),"\r\nExiting\r\n"
  182.             self.stop()
  183.             sys.exit(1)
  184.  
  185.     def initCommunication(self):
  186.         print "Initializing geiger communication => geiger 1\r\n"
  187.  
  188.     def sendCommand(self, command):
  189.         self.serialPort.flushInput()
  190.         self.serialPort.write(command)
  191.         # assume that device responds within 0.5s
  192.         time.sleep(0.5)
  193.         response=""
  194.         while (self.serialPort.inWaiting()>0 and self.stopwork==0):
  195.             response = response + self.serialPort.read()
  196.         return response
  197.  
  198.     def getData(self):
  199.         cpm=25
  200.         utcTime=datetime.datetime.utcnow()
  201.         data=[cpm, utcTime]
  202.         return data
  203.  
  204.     def stop(self):
  205.         self.stopwork=1
  206.         self.queueLock=0
  207.         self.is_running=0
  208.  
  209.     def getResult(self):
  210.         # check if we have some data in queue
  211.         if len(self.queue)>0:
  212.  
  213.             # check if it's safe to process queue
  214.             while (self.queueLock==1):
  215.                 print "getResult: quene locked! => geiger 1\r\n"
  216.                 time.sleep(0.5)
  217.  
  218.             # put lock so measuring process will not interfere with queue,
  219.             # processing should be fast enought to not break data acquisition from geiger
  220.             self.queueLock=1
  221.  
  222.             cpm=0
  223.             # now get sum of all CPM's
  224.             for singleData in self.queue:
  225.                 cpm=cpm+singleData[0]
  226.  
  227.             # and divide by number of elements
  228.             # to get mean value, 0.5 is for rounding up/down
  229.             cpm=int( ( float(cpm) / len(self.queue) ) +0.5)
  230.             # report with latest time from quene
  231.             utcTime=self.queue.pop()[1]
  232.  
  233.             # clear queue and remove lock
  234.             self.queue.clear()
  235.             self.queueLock=0
  236.  
  237.             data=[cpm, utcTime]
  238.         else:
  239.             # no data in queue, return invalid CPM data and current time
  240.             data=[-1, datetime.datetime.utcnow()]
  241.  
  242.         return data
  243.  
  244. class Demo(baseGeigerCommunication):
  245.  
  246.     def run(self):
  247.         print "Gathering data started => geiger 1\r\n"
  248.  
  249.         while(self.stopwork==0):
  250.             result=self.getData()
  251.             while (self.queueLock==1):
  252.                 print "Geiger communication: quene locked! => geiger 1\r\n"
  253.                 time.sleep(0.5)
  254.             self.queueLock=1
  255.             self.queue.append(result)
  256.             self.queueLock=0
  257.             print "Geiger sample => geiger 1:\t",result,"\r\n"
  258.            
  259.            
  260.             outputTxtName = "data-dosi.txt"
  261.             outputFile = open(outputTxtName, "a")
  262.             outputFile.write(str(result[0]) + "," + str(result[1]) + "\n")
  263.             outputFile.close()
  264.  
  265.         print "Gathering data from Geiger stopped => geiger 1\r\n"
  266.  
  267.     def getData(self):
  268.         for i in range(0,5):
  269.             time.sleep(1)
  270.         cpm=random.randint(5,40)
  271.         utcTime=datetime.datetime.utcnow()
  272.         data=[cpm, utcTime]
  273.         return data
  274.  
  275. class myGeiger(baseGeigerCommunication):
  276.  
  277.     def getData(self):
  278.         cpm=-1
  279.         try:
  280.             # wait for data
  281.             while (self.serialPort.inWaiting()==0 and self.stopwork==0):
  282.                 time.sleep(1)
  283.  
  284.             time.sleep(0.1) # just to ensure all CPM bytes are in serial port buffer
  285.             # read all available data
  286.             x=""
  287.             while (self.serialPort.inWaiting()>0 and self.stopwork==0):
  288.                 x = x + self.serialPort.read()
  289.  
  290.             if len(x)>0:
  291.                 cpm=int(x)
  292.  
  293.             utcTime=datetime.datetime.utcnow()
  294.             data=[cpm, utcTime]
  295.             return data
  296.         except Exception as e:
  297.             print "\r\nProblem in getData procedure (disconnected USB device?) => geiger 1:\r\n\t",str(e),"\r\nExiting\r\n"
  298.             self.stop()
  299.             sys.exit(1)
  300.  
  301. class gmc(baseGeigerCommunication):
  302.  
  303.     def initCommunication(self):
  304.        
  305.         print "Initializing GMC protocol communication => geiger 1\r\n"
  306.         # get firmware version
  307.         response=self.sendCommand("<GETVER>>")
  308.        
  309.         if len(response)>0:
  310.             print "Found GMC-compatible device, version => geiger 1: ", response, "\r\n"
  311.             # get serial number
  312.             # serialnum=self.sendCommand("<GETSERIAL>>")
  313.             # serialnum.int=struct.unpack('!1H', serialnum(7))[0]
  314.             # print "Device Serial Number is: ", serialnum.int
  315.             # disable heartbeat, we will request data from script
  316.             self.sendCommand("<HEARTBEAT0>>")
  317.             print "Please note data will be acquired once per 5 seconds => geiger 1\r\n"
  318.             # update the device time
  319.             unitTime=self.sendCommand("<GETDATETIME>>")
  320.             print "Unit shows time as => geiger 1: ", unitTime, "\r\n"
  321.             # self.sendCommand("<SETDATETIME[" + time.strftime("%y%m%d%H%M%S") + "]>>")
  322.             print "<SETDATETIME[" + time.strftime("%y%m%d%H%M%S") + "]>>"
  323.  
  324.         else:
  325.             print "No response from device => geiger 1\r\n"
  326.             self.stop()
  327.             sys.exit(1)
  328.  
  329.     def getData(self):
  330.         cpm=-1
  331.         try:
  332.             # wait, we want sample every 30s
  333.             for i in range(0,3):
  334.                 time.sleep(1)
  335.            
  336.             # send request
  337.             response=self.sendCommand("<GETCPM>>")
  338.            
  339.             if len(response)==2:
  340.                 # convert bytes to 16 bit int
  341.                 cpm=ord(response[0])*256+ord(response[1])
  342.             else:
  343.                 print "Unknown response to CPM request, device is not GMC-compatible? => geiger 1\r\n"
  344.                 self.stop()
  345.                 sys.exit(1)
  346.                
  347.             utcTime=datetime.datetime.utcnow()
  348.             data=[cpm, utcTime]
  349.             return data
  350.            
  351.         except Exception as e:
  352.             print "\r\nProblem in getData procedure (disconnected USB device?) => geiger 1:\r\n\t",str(e),"\r\nExiting\r\n"
  353.             self.stop()
  354.             sys.exit(1)
  355.  
  356. class netio(baseGeigerCommunication):
  357.  
  358.     def getData(self):
  359.         cpm=-1
  360.         try:
  361.             # we want data only once per 30 seconds, ignore rest
  362.             # it's averaged for 60 seconds by device anyway
  363.             for i in range(0,30):
  364.                 time.sleep(1)
  365.  
  366.             # wait for data, should be already there (from last 30s)
  367.             while (self.serialPort.inWaiting()==0 and self.stopwork==0):
  368.                 time.sleep(0.5)
  369.            
  370.             time.sleep(0.1) # just to ensure all CPM bytes are in serial port buffer
  371.             # read all available data
  372.  
  373.             # do not stop receiving unless it ends with \r\n
  374.             x=""
  375.             while ( x.endswith("\r\n")==False and self.stopwork==0):
  376.                 while ( self.serialPort.inWaiting()>0 and self.stopwork==0 ):
  377.                     x = x + self.serialPort.read()
  378.  
  379.             # if CTRL+C pressed then x can be invalid so check it
  380.             if x.endswith("\r\n"):
  381.                 # we want only latest data, ignore older
  382.                 tmp=x.splitlines()
  383.                 x=tmp[len(tmp)-1]
  384.                 cpm=int(x)
  385.            
  386.             utcTime=datetime.datetime.utcnow()
  387.             data=[cpm, utcTime]
  388.             return data
  389.  
  390.         except Exception as e:
  391.             print "\r\nProblem in getData procedure (disconnected USB device?) => geiger 1:\r\n\t",str(e),"\r\nExiting\r\n"
  392.             self.stop()
  393.             sys.exit(1)
  394.  
  395.     def initCommunication(self):
  396.         print "Initializing NetIO => geiger 1\r\n"
  397.         # send "go" to start receiving CPM data
  398.         response=self.sendCommand("go\r\n")
  399.         print "Please note data will be acquired once per 30 seconds => geiger 1\r\n"
  400.  
  401. ################################################################################
  402. # Part 2b - audio geiger handeler
  403. ################################################################################
  404. INITIAL_TAP_THRESHOLD = 0.010
  405. FORMAT = pyaudio.paInt16
  406. SHORT_NORMALIZE = (1.0/32768.0)
  407. CHANNELS = 2
  408. RATE = 44100  
  409. INPUT_BLOCK_TIME = 0.05
  410. INPUT_FRAMES_PER_BLOCK = int(RATE*INPUT_BLOCK_TIME)
  411. # if the noise was longer than this many blocks, it's not a 'tap'
  412. MAX_TAP_BLOCKS = 0.15/INPUT_BLOCK_TIME
  413.    
  414. def get_rms( block ):
  415.     # RMS amplitude is defined as the square root of the
  416.     # mean over time of the square of the amplitude.
  417.     # so we need to convert this string of bytes into
  418.     # a string of 16-bit samples...
  419.  
  420.     # we will get one short out for each
  421.     # two chars in the string.
  422.     count = len(block)/2
  423.     format = "%dh"%(count)
  424.     shorts = struct.unpack( format, block )
  425.  
  426.     # iterate over the block.
  427.     sum_squares = 0.0
  428.     for sample in shorts:
  429.         # sample is a signed short in +/- 32768.
  430.         # normalize it to 1.0
  431.         n = sample * SHORT_NORMALIZE
  432.         sum_squares += n*n
  433.  
  434.     return math.sqrt( sum_squares / count )
  435.  
  436. class audioCommunication(threading.Thread):
  437.  
  438.     def __init__(self, cfg):
  439.         super(audioCommunication, self).__init__()
  440.         self.initCommunication()
  441.         self.timeout=cfg.timeout
  442.         self.stopwork=0
  443.         self.queue=deque()
  444.         self.queueLock=0
  445.         self.is_running=1
  446.         self.pa = pyaudio.PyAudio()
  447.         self.device_index = cfg.deviceIndex
  448.         self.tap_threshold = INITIAL_TAP_THRESHOLD
  449.         self.noisycount = 0
  450.        
  451.     def run(self):
  452.         try:
  453.             print "Gathering data started => geiger 1\r\n"
  454.             while(self.stopwork==0):
  455.                 result=self.getData()
  456.                 while (self.queueLock==1):
  457.                     print "Geiger communication: quene locked! => geiger 1\r\n"
  458.                     time.sleep(0.5)
  459.                 self.queueLock=1
  460.                 self.queue.append(result)
  461.                 self.queueLock=0
  462.                 print "Geiger sample => geiger 1:\tCPM =",result[0],"\t",str(result[1]),"\r\n"
  463.                 print "a"
  464.  
  465.             print "Gathering data from Geiger stopped => geiger 1\r\n"
  466.             self.pa.terminate()
  467.         except Exception as e:
  468.             print "Problem with audio port => geiger 1:\r\n\t", str(e),"\r\nExiting\r\n"
  469.             self.stop()
  470.             sys.exit(1)
  471.  
  472.     def initCommunication(self):
  473.         print "Initializing audio communication => geiger 1\r\n"
  474.  
  475.     def getData(self):
  476.         self.stream = self.pa.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, input_device_index = self.device_index, frames_per_buffer = INPUT_FRAMES_PER_BLOCK)
  477.         for i in range(600):
  478.             try:
  479.                 block = self.stream.read(INPUT_FRAMES_PER_BLOCK)
  480.  
  481.             except Exception as ex:
  482.                 print "Problem with audio port => geiger 1:\r\n\t", str(ex),"\r\nExiting\r\n"
  483.                 self.stream.stop_stream()
  484.                 self.stream.close()
  485.                 self.stop()
  486.                 sys.exit(1)
  487.  
  488.             amplitude = get_rms( block )
  489.             if amplitude > self.tap_threshold:
  490.                 # noisy block
  491.                 self.noisycount += 1
  492.  
  493.         self.stream.stop_stream()
  494.         self.stream.close()
  495.  
  496.         if self.noisycount >= 0:
  497.             cpm = self.noisycount * ( 60 / 30 )
  498.             self.noisycount = 0
  499.            
  500.         utcTime=datetime.datetime.utcnow()
  501.         data=[cpm, utcTime]
  502.         return data
  503.  
  504.     def stop(self):
  505.         self.stopwork=1
  506.         self.queueLock=0
  507.         self.is_running=0
  508.  
  509.     def getResult(self):
  510.         # check if we have some data in queue
  511.         if len(self.queue)>0:
  512.  
  513.             # check if it's safe to process queue
  514.             while (self.queueLock==1):
  515.                 print "getResult: quene locked! => geiger 1\r\n"
  516.                 time.sleep(0.5)
  517.  
  518.             # put lock so measuring process will not interfere with queue,
  519.             # processing should be fast enought to not break data acquisition from geiger
  520.             self.queueLock=1
  521.  
  522.             cpm=0
  523.             # now get sum of all CPM's
  524.             for singleData in self.queue:
  525.                 cpm=cpm+singleData[0]
  526.  
  527.             # and divide by number of elements
  528.             # to get mean value, 0.5 is for rounding up/down
  529.             cpm=int( ( float(cpm) / len(self.queue) ) +0.5)
  530.             # report with latest time from quene
  531.             utcTime=self.queue.pop()[1]
  532.  
  533.             # clear queue and remove lock
  534.             self.queue.clear()
  535.             self.queueLock=0
  536.  
  537.             data=[cpm, utcTime]
  538.         else:
  539.             # no data in queue, return invalid CPM data and current time
  540.             data=[-1, datetime.datetime.utcnow()]
  541.  
  542.         return data
  543.  
  544. ################################################################################
  545. # Part 3 - Web server communication
  546. ################################################################################
  547. class webCommunication():
  548.     HOST="www.radmon.org"
  549.     #HOST="127.0.0.1" # uncomment this for debug purposes on localhost
  550.     PORT=80
  551.  
  552.     def __init__(self, mycfg):
  553.         self.user=mycfg.user
  554.         self.password=mycfg.password
  555.  
  556.     def sendSample(self, sample):
  557.  
  558.         print "Connecting to server => geiger 1\r\n"
  559.         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  560.         s.connect((self.HOST, self.PORT))
  561.  
  562.         BUFFER_SIZE=1024
  563.  
  564.         sampleCPM=sample[0]
  565.         sampleTime=sample[1]
  566.  
  567.         # format date and time as required
  568.         dtime=sampleTime.strftime("%Y-%m-%d%%20%H:%M:%S")
  569.  
  570.         url="GET /radmon.php?user="+self.user+"&password="+self.password+"&function=submit&datetime="+dtime+"&value="+str(sampleCPM)+"&unit=CPM HTTP/1.1"
  571.  
  572.         request=url+"\r\nHost: www.radmon.org\r\nUser-Agent: pyRadMon "+VERSION+"\r\n\r\n"
  573.         print "Sending average sample => geiger 1: "+str(sampleCPM)+" CPM\r\n"
  574.         #print "\r\n### HTTP Request ###\r\n"+request
  575.  
  576.         s.send(request)
  577.         data = s.recv(BUFFER_SIZE)
  578.         httpResponse=str(data).splitlines()[0]
  579.         print "Server response => geiger 1: ",httpResponse,"\r\n"
  580.  
  581.         if "incorrect login" in data.lower():
  582.             print "You are using incorrect user/password combination => geiger 1!\r\n"
  583.             geigerCommunication.stop()
  584.             sys.exit(1)
  585.            
  586.         #print "\r\n### HTTP Response ###\r\n"+data+"\r\n"
  587.         s.close
  588.  
  589. ################################################################################
  590. # Main code
  591. ################################################################################
  592. outputTxtName = "data-dosi.txt"
  593. outputFile = open(outputTxtName, "a")
  594. outputFile.write(datetime.datetime.utcnow().strftime("%y-%m-%d-%H:%M:%S") + "\n")
  595. outputFile.close()
  596.  
  597. # main loop is in while loop
  598. # check if file exists, if not, create one and exit
  599. if (os.path.isfile("config.txt")==0):
  600.     print "\tNo configuration file, creating default one.\r\n\t"
  601.  
  602.     try:
  603.         f = open("config.txt", 'w')
  604.         f.write("# Parameter names are not case-sensitive\r\n")
  605.         f.write("# Parameter values are case-sensitive\r\n")
  606.         f.write("user=test_user\r\n")
  607.         f.write("password=test_password\r\n")
  608.         f.write("# Port is usually /dev/ttyUSBx in Linux and COMx in Windows\r\n")
  609.         f.write("serialport=/dev/ttyUSB0\r\n")
  610.         f.write("speed=2400\r\n")
  611.         f.write("# Protocols: demo, mygeiger, gmc, netio, audio\r\n")
  612.         f.write("protocol=demo\r\n")
  613.         f.write("# In case of audio, input the device number here, default is 0.\r\n")
  614.         p = pyaudio.PyAudio()
  615.         info = p.get_host_api_info_by_index(0)
  616.         numdevices = info.get('deviceCount')
  617.         #for each audio device, determine if is an input or an output and add it to the appropriate list and dictionary
  618.         for i in range (0,numdevices):
  619.             if p.get_device_info_by_host_api_device_index(0,i).get('maxInputChannels')>0:
  620.                 f.write("# %d - %s \r\n"%(i,p.get_device_info_by_host_api_device_index(0,i).get('name')))
  621.         p.terminate()
  622.         f.write("device=0\r\n")
  623.         f.close()
  624.         print "\tPlease open config.txt file using text editor and update configuration.\r\n"
  625.         exit(1)
  626.     except Exception as e:
  627.         print "\tFailed to create configuration file\r\n\t",str(e)
  628.     exit(1)
  629. else:
  630.     # create and read configuration data
  631.     cfg=config()
  632.     cfg.readConfig()
  633.    
  634.     try:
  635.         # create geiger communication object
  636.         if cfg.protocol==config.MYGEIGER:
  637.             print "Using myGeiger protocol for 1 => geiger 1\r\n"
  638.             geigerCommunication=myGeiger(cfg)
  639.         elif cfg.protocol==config.DEMO:
  640.             print "Using Demo mode for 1 => geiger 1\r\n"
  641.             geigerCommunication=Demo(cfg)
  642.         elif cfg.protocol==config.GMC:
  643.             print "Using GMC protocol for 1 => geiger 1\r\n"
  644.             geigerCommunication=gmc(cfg)
  645.         elif cfg.protocol==config.NETIO:
  646.             print "Using NetIO protocol for 1 => geiger 1\r\n"
  647.             geigerCommunication=netio(cfg)
  648.         elif cfg.protocol==config.AUDIO:
  649.             print "Using audio protocol for 1 => geiger 1\r\n"
  650.             geigerCommunication = audioCommunication(cfg)
  651.         else:
  652.             print "Unknown protocol configured, can't run => geiger 1\r\n"
  653.             sys.exit(1)
  654.  
  655.         # create web server communication object
  656.         webService=webCommunication(cfg)
  657.        
  658.         # start measuring thread
  659.         geigerCommunication.start()
  660.  
  661.         # Now send data to web site every 30 seconds
  662.         while(geigerCommunication.is_running==1):
  663.             sample=geigerCommunication.getResult()
  664.  
  665.             if sample[0]!=-1:
  666.                 # sample is valid, CPM !=-1
  667.                 print "Average result => geiger 1:\tCPM =",sample[0],"\t",str(sample[1]),"\r\n"
  668.                 #outputFile.write(str(sample[0]) + "," + str(sample[1]) + "\n")
  669.                 try:
  670.                     webService.sendSample(sample)
  671.                 except Exception as e:
  672.                     print "Error communicating server => geiger 1:\r\n\t", str(e),"\r\n"
  673.  
  674.                 print "Waiting 30 seconds => geiger 1\r\n"
  675.                 # actually waiting 30x1 seconds, it's has better response when CTRL+C is used, maybe will be changed in future
  676.                 for i in range(0,30):
  677.                     time.sleep(1)
  678.             else:
  679.                 print "No samples in queue, waiting 5 seconds => geiger 1\r\n"
  680.                 for i in range(0,5):
  681.                     time.sleep(1)
  682.  
  683.     except KeyboardInterrupt as e:
  684.         print "\r\nCTRL+C pressed, exiting program\r\n\t", str(e), "\r\n"
  685.         geigerCommunication.stop()
  686.        
  687.  
  688.     except Exception as e:
  689.         print "\r\nUnhandled error\r\n\t",str(e),"\r\n"
  690.         geigerCommunication.stop()
  691.        
  692.  
  693.     geigerCommunication.stop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement