Ejemplo n.º 1
0
def heaterPower(mode):
    global heaterPowerIO

    log.log(log.ALWAYS, "heaterPower() called with " + mode2str(mode))

    if (mode == gv.heatPower):
        return NOERROR

    if (mode == ON):
        if (gv.pumpPower) == OFF:
            log.log(log.ERROR, "attempting to turn on heater with pump off!")
            lcd.message("ERROR", "Can't turn on heat with Pump off")
            return ERROR

        else:
            heaterPowerIO.on()
            time.sleep(1)
            gv.heatPower = ON
            log.log(log.ALWAYS, "*** Heater power on ***")
            gv.systemMode = config.SPA_ON
            return NOERROR

    elif (mode == OFF):
        heaterPowerIO.off()
        log.log(log.ALWAYS, "*** Heater power off ***")
        gv.heatPower = OFF
        gv.systemMode = config.COOLDOWN
        return NOERROR

    else:
        log.log(log.ERROR, "heaterPower was passed invalid value: ", (mode))
        return ERROR
Ejemplo n.º 2
0
def show_lcd(message, line=1) :
	if line == 1 :
		lcd.home()
		lcd.message(message)
	if line == 2 :
		lcd.setCursor(1,2)
		lcd.message(message)
Ejemplo n.º 3
0
def run():
    lcd.clear()
    lcd.message("Loading...")

    weather_live_req = live_weather_request()
    weather_forecast_req = forecast_weather_request()
    bus_arrival_req = bus_request()

    grequests.map((weather_live_req, weather_forecast_req, bus_arrival_req))

    weathers = list()
    if weather_live_req.response is not None:
        weathers.append(
            weather_live_from_json(weather_live_req.response.json()))
    else:
        weathers.append(None)

    if weather_forecast_req.response is not None:
        weathers.append(
            weather_forecast_from_json(
                weather_forecast_req.response.json(),
                datetime.datetime.now() + datetime.timedelta(hours=12)))
    else:
        weathers.append(None)

    weather_str = weather_view(weathers)

    arrivals = arrivals_from_xml(
        ElementTree.fromstring(bus_arrival_req.response.content))
    bus_str = bus_arrival_view(arrivals)
    lcd_str = bus_str + "\n" + weather_str

    lcd.clear()
    lcd.message(lcd_str)
Ejemplo n.º 4
0
def shutdown():
    global pumpPowerIO, heaterPowerIO, heaterEnableIO, sparePowerIO, valve1DirIO, valve2DirIO

    # turn off everything
    log.log(log.ALWAYS, "Shutting Down")

    # ensure everything is off
    # don't use routines as a safety precaution
    pumpPowerIO.off()
    heaterPowerIO.off()
    heaterEnableIO.off()
    valve1DirIO.off()
    valve2DirIO.off()
    sparePowerIO.off()

    try:
        lcd.message("    System Off")
        lcd.setColor(0, 0, 255)
        lcd.closePort()

    except:
        print(sys.exc_info())
        log.log(log.ERROR, "error in lcd during shutdown - ignoring")

    log.log(log.ALWAYS, "Shutdown Complete")
    print("Equipment Off")
    return
Ejemplo n.º 5
0
def timer(seconds) :
	try :
		while seconds > 0 :
			lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
			lcd.message(str(seconds) + " seconds", style=2)
			seconds -= 1
			time.sleep(1)
			
		return 0
	
	except KeyboardInterrupt :
		leave()
Ejemplo n.º 6
0
def main():

	HOME = os.path.dirname(os.path.realpath(__file__))
	f = file(HOME+'/sensors.cfg')
	CFG = Config(f)
	logging.basicConfig(filename=HOME+'/sensors.log', level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M')

	tz = pytz.timezone(CFG.timezone)
	date = datetime.now(tz)

	GPIO.setwarnings(False)
	m = date.strftime("%Y-%m-%d\n%H:%M:%S")
	lcd.init()
	lcd.message(m)

	if date.hour >= 0 and date.hour <= 5:
		lcd.backlight(False)
	else:
		lcd.backlight(True)

	d = [] # read sensor data
	for s in CFG.sensors:

		if s.id < 0: continue # skip disabled sensors

		try:
			if s.name == 'DS18B20':
				v = w1.readTemp(s.rom_code)
			elif s.name == 'DHT22' and s.rom_code == 'H':
				v = dht.readHumidity()
			elif s.name == 'DHT22' and s.rom_code == 'T':
				v = dht.readTemperature()
			else:
				raise Exception('unknown sensor name')
				continue
		except Exception as e:
			logging.error("| Can't read sensor %d | %s | %s" % (s.id, s.rom_code, str(e)))
			continue

		try:
			db.updateSensor(s.id, v, date)
			if(s.type == 'H'):
				d.append('%d%%' % v)
			else:
				d.append(v)
#			print "#%d %s, %s: %.1f" % (s.id, s.rom_code, s.label, v)
		except Exception as e:
			logging.error("| Can't update sensor %d | %s | %s" % (s.id, s.rom_code, str(e)))
			continue

	m = buildMessage(d, date)	
	lcd.message(m)
Ejemplo n.º 7
0
	def status(self) :      
		log('Taking picture')
		out = os.system("fswebcam -r " + config.resolution +
					'--log syslog -q --jpeg -1' +
					" -d " + config.camera + 					
					" " + config.tempDirectory + "/" + 					
					config.pictureName)
		log("Camera app returned " + str(out))
		
		lcd.clear()        
		lcd.message("Status request:") 
		lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
		lcd.message("Pin is " + str(state))
Ejemplo n.º 8
0
def log(string, color='white'):
    colorHex = {
        'green': '92m',
        'yellow': '93m',
        'red': '91m'
    }
    if color not in colorHex:
        print('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ' + string)
    else:
        print(u'\033[' + colorHex[color] + time.strftime("%Y-%m-%d %H:%M:%S") + ' ' + string.decode('utf-8') + '\033[0m')
    if lcd:
        if(string):
            lcd.message(string)
Ejemplo n.º 9
0
def log(string, color = 'white'):
    colorHex = {
        'green': '92m',
        'yellow': '93m',
        'red': '91m'
    }
    if color not in colorHex:
        print('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] '+ string)
    else:
        print(u'\033['+ colorHex[color] + '[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] ' + string.decode('utf-8') + '\033[0m')
    if lcd:
        if(string):
            lcd.message(string)
Ejemplo n.º 10
0
def main():

	HOME = os.path.dirname(os.path.realpath(__file__))
	f = file(HOME+'/sensors.cfg')
	CFG = Config(f)

	tz = pytz.timezone(CFG.timezone)
	date = datetime.now(tz)

	GPIO.setwarnings(False)
	lcd.init()
	lcd.message('Raspberry Pi\n%s' % date.strftime("%Y-%m-%d %H:%M"))
	lcd.backlight(True)
Ejemplo n.º 11
0
def waitUntil(seconds, state=False) :
	try :
		while seconds > 0 :
			lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
			lcd.message(str(seconds) + " seconds", style=2)
			seconds -= 1
			time.sleep(1)
			pinstate = commands.readInput()            
			if pinstate == state :                
				break             
		return 0
	
	except KeyboardInterrupt :
		leave()
Ejemplo n.º 12
0
def spaOff():
    lcd.message("Turning Off Spa... ")
    log.log(log.ALWAYS, "Turning Spa Off ")

    heaterEnable(OFF)
    heaterPower(OFF)

    timer.setPumpOffEvent(0, 15)
    gv.systemMode = config.COOLDOWN
    gv.lastSpaOnTime = 0
    timer.setTimeRemaining(15)

    valveControl(VALVE_POOL_MODE)
    log.log(log.ALWAYS, "*** Starting Cooldown ***")
    return
Ejemplo n.º 13
0
def main():

	HOME = os.path.dirname(os.path.realpath(__file__))
	f = file(HOME+'/sensors.cfg')
	CFG = Config(f)
	logging.basicConfig(filename=HOME+'/sensors.log', level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M')

	tz = pytz.timezone(CFG.timezone)
	date = datetime.now(tz)

	m = date.strftime("%Y-%m-%d\n%H:%M:%S")
	GPIO.setwarnings(False)
	lcd.init()
	lcd.backlight(True)
	lcd.message(m)

	d = [] # read sensor data
	for s in CFG.sensors:

		if s.id < 0: continue # skip disabled sensors

		try:
			if s.name == 'DS18B20':
				v = w1.readTemp(s.rom_code)
			elif s.name == 'DHT22' and s.type == 'H':
				v = dht.readHumidity()
			elif s.name == 'DHT22' and s.type == 'T':
				v = dht.readTemperature()
			else:
				raise Exception('unknown sensor name')
				continue
		except Exception as e:
			logging.error("| Can't read sensor %d | %s | %s" % (s.id, s.rom_code, str(e)))
			continue

		try:
			print "%s, %s: %.1f" % (s.rom_code, s.label, v)
			if(s.type == 'H'):
				d.append('%d%%' % v)
			else:
				d.append(v)			
		except Exception as e:
			print "Can't print sensor %d" % s.id

	m = scan.buildMessage(d, date)
	lcd.message(m)
Ejemplo n.º 14
0
def setupComponents():
    #initialize buzzer
    buzzer.setup()

    #intialize lcd
    lcd.lcd_init()
    time.sleep(1)
    lcd.message("WELCOME ", "SMART PARKING")

    #set person gate pin as output pin
    GPIO.setup(PERSON_GATE, GPIO.OUT)
    GPIO.output(PERSON_GATE, False)

    # Hook the SIGINT
    signal.signal(signal.SIGINT, end_read)

    # Welcome message
    print("Welcome to the MFRC522 data read example")
    print("Press Ctrl-C to stop.")
Ejemplo n.º 15
0
def pumpPower(mode):
    global pumpPowerIO

    log.log(log.ALWAYS, "pumpPower() called with " + mode2str(mode))

    # already on?
    if (mode == gv.pumpPower):
        return

    if (mode == ON):
        pumpPowerIO.on()
        log.log(log.ALWAYS, "*** pump on ***")
        gv.pumpPower = ON
        gv.systemMode = config.PUMP_ON
        return NOERROR

    elif (mode == OFF):
        # todo: only do this if user pushes button
        if (gv.heatPower == ON):
            log.log(log.WARNING, "Turning off Pump with Heater ON!")
            lcd.message("WARNING", "Turning off Pump with Heater ON!")

        if (gv.systemMode == config.MANUAL
                or gv.systemMode == config.COOLDOWN):
            log.log(log.WARNING, "Heater may not have cooled down yet!")
            lcd.message("WARNING", "Heater may not have cooled down yet!")

        heaterEnable(OFF)
        heaterPower(OFF)
        pumpPowerIO.off()
        log.log(log.ALWAYS, "*** pump off ***")
        gv.pumpPower = OFF
        gv.systemMode = config.SYS_OFF
        return NOERROR
    else:
        log.log(log.ERROR, "pumpPower was passed invalid value: ", str(mode))
    return ERROR
Ejemplo n.º 16
0
def log(string, color='white'):
    color_hex = {
        'red': '91m',
        'green': '92m',
        'yellow': '93m',
        'blue': '94m',
        'cyan': '96m'
    }
    if color not in color_hex:
        print('[{time}] {string}'.format(
            time=time.strftime("%H:%M:%S"),
            string=string.decode('utf-8')
        ))
    else:
        print(
            '[{time}] \033[{color} {string} \033[0m'.format(
                time=time.strftime("%H:%M:%S"),
                color=color_hex[color],
                string=string.decode('utf-8')
            )
        )
    if lcd:
        if string:
            lcd.message(string)
Ejemplo n.º 17
0
	def ip(self) :
		lcd.home()
		lcd.message("IP Request")
		p = os.popen("ip addr show wlan0 | grep inet").readline().split()[1]
		ip = p.split('/')[0]
		#ip = self._getIP()
		#print ip
		log('IP Request from ' + sender)
		log('Local IP: ' + ip)
		lcd.message('IP_ Request', style=2)
		lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
		lcd.message(ip, style=2)     
		mailmanager.sendEmail(sender, 'Local IP', ip)
		time.sleep(config.displayTime)
Ejemplo n.º 18
0
def spaOn(hours):
    lcd.message("Turning on Spa... ")
    log.log(log.ALWAYS, "SpaOn called with hours = " + str(hours))
    time.sleep(1)

    pumpPower(ON)
    lcd.message("Pump On")
    time.sleep(1)

    heaterPower(ON)
    lcd.message("Heater On")
    time.sleep(1)

    valveControl(VALVE_SPA_MODE)

    heaterEnable(ON)

    gv.systemMode = config.SPA_ON
    timer.setSpaOffEvent(hours)
    log.log(log.ALWAYS, "*** Spa on ***")
    return
Ejemplo n.º 19
0
	def warn(self, command) :  
		GPIO.output(config.lightsPin, True)
		lcd.home()
		lcd.message(command + " in", style = 2)
		timer(config.warningTime)
		GPIO.output(config.lightsPin, False)
Ejemplo n.º 20
0
def main():
    #intialize the components of the project
    setupComponents()

    # This loop keeps checking for chips. If one is near it will get the UID and authenticate
    nfc = TwoRfid.Nfc522()  #create object to read from 2 different rfid
    while continue_reading:

        #read RFID of people entry and car entry
        gid1, gid2 = nfc.obtem_nfc_rfid()

        #handle car gate
        if not gid1 == 0:
            print("rfid reader of car gate read: ", gid1)
            buzzer.beep(1)

            name, slot, state = UserDB.AllowAccess(str(gid1), 0)
            if (state == 0):  #this person has a reservation
                lcd.message("WELCOME ", name)

                time.sleep(2)
                lcd.message("Go To Slot", str(slot))
                ServoMotor.OpenGate()  #open the gate

                #wait till the car pass the gate
                if (UltraSonicSensor.IsPassed()):

                    UserDB.changeState(gid1)
                    time.sleep(3)
                    ServoMotor.CloseGate()  #close the gate

                    #make microController open specific slot
                    openSlot(str(gid1), slot)
                    lcd.message("WELCOME IN", "SMART PARKING")

            elif (state == -2):  #this person not has a reservation
                lcd.message("Please ", "Reserve First")
                time.sleep(5)
                lcd.message("WELCOME IN", "SMART PARKING")

        #handle person gate
        if not gid2 == 0:
            print("rfid reader of person gate read: ", gid2)
            buzzer.beep(1)

            name, slot, state = UserDB.IsReserve(str(gid2), 1)
            if state == 1:  #this person has a car inside the garage
                #open the gate
                lcd.message("Here you are", "The Gate is open")
                GPIO.output(PERSON_GATE, True)
                time.sleep(6)
                GPIO.output(PERSON_GATE, False)

            else:
                lcd.message("Sorry You don't ", "Have car inside")
                time.sleep(5)

            lcd.message("WELCOME IN", "SMART PARKING")
Ejemplo n.º 21
0
def checkEvents():
    global spaOffTime, pumpOnTime1, pumpOffTime1, pumpOnTime2, pumpOffTime2
    global pumpOnTime3, pumpOffTime3, lastPumpOn, nextPumpOffTime

    # get local time
    now = timeNow()
    #log.log("Checking events at " + str(now))

    # timer events return non-zero if executed
    # ----------- timer set 1 ------------------
    if (pumpOnTime1 == now):
        log.log(log.ALWAYS, "PumpOnEvent1 fired")
        if (gv.pumpPower == OFF):
            equipment.pumpPower(ON)
            lastPumpOn = pumpOnTime1
            nextPumpOffTime = pumpOffTime1
            return 1

    if (pumpOffTime1 == now):
        log.log(log.ALWAYS, "PumpOffEvent1 fired")
        # don't turn off if in spa mode
        if (gv.systemMode != c.SPA_ON):
            equipment.pumpPower(OFF)
            nextPumpOffTime = zeroTime
            return 2

    # ------------timer set 2 -----------------
    if (pumpOnTime2 == now):
        log.log(log.ALWAYS, "PumpOnEvent2 fired")
        if (gv.pumpPower == OFF):
            equipment.pumpPower(ON)
            lastPumpOnTime = pumpOnTime2
            nextPumpOffTime = pumpOffTime2
            return 3

    if (pumpOffTime2 == now):
        log.log(log.ALWAYS, "PumpOffEvent2 fired")
        # don't turn off if in spa mode
        if (gv.systemMode != c.SPA_ON):
            equipment.pumpPower(OFF)
            nextPumpOffTime = zeroTime
            return 4

    # --------- set 3 manual or cooldown mode -------------------
    # timer 3 has no on time event
    if (pumpOffTime3 == now):
        log.log(log.ALWAYS, "PumpOffEvent3 fired")
        # if (gv.pumpPower == ON):
        equipment.pumpPower(OFF)
        lastPumpOn = zeroTime
        nextPumpOffTime = zeroTime
        # clear event to prevent a retrigger
        pumpOffTime3 = zeroTime
        return 6

    # ----------- spa off event -----------------

    if (spaOffTime == now):
        log.log(log.ALWAYS, "SpaOffEvent fired")
        equipment.heaterEnable(OFF)
        equipment.heaterPower(OFF)

        # set pump off time & clear event
        setPumpOffEvent(0, 15)
        log.log(log.ALWAYS, "PumpOffEvent3 set")
        spaOffTime = zeroTime
        lcd.message("Pump will remain on for 15 minutes for cooldown")
        time.sleep(10)
        return 5

    # if nothing happened, return 0 (future)
    return 0
Ejemplo n.º 22
0
        lcd.message("         Made by:", "  Jorge Gutierrez")
        sleep(3)
        lcd.message("", "")
        os.system("sudo init 0")  #Turn off raspberry

    cv2.destroyAllWindows()


#-------------Init code---------------#
try:
    lcd.init()
except:
    print("Fail display oled sh1106 module")
lcd.logo("raspi")
sleep(2)
lcd.message("         Stewart", "  Plataform  6DOF")
sleep(2)
lcd.message("     BALL AND", "         PLATE")
sleep(2)
for i in range(3):
    lcd.logo(logos[i])
    sleep(2)


def main():
    try:
        while True:
            setup(menu)
    except KeyboardInterrupt:
        print("Closing program")
    #except:
Ejemplo n.º 23
0
def pumpOff():
    lcd.message("Turning Off Pump... ")
    pumpPower(OFF)
    gv.systemMode = config.OFF
    timer.clearPumpOffEvent()
    return
Ejemplo n.º 24
0
def pumpOn(hours):
    lcd.message("Turning on Pump... ")
    pumpPower(ON)
    timer.setPumpOffEvent(hours, 0)
    gv.systemMode = config.MANUAL
    return
Ejemplo n.º 25
0
def setup(menu_insert):
    global menu
    global counter
    global funtion
    global Kp
    global Ki
    global Kd
    global change_set_point
    #Values for plotting
    xy_label = []
    yy_label = []
    x_label = []
    list_point_x = []
    list_point_y = []

    #baterry
    get_voltaje = battery()
    #print(get_voltaje)
    while get_voltaje < 180:  #Value for low voltage
        get_voltaje = battery()
        lcd.message("     Low Battery", "      Recharge")

    #Setup menu in OLED display
    if (menu == 0):
        lcd.write("Control", "Prepare", "Setup", "OFF", True, counter)
    elif (menu == 1):  #Control
        lcd.write("PID serie", "PID parallel", "GAME", "Back", True, counter)

    elif (menu == 2):  #Prepare
        lcd.write("Pitch, Roll", "Show", "Height", "Back", True, counter)

    elif (menu == 3):  #Setup
        lcd.write("Set PID S", "Set PID P", "Conection PC", "Back ", True,
                  counter)

    elif (menu == 4):  #Pitch and roll
        lcd.write("Pitch(y)", "Roll(x)", "Pitch & Roll", "Back ", True,
                  counter)

    elif (menu == 5):  #show
        lcd.write("Show camera", "Plotting", "", "Back", True, counter)

    elif (menu == 6):  #setup PID serie
        lcd.write("Proportional", "Integral", "Derivative", "Back ", True,
                  counter)

    elif (menu == 7):  #setup PID parallel
        lcd.write("Proportional", "Integral", "Derivative", "Back ", True,
                  counter)

    elif (menu == 8):  #show plot (yes/no)
        lcd.write("", "", " Yes", " No ", True, counter)

    if funtion == 1:
        lcd.message("            PID", "           Serie")
    if funtion == 2:
        lcd.message("            PID", "         Paralell")
    while funtion == 3:  #GAMe
        lcd.write("   Put the ball", "  on the center", "  with joystick", "",
                  False, counter)

        values = camera.position(
            show=False)  #get position (x,y and ball on plate)
        ball_on_plate = values[2]
        if ball_on_plate == True:
            for i in range(3):
                lcd.message("         Ready?", "             " + str(3 - i))
                sleep(1)
            lcd.message("           Go!", "")
            while ball_on_plate == True:
                position = joystick()
                pitch = position[0]
                roll = position[1]
                values = camera.position(show=False)
                x_position = values[0]
                y_position = values[1]
                ball_on_plate = values[2]
                if x_position <= 10 and x_position >= -10 and y_position <= 10 and y_position >= -10:
                    lcd.message("        Winner!", "          :)")

                set_plataform([0, pitch, roll], [0, 0, 117])

            if ball_on_plate == False:
                lcd.message("        Looser!", "          :(")
                sleep(3)

#main funtions(case)
    while funtion == 1 or funtion == 2:  #Control PID Paralell and serial
        for i in range(time_plot):
            global area_x
            global area_y
            global error_anterior_x
            global error_anterior_y

            values = camera.position(
                show=False)  #get position (x,y and ball on plate)
            x_position = values[0]
            y_position = values[1]
            ball_on_plate = values[2]

            value_joystick = joystick()
            value_change = value_joystick[0]

            if value_change >= 6.5:
                change_set_point = change_set_point + 1
                sleep(0.1)
                if change_set_point >= 7: change_set_point = 7
                print("Set point :" + position_plataform[change_set_point])
            if value_change <= -6.5:
                change_set_point = change_set_point - 1
                sleep(0.1)
                if change_set_point < 0: change_set_point = 0
                print("Set point :" + position_plataform[change_set_point])

            if (funtion == 1):  #Gain PID serie
                Kp = 1
                Ki = 0
                Kd = 0

            if (funtion == 2):  #Gain PID parallel
                Kp = 1.55
                Ki = 0.22
                Kd = 18

            if change_set_point <= 6:
                set_point_x = positions_x[change_set_point]
                set_point_y = positions_y[change_set_point]

            if change_set_point == 7:
                if show_plot == False:
                    if i < (time_plot / 2):
                        side = "up"
                    if i >= (time_plot / 2):
                        side = "down"
                        i = time_plot - i
                    set_point_x = (time_plot / 2) - abs(i * 2)
                    set_point_y = set_circle((time_plot / 2) - abs(i * 2),
                                             side)
                else:
                    print("Turn off plotting, please")

            #set_point_x=0
            #set_point_y=0

            error_x = set_point_x - x_position  # x position error
            error_y = set_point_y - y_position  # y position error

            if (integration_time.ticker > 1):  #Integrative time
                area_x = (error_x / DIV_KI) + area_x
                area_y = (error_y / DIV_KI) + area_y
                if (area_x > 5): area_x = 5
                if (area_y > 5): area_y = 5
                if (area_x < -5): area_x = -5
                if (area_y < -5): area_y = -5
                integration_time.ticker = 0

            derivate_x = (error_x - error_anterior_x) / DIV_KD
            derivate_y = (error_y - error_anterior_y) / DIV_KD

            controller_px = (Kp * error_x / DIV_KP)
            controller_ix = (Ki * area_x)
            controller_dx = derivate_x * Kd
            controller_py = (Kp * error_y / DIV_KP)
            controller_iy = (Ki * area_y)
            controller_dy = derivate_y * Kd

            if (funtion == 1):  #PID serie algorithm
                pitch = controller_px * (controller_ix + 1) * (controller_dx +
                                                               1)
                roll = controller_py * (controller_iy + 1) * (controller_dy +
                                                              1)

            if (funtion == 2):  #PID paralell algorithm
                pitch = controller_px + controller_ix + controller_dx
                roll = controller_py + controller_iy + controller_dy

            if (pitch >= 6.5): pitch = 6.5
            if (pitch <= -6.5): pitch = -6.5
            if (roll >= 6.5): roll = 6.5
            if (roll <= -6.5): roll = -6.5

            x_platform = pitch
            y_platform = -roll

            if (ball_on_plate == True):  #ball must be on plate
                set_plataform([0, -pitch, roll], [x_platform, y_platform, 117])
                print("X={}, Y={},".format(x_position, y_position))
            else:
                set_plataform([0, 0, 0], [0, 0, 117])
                area_x = 0
                area_y = 0

            #print("X={}, Y={}, area_x{}, pitch{}".format(x_position,y_position,area_x,pitch))
            #lcd.message("   X = {}".format(x_position),"   Y = {}".format(y_position))
            menu = 0

            error_anterior_x = error_x
            error_anterior_y = error_y

            if show_plot:
                xy_label = np.append(xy_label, x_position)
                yy_label = np.append(yy_label, y_position)
                x_label = np.append(x_label, i)
                list_point_x = np.append(list_point_x, set_point_x)
                list_point_y = np.append(list_point_y, set_point_y)

        if show_plot:
            plotting()
            ax[0].plot(x_label, xy_label, "b", label="x position")
            ax[0].plot(x_label, list_point_x, "r--", label="set point")
            ax[1].plot(x_label, yy_label, "g", label="y position")
            ax[1].plot(x_label, list_point_y, "r--", label="set point")
            ax[0].legend(loc="upper right")
            ax[1].legend(loc="upper right")
            plt.show()

            yy_label = []
            xy_label = []
            x_label = []
            list_point_x = []
            list_point_y = []

    while funtion == 4:  #Height
        position = joystick()
        height = position[1]
        set_plataform([0, 0, 0], [0, 0, 116 + height])
        lcd.message("         Height    ",
                    "Length:{:.2f}".format(116 + height) + "mm")
        menu = 2

    while funtion == 5:  #IP direction
        ip_message = " Searching IP"
        for i in range(4):
            lcd.message(ip_message, "")
            ip_message += "."
            sleep(0.5)
        ip = get_ip()
        if ip is None:
            lcd.message("  IP not found", "")
            sleep(2)
        while ip is not None and funtion == 5:
            lcd.message("  IP Found:", "  IP:{}".format(ip))

    while (funtion == 6 or funtion == 7
           or funtion == 8):  # move Pitch and roll
        position = joystick()
        pitch = position[0]
        roll = position[1]
        if funtion == 6:  #Pitch
            set_plataform([0, pitch, 0], [0, 0, 117])
            lcd.message("           Pitch    ",
                        "      Angle:{:.2f}".format(pitch) + "°")
        elif funtion == 7:  #Roll
            set_plataform([0, 0, roll], [0, 0, 117])
            lcd.message("            Roll    ",
                        "      Angle:{:.2f}".format(roll) + "°")
        elif funtion == 8:  #Pitch and roll
            set_plataform([0, pitch, roll], [0, 0, 117])
            lcd.message("Pitch = {:.2f}".format(pitch) + "°",
                        "Roll = {:.2f}".format(roll) + "°")
        menu = 2

    while funtion == 9 or funtion == 10 or funtion == 11:
        lcd.message("         Funtion", "    no supported".format(Kp))

    counter_serial = 0  #Gains for Kp,Ki,Kd
    while funtion == 15 or funtion == 16 or funtion == 17:

        value_joystick = joystick()
        selector = value_joystick[1]
        if selector > 6: counter_serial = counter_serial + 0.01
        elif selector < -6: counter_serial = counter_serial - 0.01
        elif selector > -6 and selector < 6:
            counter_serial = counter_serial + 0

        if funtion == 15:
            Kp = Kp + counter_serial
            lcd.message("Proportional", "     Kp={}".format(Kp))
            if Kp == 1.55:
                lcd.message("Proportional", "     Kp={}".format(Kp) + "*Recom")

        if funtion == 16:
            Ki = Ki + counter_serial
            lcd.message("Integral", "     Ki={:.2f}".format(Ki))
            if Ki == 0.22:
                lcd.message("Integral", "     Ki={}".format(Ki) + "*Recom")

        if funtion == 17:
            Kd = Kd + counter_serial
            lcd.message("Derivative", "     Kd={}".format(Kd))
            if Kd == 18:
                lcd.message("Derivative", "     Kd={}".format(Kd) + "*Recom")

    while funtion == 14:
        values = camera.position(show=True)
        lcd.message("       CAMERA", "")
        menu = 5

    while funtion == 18:
        os.system("exit")
        sleep(0.5)
        lcd.message("       Bye   Bye", "          ;)")
        sleep(1)
        lcd.message("         Made by:", "  Jorge Gutierrez")
        sleep(3)
        lcd.message("", "")
        os.system("sudo init 0")  #Turn off raspberry

    cv2.destroyAllWindows()
Ejemplo n.º 26
0
# Torrent Operating boX's Integrated Client (TOXIC)

from os import system as sys
from time import sleep
from transmission import Transmission
import lcd


lcd = lcd.lcd()
lcd.begin(16,2)
lcd.clear()

sys("service transmission-daemon start")
lcd.clear()
lcd.message("Booting to TOXIC\nT-  seconds left")
for i in range(5,0,-1):
	lcd.setCursor(2,1)
	lcd.message(str(i))
	sleep(1)

# Enter specific details here
client = Transmission(host='IP_ADDRESS', port=PORT, username='******', password='******')
lcd.clear()
lcd.message("TOX: __d __s __p\nUp:____|Dwn:____")

def adjust(speed):
	speed = int(speed)/1024
	if speed < 1000 :
		speed = str(str(speed)+'K').rjust(4)
	else :
		speed = str(float(speed)/1024)
Ejemplo n.º 27
0
	password = sys.argv[2]
	
	mailmanager = Mailmanager(login, password)
	mail = mailmanager.mail

	lcd.lcd_init()
	
	log("Control Server started\n")
	
	
	
	try :
		state = 'off'
		GPIO.output(config.backlightPin, False)
		lcd.home()
		lcd.message('Message service', style=2)
		lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
		lcd.message('started', style=2)        
		time.sleep(3)
		while True:            
			lcd.clear()
			time.sleep(.1)
			if config.verbose: log('Checking messages...')
			lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
			lcd.message("Checking", style=2)
			lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
			lcd.message("messages", style=2)
			time.sleep(3)
			number = 0
			
			try :
Ejemplo n.º 28
0
	def off(self) :    
		lcd.home()       
		lcd.message("OFF command") 
		GPIO.output(config.lightsPin, False)                                  
		time.sleep(config.displayTime)
Ejemplo n.º 29
0
	def on(self) :
		lcd.clear()
		lcd.message("ON command")
		GPIO.output(config.lightsPin, True)        
		time.sleep(config.displayTime)