Example #1
0
class lm35(object):
    """
    Instatiates a analog read of the GPIO pin from galileo gen2 

    pin: Valid Analog Pin (14, 15, 16, 17, 18, 19) respectively from A0 to A5
    unit: Can be either Celcius, Kelvin or Farenheit [c, k f]
    """

    # Class Initializer
    def __init__(self, pin, unit="c", debug=False):
        self.gpio = GPIO(debug=False)
        self.unit = unit
        self.pin = pin
        self.gpio.pinMode(self.pin, self.gpio.ANALOG_INPUT)

    def get_value(self):
        self.raw = self.gpio.analogRead(self.pin)
        self.milivolt = (self.raw / 1024.0) * 5000
        self.celcius = self.milivolt / 10
        self.farenheit = (self.celcius * 1.8) + 32
        self.kelvin = self.celcius + 273.0
        if self.unit == "c":
            return self.celcius
        if self.unit == "k":
            return self.kelvin
        if self.unit == "f":
            return self.farenheit
Example #2
0
class presence_sensor(object):
    def __init__(self, pin):
        self.gpio = GPIO(debug=False)
        self.pin = pin
        self.gpio.pinMode(pin, self.gpio.INPUT)

    def get_value(self):
        return bool(self.gpio.digitalRead(self.pin))
Example #3
0
class Device(object):
    def __init__(self, pin_):
        self.gpio = GPIO(debug=False)
        self.gpio.pinMode(pin_, self.gpio.OUTPUT)

    def onDevice(self, pin_):
        return self.gpio.digitalWrite(pin_, self.gpio.HIGH)

    def offDevice(self, pin_):
        return self.gpio.digitalWrite(pin_, self.gpio.LOW)

    def getDevice(self, pin_):
        return self.gpio.digitalRead(pin_)
Example #4
0
def defineIO():
	gpio = GPIO(debug=False)
	if debugMode: print 'setting up io pin'
	gpio.pinMode(13,gpio.OUTPUT)
	gpio.pinMode(2,gpio.OUTPUT)
	gpio.pinMode(3,gpio.OUTPUT)
	gpio.pinMode(4,gpio.OUTPUT)
	gpio.pinMode(5,gpio.OUTPUT)
	gpio.pinMode(6,gpio.OUTPUT)
	if debugMode: print 'successfull...'
def defineIO():
	from wiringx86 import GPIOGalileoGen2 as GPIO
	gpio = GPIO(debug=False)
	if debugMode: print 'setting up io pin'
	gpio.pinMode(13,gpio.OUTPUT)
	gpio.pinMode(2,gpio.OUTPUT)
	gpio.pinMode(3,gpio.OUTPUT)
	gpio.pinMode(4,gpio.OUTPUT)
	gpio.pinMode(5,gpio.OUTPUT)
	gpio.pinMode(6,gpio.OUTPUT)
	if debugMode: print 'successfull...'
Example #6
0
def main(argv):
   print 'Starting up'
   gpio = GPIO(debug=False)
   gpio.pinMode(8,gpio.OUTPUT)
   for i in range(4):
      print 'Hi\n'
      gpio.digitalWrite(8,gpio.HIGH)
      time.sleep(0.5)
      print 'Lo\n'
      gpio.digitalWrite(8,gpio.LOW)
      time.sleep(0.5)
   print 'Done\n'
   gpio.cleanup()
Example #7
0
def checkThenSetByte(dataVar):
	gpio = GPIO(debug=False)                                            
	for x in range(0,8):
		if x==0: 
			pin=2                                                 
		elif x==1: 
			pin=3
		elif x==2:
			pin=4
		elif x==3:                                                              
			pin=5
		elif x==4:                                                              
			pin=6
		elif x==5:                                                              
			pin=13
		else:
			break
		
		gpio.pinMode(pin,gpio.OUTPUT) 
		if checkBit(dataVar,x)>0:
			print("on")
			gpio.digitalWrite(pin, gpio.HIGH)
			if pin==13:
				print('indikator on')
		else: 	
			print("off")
			gpio.digitalWrite(pin, gpio.LOW)
			if pin==13:                                                                                   
				print('indikator off')
	if debugMode:print("seharusnya setelah di set, disini dicek lagi benar2 on apa tidak")	    
Example #8
0
class photo_resistor(object):
    """
    Instatiates a analog read of the GPIO pin from galileo gen2 

    pin: Valid Analog Pin (14, 15, 16, 17, 18, 19) respectively from A0 to A5
    """

    # Class Initializer
    def __init__(self, pin, debug=False):
        self.gpio = GPIO(debug=False)
        self.pin = pin
        self.gpio.pinMode(self.pin, self.gpio.ANALOG_INPUT)

    def get_value(self):
        self.raw = self.gpio.analogRead(self.pin)
        self.normalized = (self.raw / 1024.0)
        self.percent = self.normalized * 100
        return self.percent
Example #9
0
def main(argv):
   print 'Starting up'
   gpio = GPIO(debug=False)
   for i in range(5):
      gpio.pinMode(8+i,gpio.OUTPUT)
   gpio.pinMode(19,gpio.ANALOG_INPUT)
   for i in range(4100):
      x = gpio.analogRead(19)
      print x
      n = (x-460)/30
      for j in range(5):
         if j<n: 
           s=gpio.HIGH 
         else: 
           s=gpio.LOW
         gpio.digitalWrite(8+j,s)
      time.sleep(0.1)
   print 'Done\n'
   gpio.cleanup()
def temp_command():
	gpio = GPIO(debug=False)
	analogpin = 14

	gpio.pinMode(analogpin, gpio.ANALOG_INPUT)

	print 'Analog reading from pin %d now...' % analogpin
	try:
    		count = 0
    		while(count < 5):
        		# Read the voltage on pin 14
        		value = gpio.analogRead(analogpin)

    			tempc = (5.0 * value * 100.0)
    			tempc = tempc / 1024
    			value = tempc

        		print 'Leitura: %.2f  celsius'   % value
        		time.sleep(0.5)
        		count = count + 1

	# When you get tired of seeing the led blinking kill the loop with Ctrl-C.
	except KeyboardInterrupt:
    	
    		print '\nCleaning up...'
    	# Do 
    		gpio.cleanup()       
Example #11
0
def main(argv):
   print 'Starting up'
   gpio = GPIO(debug=False)
   gpio.pinMode(19,gpio.ANALOG_INPUT)
   for i in range(30):
      x = gpio.analogRead(19)
      print x
      time.sleep(0.5)
   print 'Done\n'
   gpio.cleanup()
    def __init__(self, uuid, pin, name, debug=False, gpio_debug=False):
        print_debug(debug, currentframe().f_code.co_name, 'Init pump: %s' % name, __name__)

        # Make sure we only have one instance per pump
        if uuid in self.instances:
            error = ValueError
            error.message = 'A pump-instance with ID "%i" already exist!' % uuid
            raise error

        # Add the new instance to the instances-list
        Pump.instances[uuid] = self

        self.uuid = uuid
        self.pin = pin
        self.name = name
        self.digital_pin = digitalPins.get(pin)
        self.debug = debug

        all_params_str = u'Uuid: {uuid}. Pin: {pin}. Digital pin: {dpin}. Name: {name}'.format(
            uuid=uuid,
            pin=pin,
            dpin=self.digital_pin,
            name=name,
        )
        print_debug(debug, currentframe().f_code.co_name, all_params_str, __name__)

        # Get a new instance of the GPIO
        self.gpio = GPIO(debug=gpio_debug)  # type: GPIO

        # Set the pump to output
        self.gpio.pinMode(self.digital_pin, self.gpio.OUTPUT)

        # Set the pumps initial status to closed
        self.__status = self.closed

        # Events the pump can send
        self.pump_is_turned_on = signal(blinker_signals['pump_is_on'])
        self.pump_is_turned_off = signal(blinker_signals['pump_is_off'])
Example #13
0
import time
import subprocess

from wiringx86 import GPIOGalileoGen2 as GPIO

gpio = GPIO(debug=False)

pwm_pin = 11
value = 0
fade = 5

print("Setting up Pins...")
gpio.pinMode(pwm_pin, gpio.OUTPUT)

try:
    while (True):

        for i in xrange(0, 1000):
            gpio.digitalWrite(pwm_pin, gpio.HIGH)
            time.sleep(0.001)
            gpio.digitalWrite(pwm_pin, gpio.LOW)
            time.sleep(0.001)

        time.sleep(2)

except KeyboardInterrupt:
    print("Cleaning up...")
    gpio.digitalWrite(pwm_pin, gpio.LOW)
    gpio.cleanup()
Example #14
0
 def __init__(self, pin_):
     self.gpio = GPIO(debug=False)
     self.gpio.pinMode(pin_, self.gpio.OUTPUT)
class Pump(object):
    """
    Simple class that helps to open and close a pump that is connected to the board
    One instance represents one pump
    """

    instances = {}

    opened = 'OPENED'
    closed = 'CLOSED'

    def __init__(self, uuid, pin, name, debug=False, gpio_debug=False):
        print_debug(debug, currentframe().f_code.co_name, 'Init pump: %s' % name, __name__)

        # Make sure we only have one instance per pump
        if uuid in self.instances:
            error = ValueError
            error.message = 'A pump-instance with ID "%i" already exist!' % uuid
            raise error

        # Add the new instance to the instances-list
        Pump.instances[uuid] = self

        self.uuid = uuid
        self.pin = pin
        self.name = name
        self.digital_pin = digitalPins.get(pin)
        self.debug = debug

        all_params_str = u'Uuid: {uuid}. Pin: {pin}. Digital pin: {dpin}. Name: {name}'.format(
            uuid=uuid,
            pin=pin,
            dpin=self.digital_pin,
            name=name,
        )
        print_debug(debug, currentframe().f_code.co_name, all_params_str, __name__)

        # Get a new instance of the GPIO
        self.gpio = GPIO(debug=gpio_debug)  # type: GPIO

        # Set the pump to output
        self.gpio.pinMode(self.digital_pin, self.gpio.OUTPUT)

        # Set the pumps initial status to closed
        self.__status = self.closed

        # Events the pump can send
        self.pump_is_turned_on = signal(blinker_signals['pump_is_on'])
        self.pump_is_turned_off = signal(blinker_signals['pump_is_off'])

    def turn_on_pump(self, magnetic_valve):
        """
        Will open a specific pump and when it's open, and filled with water, it will open the valve provided

        :type magnetic_valve: MagneticValve
        :param magnetic_valve: The valve that should be opened while the pump is opened
        """
        print_debug(self.debug, currentframe().f_code.co_name, 'Turning on pump: %s' % self.name, __name__)
        self.__status = self.opened
        self.gpio.digitalWrite(self.digital_pin, self.gpio.HIGH)

        # Open the valve after 1 second so we know there's water in the hose
        timer_time = 1
        timer = Timer(timer_time, self.__send_turned_on_event, args=[magnetic_valve])
        timer.start()

    def turn_off_pump(self):
        """
        Turn off the pump
        :return:
        """
        print_debug(self.debug, currentframe().f_code.co_name, 'Turning off pump: %s' % self.name, __name__)
        self.__status = self.closed
        self.gpio.digitalWrite(self.digital_pin, self.gpio.LOW)

    def cleanup(self):
        """
        Turn off the pump on cleanup
        """
        self.turn_off_pump()

    def __send_turned_on_event(self, valve):
        """
        Send the turn on signal to the WateringQueue so it knows that it can open the valve
        :param valve:
        :return:
        """
        self.pump_is_turned_on.send(valve)

    @property
    def is_opened(self):
        return self.__status is self.opened

    @property
    def get_instances(self):
        return self.instances
Example #16
0
# This example is inspired on Arduino Blink example.
# http://arduino.cc/en/Tutorial/Blink
#
# This example will work "out of the box" on an Intel® Galileo Gen2 board. If
# you are using a different board such as an Intel® Galileo, just change the
# import below. wiringx86 uses the same API for all the boards it supports.

# Import the time module enable sleeps between turning the led on and off.
import time

# Import the GPIOGalileoGen2 class from the wiringx86 module.
from wiringx86 import GPIOGalileoGen2 as GPIO

# Create a new instance of the GPIOGalileoGen2 class.
# Setting debug=True gives information about the interaction with sysfs.
gpio = GPIO(debug=False)
state = gpio.HIGH
pins = 20

# Set all pins to be used as output GPIO pins.
print 'Setting up all pins...'
for pin in range(0, pins):
    gpio.pinMode(pin, gpio.OUTPUT)

print 'Blinking all pins now...'
try:
    while(True):
        for pin in range(0, pins):
            # Write a state to the pin. ON or OFF.
            gpio.digitalWrite(pin, state)
from upm import pyupm_servo as servo
from wiringx86 import GPIOGalileoGen2 as GPIO
from upm import pyupm_jhd1313m1 as lcd

import __future__
from collections import OrderedDict

pino_sensor_temperatura = 0
pino_rele = 8
pino_led1 = 3
pino_led2 = 4
pino_pot = 15
pino_servo1 = 5
pino_servo2 = 6

pinos = GPIO(debug=False)

pinos.pinMode(pino_rele, pinos.OUTPUT)
pinos.pinMode(pino_led1, pinos.OUTPUT)
pinos.pinMode(pino_led2, pinos.OUTPUT)
pinos.pinMode(pino_pot, pinos.ANALOG_INPUT)
pinos.pinMode(pino_servo1, pinos.OUTPUT)
pinos.pinMode(pino_servo2, pinos.OUTPUT)
temp = upm.Temperature(pino_sensor_temperatura)
sg_servo1 = servo.ES08A(pino_servo1)
sg_servo2 = servo.ES08A(pino_servo2)
tela = lcd.Jhd1313m1(0, 0x3E, 0x62)

tela.setColor(0, 100, 50)

Example #18
0
#defining necessary pins
led = 13

#Importing Intel Galileo Official UPM Library
import pyupm_grove as grove

# Create the temperature sensor object using AIO pin 0
temp = grove.GroveTemp(0)

# Create the light sensor object using AIO pin 0
light = grove.GroveLight(1)

# make sure python wiring x86 library is installed.
# Import the GPIOEdison class from the wiringx86 module.
from wiringx86 import GPIOGalileoGen2 as GPIO
gpio = GPIO()

gpio.pinMode(led, gpio.OUTPUT)

#defining topics
ledTopic    = "things/galileo"


def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe(ledTopic)
    print("Subscribed to Necessary Topics")

def on_message(client, userdata, msg):
    print "Message Topic :" + str(msg.topic)
    print "Message :" + str(msg.payload)
Example #19
0
import sys
sys.path.append("../../gpio")
import serial
import math
import time
import os.path
import argparse
import threading
from wiringx86 import GPIOGalileoGen2 as GPIO

gpio = GPIO(debug=False)
mote_pin = 2
gpio.pinMode(mote_pin, gpio.OUTPUT)


class MoteData(object):
    def convert_power(raw):
        pw = -1
        if (raw < 120):
            pw = 0
        else:
            pw = 220 * math.sqrt(raw) * 0.004343
        return (round(pw * 100) / 100)

    def convert_luminosity(raw):
        lum = ((raw / 8192) * 100) - 28
        return lum


class EposMoteIII(object):
    """
Example #20
0
#!/usr/bin/python

import socket, traceback
import os
import os.path
import time
import math
from wiringx86 import GPIOGalileoGen2 as GPIO

gpio = GPIO(debug=False)

import thread

#Stepper Motor Pins
step = 0
direction = 1

#DC Motor Pins

#For Motor 1
dir1 = 2
pwm1 = 3
brk1 = 4

#For Motor 2
dir2 = 8
pwm2 = 9
brk2 = 10

pwmvalue = 50
Example #21
0
#!/usr/bin/python3

import sys
sys.path.append("../gpio")

import os
import subprocess
import time
import threading
from wiringx86 import GPIOGalileoGen2 as GPIO

gpio = GPIO(debug=False)
internet_pin = 1
gpio.pinMode(internet_pin, gpio.OUTPUT)


def check_internet(period, lock):
    while True:

        #response = subprocess.call("ping -c 1 google.com -q > /dev/null 2>&1", shell=True)

        p = subprocess.Popen("ping -c 1 google.com".split(),
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        out, err = p.communicate()
        response = p.wait()
        #print (response)

        if response == 0:
            print("CONNECTIVITY: \tConnected to internet")
            gpio.digitalWrite(internet_pin, gpio.HIGH)
Example #22
0
    print 'Plataforma galileogen1'
    from wiringx86 import GPIOGalileo as GPIO
elif modelo == 'raspberrypi':
    print 'Plataforma RaspBerryPi'

print 'passou pela configuraPCI'
'''
try:
	from wiringx86 import GPIOGalileo as GPIO
	print ('Rodando na Gen1')
except:
	from wiringx86 import GPIOGalileoGen2 as GPIO
	print ('Rodando na Gen2')
'''

pinos = GPIO(debug=False)
from openweather import openweather
try:
    with open('config.txt') as json_data:
        config = json.load(json_data)
    piracicaba = openweather(config['api_key'], '3453643')
except:
    print 'Erro na coneccao com a internet'

from upm import pyupm_jhd1313m1 as LCD
lcd = LCD.Jhd1313m1(0, 0x3E, 0x62)
from upm import pyupm_servo as servo
from upm import pyupm_temperature as upm
import threading

pino_sensor_temperatura = 0
import time
import subprocess

from wiringx86 import GPIOGalileoGen2 as GPIO

gpio = GPIO(debug=False)

lm35_pin = 16
photo_pin = 14

summ = 0
sample = 0

print("Setting Up all pins...")

gpio.pinMode(lm35_pin, gpio.ANALOG_INPUT)
gpio.pinMode(photo_pin, gpio.ANALOG_INPUT)

print("Analog reading from pin A0")

try:
    while (True):
        raw_value_lm35 = gpio.analogRead(lm35_pin)
        raw_value_photo = gpio.analogRead(photo_pin)
        milivolt = (raw_value_lm35 / 1024.0) * 5000
        celcius = milivolt / 10
        percent = 100 - (raw_value_photo / 1024.0 * 100)
        # 	summ += celcius
        # 	sample += 1
        # 	avg = summ/sample
        print(celcius, percent)
Example #24
0
import time
import subprocess

from wiringx86 import GPIOGalileoGen2 as GPIO

gpio = GPIO(debug=False)
presence_sensor = 4

gpio.pinMode(presence_sensor, gpio.INPUT)

print("Reading Now")
try:
    while (True):
        time.sleep(1)
        state = gpio.digitalRead(presence_sensor)
        print(state)

except KeyboardInterrupt:
    print("\n\nCleaning Up...")
    gpio.cleanup()
class AutomaticWateringSystem(object):
    """
    Main class for the Automatic Watering System (AWS)
    Will initiate the classes needed for a plant
    """

    instances = {}

    def __init__(self, uuid, name, temperature_pin=None, magnetic_valve_pin=None, moisture_pin=None,
                 debug=False, gpio_debug=False):
        """
        Constructor

        :type uuid: str
        :param uuid: The ID from the database

        :type name: str
        :param name: The name of the plant

        :type temperature_pin: int
        :param temperature_pin: Which pin the temperature sensor is attached to

        :type magnetic_valve_pin: int
        :param magnetic_valve_pin: Which pin the magnetic valve is attached to

        :type moisture_pin: int
        :param moisture_pin: Which pin the moisture sensor is attached to

        :type debug: bool
        :param debug:

        :type gpio_debug: bool
        :param gpio_debug: Specify if the debug should be on/off for the GPIO library
        """
        print_debug(debug, currentframe().f_code.co_name, u'Init %s' % name, __name__)
        all_params_str = u'UUID: {uuid}. Name: {name}. TP: {tp}. MVP: {mvp}. MP: {mp}'.format(
            uuid=uuid,
            name=name,
            tp=temperature_pin,
            mvp=magnetic_valve_pin,
            mp=moisture_pin
        )
        print_debug(debug, currentframe().f_code.co_name, all_params_str, __name__)

        # Add the new instance to the instances-list
        AutomaticWateringSystem.instances[uuid] = self

        self.__name = name
        self.__temperature_pin = temperature_pin
        self.__magnetic_valve_pin = magnetic_valve_pin
        self.__moisture_pin = moisture_pin
        self.debug = debug

        # Get a uuid for the class so we can identify easier
        # self.__uuid = str(uuid4())  # type: uuid4
        self.__uuid = uuid

        self.DB = Database.Database()
        self.db_own_plant = self.DB.get_own_plant_from_id(self.get_uuid)
        self.db_plant = self.DB.get_plant_from_id(self.db_own_plant.get('plant_id'))
        self.db_pump = self.DB.get_pump_from_id(self.db_own_plant.get('pump_id'))

        # Get a new instance of the GPIO
        self.gpio = GPIO(debug=gpio_debug)  # type: GPIO

        # It has to be a magnetic valve connected!
        self.MagneticValve = None
        if magnetic_valve_pin is not None:
            print_debug(debug, currentframe().f_code.co_name,
                        'Initializing magnetic valve at pin %i' % magnetic_valve_pin, __name__)
            self.MagneticValve = MagneticValve(self.gpio, self.__uuid, magnetic_valve_pin,
                                               name, self.db_own_plant.get('pump_id'), debug)  # type: MagneticValve
        else:
            error = EnvironmentError
            error.message = 'A magnetic valve is needed!'
            raise error

        self.TemperatureSensor = None
        if temperature_pin is not None:
            print_debug(debug, currentframe().f_code.co_name,
                        'Initializing temperature sensor at pin %i' % temperature_pin, __name__)
            self.TemperatureSensor = Temperature(self.gpio, self.__uuid, temperature_pin,
                                                 name, 30, debug)  # type: Temperature

        self.MoistureSensor = None
        if moisture_pin is not None:
            print_debug(debug, currentframe().f_code.co_name,
                        'Initializing moisture sensor at pin %i' % moisture_pin, __name__)
            self.MoistureSensor = Moisture(self.gpio, self.__uuid, moisture_pin, name,
                                           self.db_plant.get('min_moisture'), self.db_plant.get('max_moisture'),
                                           debug)  # type: Moisture

        self.__run_count = 0
        self.active = True

        # Run a check directly when a new instance is created
        self.__start_new_timer(0)

    def __start_new_timer(self, time=60):
        """
        Starts a new timer

        :type time: int
        :param time: How many seconds the timer should be set to
        """
        new_timer_uuid = str(uuid.uuid4())

        print_debug(self.debug, currentframe().f_code.co_name,
                    u'New timer will start after {time} second(s). AWS name: {name}. Timer UUID: {uuid}'
                    .format(time=time, name=self.get_name, uuid=new_timer_uuid), __name__)

        self.timer = Timer(time, self.__run, [new_timer_uuid])
        self.timer.start()

    def __run(self, timer_id):
        """
        Run the different checks, and open the valve if needed!
        This function should not be called directly! Call __start_new_timer() instead!

        :type timer_id: str
        :param timer_id: A unique identifier for each timer
        """
        self.__run_count += 1
        print_debug(self.debug, currentframe().f_code.co_name,
                    u'Timer executing. AWS name: {name}. Timer UUID: {timer_id}'
                    .format(name=self.get_name, timer_id=timer_id), __name__)
        print_debug(self.debug, currentframe().f_code.co_name, u'Run count: %s' % self.__run_count, __name__)

        temp_exceed = False
        moist_deceed = False

        stats_dict = {Database.TABLE_STATISTICS_RUN_COUNT: self.__run_count}

        if self.TemperatureSensor:
            stats_dict[Database.TABLE_STATISTICS_TEMPERATURE_RAW] = self.TemperatureSensor.get_raw_read()
            stats_dict[Database.TABLE_STATISTICS_TEMPERATURE_MIN_CELSIUS] = self.TemperatureSensor.min_celsius
            stats_dict[Database.TABLE_STATISTICS_TEMPERATURE_MAX_CELSIUS] = self.TemperatureSensor.max_celsius
            stats_dict[Database.TABLE_STATISTICS_TEMPERATURE_CELSIUS] = self.TemperatureSensor.get_celsius()
            temp_exceed = self.TemperatureSensor.has_exceeded_threshold()

        if self.MoistureSensor:
            stats_dict[Database.TABLE_STATISTICS_MOISTURE_RAW] = self.MoistureSensor.get_raw_read()
            stats_dict[Database.TABLE_STATISTICS_MOISTURE_MIN_PERCENT] = self.MoistureSensor.min_percent
            stats_dict[Database.TABLE_STATISTICS_MOISTURE_MAX_PERCENT] = self.MoistureSensor.max_percent
            stats_dict[Database.TABLE_STATISTICS_MOISTURE_PERCENT] = self.MoistureSensor.get_percent_read()
            moist_deceed = self.MoistureSensor.has_deceeded_threshold()

        print_debug(self.debug, currentframe().f_code.co_name, u'Temp exceed: %s' % str(temp_exceed), __name__)
        print_debug(self.debug, currentframe().f_code.co_name, u'Moist deceed: %s' % str(moist_deceed), __name__)

        # Add statistics
        self.DB.add_statistic(self.get_uuid, **stats_dict)

        if moist_deceed:
            # Try to open the valve
            self.MagneticValve.send_open_valve_signal()

        print_debug(self.debug, currentframe().f_code.co_name,
                    u'Timer done. AWS name: {name}. Timer UUID: {timer_id}'
                    .format(name=self.get_name, timer_id=timer_id), __name__)

        self.__start_new_timer(10)
        # self.__start_new_timer()

    def cleanup(self):
        """
        Cleanup all the things!
        """
        print_debug(self.debug, currentframe().f_code.co_name,
                    u'Cleanup  ({name}, {uuid})!'.format(name=self.get_name, uuid=self.get_uuid), __name__)

        if self.TemperatureSensor:
            self.TemperatureSensor.cleanup()

        if self.MoistureSensor:
            self.MoistureSensor.cleanup()

        self.MagneticValve.cleanup()

        self.timer.cancel()

        self.gpio.cleanup()

    @property
    def get_name(self):
        return self.__name

    @property
    def get_uuid(self):
        return self.__uuid
    def __init__(self, uuid, name, temperature_pin=None, magnetic_valve_pin=None, moisture_pin=None,
                 debug=False, gpio_debug=False):
        """
        Constructor

        :type uuid: str
        :param uuid: The ID from the database

        :type name: str
        :param name: The name of the plant

        :type temperature_pin: int
        :param temperature_pin: Which pin the temperature sensor is attached to

        :type magnetic_valve_pin: int
        :param magnetic_valve_pin: Which pin the magnetic valve is attached to

        :type moisture_pin: int
        :param moisture_pin: Which pin the moisture sensor is attached to

        :type debug: bool
        :param debug:

        :type gpio_debug: bool
        :param gpio_debug: Specify if the debug should be on/off for the GPIO library
        """
        print_debug(debug, currentframe().f_code.co_name, u'Init %s' % name, __name__)
        all_params_str = u'UUID: {uuid}. Name: {name}. TP: {tp}. MVP: {mvp}. MP: {mp}'.format(
            uuid=uuid,
            name=name,
            tp=temperature_pin,
            mvp=magnetic_valve_pin,
            mp=moisture_pin
        )
        print_debug(debug, currentframe().f_code.co_name, all_params_str, __name__)

        # Add the new instance to the instances-list
        AutomaticWateringSystem.instances[uuid] = self

        self.__name = name
        self.__temperature_pin = temperature_pin
        self.__magnetic_valve_pin = magnetic_valve_pin
        self.__moisture_pin = moisture_pin
        self.debug = debug

        # Get a uuid for the class so we can identify easier
        # self.__uuid = str(uuid4())  # type: uuid4
        self.__uuid = uuid

        self.DB = Database.Database()
        self.db_own_plant = self.DB.get_own_plant_from_id(self.get_uuid)
        self.db_plant = self.DB.get_plant_from_id(self.db_own_plant.get('plant_id'))
        self.db_pump = self.DB.get_pump_from_id(self.db_own_plant.get('pump_id'))

        # Get a new instance of the GPIO
        self.gpio = GPIO(debug=gpio_debug)  # type: GPIO

        # It has to be a magnetic valve connected!
        self.MagneticValve = None
        if magnetic_valve_pin is not None:
            print_debug(debug, currentframe().f_code.co_name,
                        'Initializing magnetic valve at pin %i' % magnetic_valve_pin, __name__)
            self.MagneticValve = MagneticValve(self.gpio, self.__uuid, magnetic_valve_pin,
                                               name, self.db_own_plant.get('pump_id'), debug)  # type: MagneticValve
        else:
            error = EnvironmentError
            error.message = 'A magnetic valve is needed!'
            raise error

        self.TemperatureSensor = None
        if temperature_pin is not None:
            print_debug(debug, currentframe().f_code.co_name,
                        'Initializing temperature sensor at pin %i' % temperature_pin, __name__)
            self.TemperatureSensor = Temperature(self.gpio, self.__uuid, temperature_pin,
                                                 name, 30, debug)  # type: Temperature

        self.MoistureSensor = None
        if moisture_pin is not None:
            print_debug(debug, currentframe().f_code.co_name,
                        'Initializing moisture sensor at pin %i' % moisture_pin, __name__)
            self.MoistureSensor = Moisture(self.gpio, self.__uuid, moisture_pin, name,
                                           self.db_plant.get('min_moisture'), self.db_plant.get('max_moisture'),
                                           debug)  # type: Moisture

        self.__run_count = 0
        self.active = True

        # Run a check directly when a new instance is created
        self.__start_new_timer(0)
Example #27
0
 def __init__(self, pin):
     self.gpio = GPIO(debug=False)
     self.pin = pin
     self.gpio.pinMode(pin, self.gpio.INPUT)
Example #28
0
from wiringx86 import GPIOGalileoGen2 as GPIO
import time

gpio = GPIO(debug=False)

led = 13
dht11 = 8

print("Setting up Pins")

gpio.pinMode(dht11, gpio.INPUT)
gpio.pinMode(led, gpio.OUTPUT)

data = []

for i in range(0, 500):
    data.append(gpio.digitalRead(dht11))

bit_count = 0
tmp = 0
count = 0
hum_bit = ""
temp_bit = ""
crc = ""
try:
    while data[count] == 1:
        tmp = 1
        count += 1
    for i in range(0, 32):
        bit_count = 0
Example #29
0
# This example is inspired on Arduino Analog Input example.
# http://arduino.cc/en/Tutorial/AnalogInput
#
# This example will work "out of the box" on an Intel® Galileo Gen2 board. If
# you are using a different board such as an Intel® Galileo, just change the
# import below. wiringx86 uses the same API for all the boards it supports.

# Import the time module enable sleeps between turning the led on and off.
import time

# Import the GPIOGalileoGen2 class from the wiringx86 module.
from wiringx86 import GPIOGalileoGen2 as GPIO

# Create a new instance of the GPIOGalileoGen2 class.
# Setting debug=True gives information about the interaction with sysfs.
gpio = GPIO(debug=False)
pin = 13
analogpin = 14

print 'Setting up all pins...'

# Set pin 14 to be used as an analog input GPIO pin.
gpio.pinMode(analogpin, gpio.ANALOG_INPUT)

# Set pin 13 to be used as an output GPIO pin.
gpio.pinMode(pin, gpio.OUTPUT)

print 'Analog reading from pin %d now...' % analogpin
try:
    while(True):
        # Read the voltage on pin 14
Example #30
0
from time import sleep
import json
from wiringx86 import GPIOGalileoGen2 as GPIO

varSuhu = int(argv[1])
varKelembapan = int(argv[2])
varStatus=192
varReset=1
varon1=0
varon2=0
varon3=0
varon4=0
varon5=0
varon6=0

gpio = GPIO(debug=False)
pin = 13
state = gpio.HIGH

print 'setting up pin %d' % pin

gpio.pinMode(pin,gpio.OUTPUT)
gpio.pinMode(2,gpio.OUTPUT)
gpio.pinMode(3,gpio.OUTPUT)
gpio.pinMode(4,gpio.OUTPUT)
gpio.pinMode(5,gpio.OUTPUT)
gpio.pinMode(6,gpio.OUTPUT)


print 'coba mengendalikan pin %d sekarang...' % pin
Example #31
0
welcome2internet()  
print('cek koneksi 1')
sendData2Server(APIkey, Suhu, Kelembapan, ReadON)
print('cek koneksi 2')
sendData2Server(APIkey, Suhu, Kelembapan, ReadON)
print('cek koneksi 3')
sendData2Server(APIkey, Suhu, Kelembapan, ReadON)
print('cek koneksi 4')
sendData2Server(APIkey, Suhu, Kelembapan, ReadON)
print('cek koneksi 5')
sendData2Server(APIkey, Suhu, Kelembapan, ReadON)
                                                                                                                                              
ReadON=requestDataFromServer(APIkey,'readon')
sendData2Server(APIkey, Suhu, Kelembapan, ReadON)

gpio = GPIO(debug=False) 
gpio.pinMode(2,gpio.OUTPUT) 
gpio.pinMode(3,gpio.OUTPUT) 
gpio.pinMode(4,gpio.OUTPUT) 
gpio.pinMode(5,gpio.OUTPUT) 
gpio.pinMode(6,gpio.OUTPUT) 
gpio.pinMode(13,gpio.OUTPUT) 

#void loop()
while True :
	sleep(2)
	print('??')
	ReadON=requestDataFromServer(APIkey,'readon')
	dataVar=ReadON                                                                                                                
        for x in range(0,8):                                                                                                                    
                if x==0:                                                                                                                        
Example #32
0
gpio40	pin8
gpio4	pin9
gpio10	pin10
gpio5	pin11
gpio15	pin12
gpio7	pin13

"""

import os
import os.path
import time


from wiringx86 import GPIOGalileoGen2 as GPIO
gpio = GPIO(debug=False)
from flask import Flask,url_for, render_template
app = Flask(__name__)
from flask import request
from flask import json

#Our robot mappings
#For motor 1
dir1 = 5
#For motor 2
dir2 = 6

gpio.pinMode(dir1, gpio.OUTPUT)

gpio.pinMode(dir2, gpio.OUTPUT)
Example #33
0
# This example is inspired on Arduino Fade example.
# http://arduino.cc/en/Tutorial/Fade
#
# This example will work "out of the box" on an Intel® Galileo Gen2 board. If
# you are using a different board such as an Intel® Galileo, just change the
# import below. wiringx86 uses the same API for all the boards it supports.

# Import the time module enable sleeps between turning the led on and off.
import time

# Import the GPIOGalileoGen2 class from the wiringx86 module.
from wiringx86 import GPIOGalileoGen2 as GPIO

# Create a new instance of the GPIOGalileoGen2 class.
# Setting debug=True gives information about the interaction with sysfs.
gpio = GPIO(debug=False)
pin = 3
brightness = 0
fadeAmount = 5

# Set pin 3 to be used as a PWM pin.
print 'Setting up pin %d' % pin
gpio.pinMode(pin, gpio.PWM)

print 'Fading pin %d now...' % pin
try:
    while(True):
        # Write brightness to the pin. The value must be between 0 and 255.
        gpio.analogWrite(pin, brightness)

        # Increment or decrement the brightness.
Example #34
0
#
# See license in LICENSE.txt file.
#
# This example is inspired on Arduino Button example.
# http://arduino.cc/en/Tutorial/Button
#
# This example will work "out of the box" on an Intel® Galileo Gen2 board. If
# you are using a different board such as an Intel® Galileo, just change the
# import below. wiringx86 uses the same API for all the boards it supports.

# Import the GPIOGalileoGen2 class from the wiringx86 module.
from wiringx86 import GPIOGalileoGen2 as GPIO

# Create a new instance of the GPIOGalileoGen2 class.
# Setting debug=True gives information about the interaction with sysfs.
gpio = GPIO(debug=False)
pin = 13
button = 2

print 'Setting up pins %d and %d...' % (pin, button)

# Set pin 13 to be used as an output GPIO pin.
gpio.pinMode(pin, gpio.OUTPUT)

# Set pin 2 to be used as an input GPIO pin.
gpio.pinMode(button, gpio.INPUT)

print 'Reading from pin %d now...' % button
try:
    while(True):
        # Read the state of the button
Example #35
0
import sys
sys.path.append("../gpio")
from wiringx86 import GPIOGalileoGen2 as GPIO
import time

gpio = GPIO(debug=False)

user_pin = 0
internet_pin = 1
mote_pin = 2
alarm_pin = 3
presence_pin = 4
speaker_pin = 13
lm35_pin = 14
photo_pin = 16

print("Setting up all pins")

gpio.pinMode(user_pin, gpio.OUTPUT)
gpio.pinMode(internet_pin, gpio.OUTPUT)
gpio.pinMode(mote_pin, gpio.OUTPUT)
gpio.pinMode(alarm_pin, gpio.OUTPUT)
gpio.pinMode(speaker_pin, gpio.OUTPUT)
gpio.pinMode(presence_pin, gpio.INPUT)
gpio.pinMode(lm35_pin, gpio.ANALOG_INPUT)
gpio.pinMode(photo_pin, gpio.ANALOG_INPUT)

while (True):
    print("Turning User Pin On")
    gpio.digitalWrite(user_pin, gpio.HIGH)
    time.sleep(0.2)
Example #36
0
 def __init__(self, pin, unit="c", debug=False):
     self.gpio = GPIO(debug=False)
     self.unit = unit
     self.pin = pin
     self.gpio.pinMode(self.pin, self.gpio.ANALOG_INPUT)
#!/usr/bin/python

import socket, traceback
import os
import os.path
import time
import math
from wiringx86 import GPIOGalileoGen2 as GPIO
gpio = GPIO(debug=False)

import thread

#Stepper Motor Pins
step      = 0
direction = 1

#DC Motor Pins

#For Motor 1
dir1 = 2
pwm1 = 3
brk1 = 4

#For Motor 2
dir2 = 8
pwm2 = 9
brk2 = 10

pwmvalue = 50

#Pin Mode Settings for Stepper and DC Motors
Example #38
0
#!/usr/bin/python3

import sys

sys.path.append("../gpio")

import subprocess
import threading
import time
import os
from wiringx86 import GPIOGalileoGen2 as GPIO

gpio = GPIO(debug=False)
user_pin = 0
gpio.pinMode(user_pin, gpio.OUTPUT)


class user(object):
    def __init__(self, path, MAC, name, last_ip="none"):
        self.connected = False
        self.scripts_path = path
        self.last_connected = 0
        self.name = name
        self.mac_addr = MAC
        self.ip = ""
        self.last_ip = last_ip
        self.tries = 0

    def validate_ip(self):
        valid = self.ip.split('.')
        if len(valid) == 4:
# This example is inspired on Arduino Analog Input example.
# http://arduino.cc/en/Tutorial/AnalogInput
#
# This example will work "out of the box" on an Intel® Edison board. If
# you are using a different board such as an Intel® Galileo Gen2, just change the
# import below. wiringx86 uses the same API for all the boards it supports.

# Import the time module enable sleeps between turning the led on and off.
import time

# Import the GPIOEdison class from the wiringx86 module.
from wiringx86 import GPIOGalileoGen2 as GPIO

# Create a new instance of the GPIOEdison class.
# Setting debug=True gives information about the interaction with sysfs.
gpio = GPIO(debug=False)
analogpin = 14

print 'Setting up all pins...'

# Set pin 14 to be used as an analog input GPIO pin.
gpio.pinMode(analogpin, gpio.ANALOG_INPUT)

# Set pin 13 to be used as an output GPIO pin.
#gpio.pinMode(pin, gpio.OUTPUT)

print 'Analog reading from pin %d now...' % analogpin
try:
    while(True):
        # Read the voltage on pin 14
        value = gpio.analogRead(analogpin)