def __init__(self): self.lock = threading.Lock() self.gpio = Gpio() # init to LOW self.lock.acquire() for pin in Reader.selector_pins: self.gpio.pinMode(pin, self.gpio.OUTPUT) self.gpio.digitalWrite(pin, self.gpio.LOW) self.lock.release()
def __init__(self, sender): threading.Thread.__init__(self) self.sender = sender self.gpio = Gpio() # init to LOW for pin in SensingThread.selector_pins: self.gpio.pinMode(pin, self.gpio.OUTPUT) self.gpio.digitalWrite(pin, self.gpio.LOW)
def __init__(self): self.temp = 0 self.output_pins = [24, 25, 26, 27] self.IOLock = threading.Lock() # mutual lock for R/W control self.gpio = Gpio() # initialize GPIO controller # setup output pins self.IOLock.acquire() for pin in self.output_pins: self.gpio.pinMode(pin, self.gpio.OUTPUT) self.gpio.digitalWrite(pin, self.gpio.LOW) self.IOLock.release()
def __init__(self): # Parent class constructor Thread.__init__(self) # Assign GPIO pins that controls MUX, LSB to MSB self.gpio_pins = [24, 25, 26, 27] self.gpio = Gpio() # Set GPIO pins to output try: for pin in self.gpio_pins: self.gpio.pinMode(pin, self.gpio.OUTPUT) except Exception as e: logger.error("Error setting GPIO pin, reason %s" % e.message) print "Error setting GPIO pin %d, reason %s" % e.message # Use A0 port self.adc_raw = "/sys/bus/iio/devices/iio:device0/in_voltage0_raw" self.adc_scale = "/sys/bus/iio/devices/iio:device0/in_voltage_scale" self.sensor_names = ['Temp', 'SN1', 'SN2', 'SN3', 'SN4', 'PM25'] # Use a dict to store sensor output, the format is: # { "time": [time stamp], # [sensor1 name]: [sensor1 output], # ... # [sensor6 name]: [sensor6 output]} self.sensor_output = {} # Create a lock to protect sensor output. That is, when updating the result, lock it on to prevent it from being # read at the same time; similarly, when reading the result, lock it on to prevent it from being updated. self.sensor_output_lock = Lock() #스레드의 값이 이상하게 나오는 것을 막기 위해 Lock() self.db_conn = sqlite3.connect("air_pollution_data.db") self.db_cur = self.db_conn.cursor() for sensor_name in self.sensor_names: self.db_cur.execute( "CREATE TABLE IF NOT EXISTS %s (time int PRIMARY KEY NOT NULL, value real)" % sensor_name)
def __init__(self, database_name="air_pollution_data.db"): # Parent class constructor Thread.__init__(self) # Assign GPIO pins that controls MUX, LSB to MSB self.gpio_pins = [24, 25, 26, 27] self.gpio = Gpio() # Set GPIO pins to output try: for pin in self.gpio_pins: self.gpio.pinMode(pin, self.gpio.OUTPUT) except Exception as e: logger.error("Error setting GPIO pin {}, reason {}".format( pin, e.message)) # Use A0 port self.adc_raw = "/sys/bus/iio/devices/iio:device0/in_voltage0_raw" self.adc_scale = "/sys/bus/iio/devices/iio:device0/in_voltage_scale" self.sensor_names = ['temp', 'CO', 'NO2', 'SO2', 'O3', 'PM25'] # Use a dict to store sensor output, the format is: # { "time": [time stamp], # [sensor1 name]: [sensor1 output], # ... # [sensor6 name]: [sensor6 output]} self.sensor_output = {} # Create a lock to protect sensor output. That is, when updating the result, lock it on to prevent it from being # read at the same time; similarly, when reading the result, lock it on to prevent it from being updated. self.sensor_output_lock = Lock() # Here we have a decision to make. I decide to let sensor server write sensor outputs to the local database. Of # course we can do so in a different thread either in a synchronous way or in an asynchronous way. If we do it # with a synchronous approach, we need to use locks to keep synchronization; if we do it with an asynchronous # solution, then SQLite3 is already an asynchronous module and I don't see good reason of adding another layer # of complexity. Perhaps the most reasonable way would be specifying the database in the main thread and then # send it to the sensor server thread. self.database_name = database_name try: # Create the database file and get the connection object. self.db_conn = sqlite3.connect(self.database_name) # Get database cursor from the connection object. self.db_cur = self.db_conn.cursor() except Exception as e: logger.error("Error connecting the database {}, reason: {}".format( self.database_name, e.message)) self.__del__() # Create a 'history' table for history data. # TIME | Temp | SN1 | SN2 | SN3 | SN4 | PM25 # ----------------------------------------------- # int | real | real | real | real | real | real self.db_cur.execute(( "CREATE TABLE IF NOT EXISTS history (time int PRIMARY KEY NOT NULL," " {0} real, {1} real, {2} real, {3} real, {4} real, {5} real)" ).format(self.sensor_names[0], self.sensor_names[1], self.sensor_names[2], self.sensor_names[3], self.sensor_names[4], self.sensor_names[5])) # Commit the changes. When a database is accessed by multiple connections, and one of the processes modifies the # database, the SQLite database is locked until that transaction is committed. The timeout parameter specifies # how long the connection should wait for the lock to go away until raising an exception. The default for the # timeout parameter is 5.0 (five seconds). self.db_conn.commit()
args = parser.parse_args() # Create a BT server uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee" service_name = "BTServer" server = BTServer(uuid, service_name) # Create the server thread and run it server_thread = Thread(target=asyncore.loop, name="BT Server Thread") server_thread.daemon = True server_thread.start() # epochtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S') #(int)(time()) neo = Gpio() gpiopins = [8, 9, 10, 11] gpio = Gpio() pinnum = [0, 0, 0, 0] # Set GPIO pins to output # try: # for pin in gpiopins: # gpio.pinMode(pin, gpio.OUTPUT) # except Exception as e: # logger.error("Error : GPIO pin {} .reason {}".format(pin, e.message)) # Blink example for i in range(4):
from neo import Gpio # import Gpio library from time import sleep # import sleep to wait for blinks neo = Gpio() #create new Neo object pinOne = 25 #pin to use neo.pinMode(pinOne, neo.OUTPUT)# Use innerbank pin 2 and set it as output either 0 (neo.INPUT) or 1 (neo.OUTPUT) #Blink example while True: #Do for five times neo.digitalWrite(pinOne,neo.HIGH) #write high value to pin sleep(1)# wait one second neo.digitalWrite(pinOne,neo.LOW) #write low value to pin sleep(1)# wait one second
def getSamsungCode(self): # Learning mode feedback led pinLED = 26 # IR receiver pinIR = 25 command_length_samasung = 65 neo = Gpio() neo.pinMode(pinIR, neo.INPUT) neo.pinMode(pinLED, neo.OUTPUT) neo.digitalWrite(pinLED, neo.HIGH) sample_number = 0 # Compute the average result after MAX_SAMPLES bits_sum = [0] * 32 MAX_SAMPLES = 3 while True: # stop the receiver after MAX_SAMPLES if sample_number == MAX_SAMPLES: for x in range(0, len(bits_sum)): bits_sum[x] = bits_sum[x] / (MAX_SAMPLES * 1.0) break value = 1 # Loop until get IR data time_to_live = 45000 while value and time_to_live: value = neo.digitalRead(pinIR) time_to_live -= 1 if time_to_live == 0: neo.digitalWrite(pinLED, neo.LOW) return "" # Grab the start time of the command startTime = datetime.now() # Used to buffer the command pulses command = [] # The end of the "command" happens when we read more than # a certain number of 1s (1 is off for the IR receiver) numOnes = 0 # Used to keep track of transitions from 1 to 0 previousVal = 0 while True: if value != previousVal: # The value has changed, so calculate the length of this run now = datetime.now() pulseLength = now - startTime startTime = now command.append((previousVal, pulseLength.microseconds)) # print str(previousVal) + " " + str(pulseLength.microseconds) #if len(command) == command_length_samasung: # break if value: numOnes = numOnes + 1 else: numOnes = 0 if numOnes > 100: break #if numOnes > 300: # break previousVal = value value = neo.digitalRead(pinIR) # A Sony IR signal starts with 2400 microseconds on and 600 microseconds off; # that's the first wide pulse. A "1" bit is transmitted with 1200 microseconds on and 600 microseconds off, # while a "0" bit is transmitted with 600 microseconds on and 600 microseconds off. # (This encoding is also called SIRC or SIRCS encoding.) # Chop the header of the received IR signal # print command command = command[2:] command = command[:64] #print "Command length: " + str(len(command)) # Establish the payload of the received IR signal binaryString = "".join( map(lambda x: "1" if x[1] > 1080 else "0", filter(lambda x: x[0] == 1, command))) # The length of the payload, according to SONY protocol is 12 bits; skip otherwise #print len(binaryString) if len(binaryString) != 32: continue #print "Good length!" sample_number = sample_number + 1 binaryString = map(int, binaryString) bits_sum = [sum(x) for x in zip(bits_sum, binaryString)] # compute the IR code based on MAX_SAMPLES result = "" for x in bits_sum: if x < 0.5: result += '0' else: result += '1' neo.digitalWrite(pinLED, neo.LOW) print result return result
def getCode(self): # Learning mode feedback led pinLED = 26 # IR receiver pinIR = 25 neo = Gpio() neo.pinMode(pinIR, neo.INPUT) neo.pinMode(pinLED, neo.OUTPUT) neo.digitalWrite(pinLED, neo.HIGH) # Compute the average result after MAX_SAMPLES gap_number = 0 MAX_GAPS = 3 GAP_TIME = 20000 value = 1 time_to_live = 45000 while value and time_to_live: value = neo.digitalRead(pinIR) time_to_live -= 1 if time_to_live == 0: neo.digitalWrite(pinLED, neo.LOW) return "" # Grab the start time of the command startTime = datetime.now() # Used to buffer the command pulses command = [] # Used to keep track of transitions from 1 to 0 previousVal = 0 while True: if value != previousVal: # The value has changed, so calculate the length of this run now = datetime.now() pulseLength = now - startTime startTime = now if pulseLength.microseconds > GAP_TIME: gap_number = gap_number + 1 if gap_number == MAX_GAPS: break command.append((previousVal, pulseLength.microseconds)) previousVal = value value = neo.digitalRead(pinIR) neo.digitalWrite(pinLED, neo.LOW) result = "" for (i, j) in command: result = result + " " + str(j) #result = result.replace(",", "") result = result[1:] print result return result
service_name = "GossipBTServer" server = BTServer(uuid, service_name) # Create the server thread and run it server_thread = Thread(target=asyncore.loop, name="Gossip BT Server Thread") server_thread.daemon = True server_thread.start() while True: for client_handler in server.active_client_handlers.copy(): # Use a copy() to get the copy of the set, avoiding 'set change size during iteration' error # Create CSV message "'realtime', time, temp, SN1, SN2, SN3, SN4, PM25\n" epoch_time = int(time()) # epoch time neo = Gpio() S0 = 8 # pin to use S1 = 9 S2 = 10 S3 = 11 pinNum = [S0, S1, S2, S3] num = [0, 0, 0, 0] # Blink example for i in range(4): neo.pinMode(pinNum[i], neo.OUTPUT) #Temperature sensor