Exemplo n.º 1
0
def main() -> None:
    global desired_temperature, room_temperature, screen, sense, semaphore

    sensor_thread: Thread
    events_thread: Thread

    try:
        print(
            f'{colors.GREEN}Initializing the thermostat using sense hat{colors.END}'
        )
        sense = SenseHat()
        sense.clear()

        desired_temperature = room_temperature = sense.get_temperature()

        print(f'{colors.GREEN}Connecting to screen via socket{colors.END}')
        screen = connect(host, port)

        print(f'{colors.GREEN}Initializing application threads{colors.END}')
        semaphore = Semaphore()

        sensor_thread = Thread(target=display)
        events_thread = Thread(target=process)
    except:
        print(f'{colors.RED}Failed to initialize the thermostat{colors.END}')
        print('Error: {}'.format(sys.exc_info()))
        sys.exit(1)

    print(f'{colors.GREEN}Initialization complete!{colors.END}')

    sensor_thread.start()
    events_thread.start()
Exemplo n.º 2
0
    def display_weather(self):
        sense_emulator = SenseHat()
        message = "%s %sC %s wind speed %s km/h" % (
            self.city, self.temperature, self.weather_conditions,
            self.wind_speed)

        sense_emulator.show_message(message)
 def display(self):
     sense_hat_emulator = SenseHat()
     
     message = ("%s %sC %s wind speed %s km/h"
        %(self.current_weather.getCity(),
        self.current_weather.getTemperature(),
        self.current_weather.getWeatherConditions(),
        self.current_weather.getWindSpeed()))
        
     sense_hat_emulator.show_message(message)
Exemplo n.º 4
0
    def __init__(self):
        self.sense = SenseHat()
        self.sense.low_light = True

        self.intro_msg()

        self.grid = Grid(colors["white"])
        self.sense.set_pixels(self.grid)

        self.cursor = Cursor(colors["pink"])
        self.tiles = [GameTile(i) for i in range(9)]

        self.players = [Player(colors["blue"]), Player(colors["red"])]
Exemplo n.º 5
0
def actuator_observer():
    sense = SenseHat()
    global temp_t
    global humi_t
    while True:
        time.sleep(1)
        print("TT = " + str(temp_t) + "\tTemp = " +
              str(sense.get_temperature()) + "\tHU= " + str(humi_t) +
              "\tHumidity = " + str(sense.get_humidity()))
        if sense.get_temperature() > float(
                temp_t) or sense.get_humidity() > float(humi_t):
            sense.clear(red)
        else:
            sense.clear(black)
Exemplo n.º 6
0
def main():
    ip = sys.argv[1]
    port = int(sys.argv[2])
    multicast = False

    # CREATE CoAP server
    server = CoAPServer(ip, port, multicast)
    print server

    # Create thread to get client threshold
    thread = Thread(target=listener, args=(server, ))
    thread.setDaemon(True)
    thread.start()

    # Initialize emulator
    sense = SenseHat()

    # Red color
    red = (255, 0, 0)

    while True:
        time.sleep(1)

        # Get values from emulator
        t = sense.get_temperature()
        p = sense.get_pressure()

        if t > server.t_lim or p > server.p_lim:  # if temperature and pressure values are above threshold
            sense.clear(red)  # turn on all red lights
        else:
            sense.clear()  # turn off all leds
Exemplo n.º 7
0
 def __init__(self,
              change_percent: float = 0.1,
              tick: float = 0.01,
              movement_check_interval: float = 1):
     self.sense = SenseHat()
     # amount of change to be considered movement
     self.change_percent = change_percent
     self.tick = tick  # sampling interval
     self.movement_check_interval = movement_check_interval
     self.orientation = self.sense.get_orientation()
     self._moved_event = threading.Event()
     TamperAlert._stop_event = threading.Event()
     self._moved_thread = threading.Thread(
         target=self._run,
         name=f'Moved-{threading.active_count()+1}',
         daemon=True)
     self._moved_thread.start()
Exemplo n.º 8
0
def main():
    path = "data.csv"

    sense = SenseHat()
    sense.clear()

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("", 50007))
    s.listen(1)
    soc, addr = s.accept()
    print("Connected by " + str(addr))

    while True:
        data = (soc.recv(1024)).decode()
        print("Client > ", data)
        if data == "q":
            soc.close()
            break
        elif data == "y":
            t = str(sense.get_temperature())
            h = str(sense.get_humidity())
            p = str(sense.get_pressure())
            data = t + "," + h + "," + p
            with open(path, mode="a") as f:
                f.write(
                    (datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S") +
                    "," + data + "\n")
        else:
            data = input("Server > ")
        print("data = " + data)
        soc.send(data.encode())
    print("Finished.")
Exemplo n.º 9
0
def sensor_hat():
    sense = SenseHat()

    last_humidity = 0
    while True:
        time.sleep(wait_for)
        humidity = int(sense.humidity)
        if humidity > last_humidity + 1 or humidity < last_humidity - 1:
            send_to_aws(humidity)
            last_humidity = humidity
Exemplo n.º 10
0
def main():
    # 1. init sense_hat
    sense_emu = SenseHat()  # instantiate a sense_hat object

    # 2. init MQTT
    client = init_mqtt()

    # 3. enter MQTT loop
    client_loop(client, sense_emu)
    exit(0)
Exemplo n.º 11
0
def init():
    if configState.config["simulateSenseHat"]:
        from sense_emu import SenseHat
    else:
        from sense_hat import SenseHat

    global sense
    sense = SenseHat()

    global display
    display = SenseHatCounter()
Exemplo n.º 12
0
    def __init__(self, n):
        """
        Initializes a Board object of size n x n

        Parameters:
            n -- size for n x n grid to create

        Post-Condition:
            An instance of a Board object
        """
        self._grid = []
        self._ships = []
        self._sense = SenseHat()
        self._sense.clear(0, 0, 255)

        for i in range(n):
            row = []
            for j in range(n):
                new_pos = GridPos(i, j)
                row.append(new_pos)
            self._grid.append(row)
Exemplo n.º 13
0
def main():
    sense = SenseHat()
    sense.clear()

    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    soc.connect(("127.0.0.1", 50007))
    print("Connected.")

    while True:
        data = input("Client (q: quit, y: recv data) > ")
        soc.send(data.encode())
        if data == "q":
            soc.close()
            break
        data = (soc.recv(1024)).decode()
        print("cServer > ", data)
        if (data[0] >= "0" or data[0] <= "9"):
            datastr = data.split(",")
            print("data received: ", datastr)
            mylist = [float(i) for i in datastr]
            THI = 0.81 * mylist[0] + 0.01 * mylist[1] * (0.99 * mylist[0] -
                                                         14.3) + 46.3
            if (THI < 60):
                x = 255 * (THI - 45) / 60
                RGB = [x, 0, 255 - x]
            elif (THI < 75):
                RGB = [0, 255, 0]
            else:
                x = 255 * (THI - 75) / 110
                RGB = [x, 255 - x, 0]
            print("THI: " + str(THI) + ", RGB:" + str(RGB))
            sense.clear(RGB[0], RGB[1], RGB[2])
    print("Finished.")
Exemplo n.º 14
0
    def __init__(self):
        self.sense = SenseHat()

        self.midiendo = True  # Mediciones activas
        self.data_points = list()  # Puntos para la gráfica

        self.queue = queue.Queue()  # Para comunicacion con hebra worker
        self.cuadrados = dict(
        )  # Para ahorrar recursos GUI guardamos los cuadrados

        self.list_max = [105, 1260, 100]  # Temp, pres, hum
        self.periodo = self.PERIODO_INICIAL

        self.ventana1 = tk.Tk()
        self.ventana1.title("Práctica GUI SenseHat")

        self.agregar_menu()

        self.cuaderno1 = ttk.Notebook(self.ventana1)
        self.pagina1 = ttk.Frame(self.cuaderno1)
        self.cuaderno1.add(self.pagina1, text="Monitorización")

        self.pagina2 = ttk.Frame(self.cuaderno1)
        self.cuaderno1.add(self.pagina2, text="Gráfica")

        self.cuaderno1.grid(column=0, row=0)

        # Página 1
        self.control()
        self.mediciones()
        self.canvas()
        self.historico()

        # Página 2
        self.matplotlib()

        # Ya no utilizado. Controlando posición desde el emulador
        #self.ventana1.bind("<KeyPress>", self.presion_tecla)
        #self.ventana1.bind("<Button-1>", self.presion_raton)

        # Lento
        # while True:
        #    self.medir()
        #    self.ventana1.update()
        #    time.sleep(1)

        self.ventana1.after(self.periodo, self.llamada_medir)
        self.ventana1.after(1000, self.comprobar_joystick)
        self.ventana1.mainloop()
Exemplo n.º 15
0
def test_periodic_task():
    from weather_station.sensors import SensorManager
    from sense_emu import SenseHat
    import time

    hat = SenseHat()
    manager = SensorManager.PeriodicTask(hat.get_humidity, 1, 20)
    manager.start()

    while True:
        average = manager.get_average()
        print("average = " + str(average.timestamp) + ", " +
              str(average.value))
        time.sleep(0.25)
        print("out of sleep")
Exemplo n.º 16
0
    def comenzar(self):
        if (self.comienzo == False):

            self.comienzo = True
            self.boton1.configure(text="Parar")
            periodo = 10
            i = 0
            sense = SenseHat()
            while (i < periodo):
                self.medir(sense)
                i += 1

        else:
            self.comienzo = False
            self.boton1.configure(text="Comenzar")
Exemplo n.º 17
0
def main():
    global sense
    global pixels
    global host
    global port
    global limiares_temperature
    global limiares_pressure
    global last_temperature
    global last_pressure
    
    # initialize the sensehat and set outliers as pre-sensored data for temperature and pressure
    sense = SenseHat()
    last_temperature=999999
    last_pressure=999999
    
    # initialize arrays for the LEDs and thresholds
    pixels = [None]*64
    limiares_temperature = [None]*64
    limiares_pressure = [None]*64
    for i in range(64):
        pixels[i] = (0,0,0)
        limiares_temperature[i] = 105 # highest temperature possible from the sensor, so the LEDs initiate turned OFF
        limiares_pressure[i] = 1260 # highest pressure possible from the sensor, so the LEDs initiate turned OFF
 
    # convert arguments into variables: host and port of the server
    host = sys.argv[1]
    port = int (sys.argv[2])
    
    # create the server
    server = CoAPServer(host, port)
    
    # this thread will be responsible for observing CoAP for changes in clients' thresholds
    clients_thread = Thread(target = clients_thread_function)
    clients_thread.setDaemon(True)
    clients_thread.start()
    
    # this thread will control the sensehat board
    sensehat_thread = Thread(target = gerencia_a_sensehat)
    sensehat_thread.setDaemon(True)
    sensehat_thread.start()
    
    # server starts listening for communication
    try:
        server.listen(10)
    except KeyboardInterrupt:
        server.close()
        sys.exit()
Exemplo n.º 18
0
    def __init__(self):
        self.sense = SenseHat()

        self.medir = True

        self.queue = queue.Queue()

        self.periodo = self.periodo_inicial

        self.ventana = tk.Tk()
        self.ventana.title("Practica GUI SenseHat")

        #Creamos las opciones
        menubar1 = tk.Menu(self.ventana)
        self.ventana.config(menu=menubar1)
        opciones1 = tk.Menu(menubar1)
        opciones1.add_command(label="Configurar Periodo",
                              command=self.cambiar_periodo)
        menubar1.add_cascade(label="Opciones", menu=opciones1)

        #Creamos la ventana Monitorizacion
        self.cuaderno1 = ttk.Notebook(self.ventana)
        self.pagina1 = ttk.Frame(self.cuaderno1)
        self.cuaderno1.add(self.pagina1, text="Monitorizacion")

        self.labelframe1 = ttk.LabelFrame(self.pagina1, text="Control")
        self.labelframe1.grid(column=0, row=1, padx=5, pady=10)
        self.control()

        self.labelframe2 = ttk.LabelFrame(self.pagina1, text="Medidas")
        self.labelframe2.grid(column=0, row=2, padx=5, pady=10)
        self.medidas()

        self.labelframe3 = ttk.LabelFrame(self.pagina1, text="Historico")
        self.labelframe3.grid(column=0, row=3, padx=5, pady=10)
        self.historico()

        #Creamos la ventana Gráfico
        self.pagina2 = ttk.Frame(self.cuaderno1)
        self.cuaderno1.add(self.pagina2, text="Gráfica")

        self.cuaderno1.grid(column=0, row=0, sticky='WE')

        Worker(self.queue).start()
        self.ventana.after(self.periodo, self.process_queue)
        self.ventana.mainloop()
def main():
    parser = argparse.ArgumentParser(description="Example Robot Raconteur iRobot Create service")    
    parser.add_argument("--nodename",type=str,default="sense_hat.SenseHat",help="The NodeName to use")
    parser.add_argument("--tcp-port",type=int,default=2354,help="The listen TCP port")
    parser.add_argument("--wait-signal",action='store_const',const=True,default=False)
    args = parser.parse_args()
    sense = SenseHat()
    imu_service=Sense_hat_IMU(sense)
    sensor_hat_service=Sense_hat(sense,imu_service)

    
    with RR.ServerNodeSetup(args.nodename,args.tcp_port) as node_setup:
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.uuid")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.identifier")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.geometry")
        
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.color")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.datetime")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.sensordata")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.resource")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.device")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.datatype")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.param")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.units")
        
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.sensor")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.imu")
        RRN.RegisterServiceTypeFromFile("experimental.sensehat")
        RRN.RegisterService("SensorHat","experimental.sensehat.SenseHat",sensor_hat_service)
        RRN.RegisterService("SensorHatIMU","com.robotraconteur.imu.ImuSensor",imu_service)
        sensor_hat_service.joystick_thread.start()
    
        if args.wait_signal:  
            #Wait for shutdown signal if running in service mode          
            print("Press Ctrl-C to quit...")
            import signal
            signal.sigwait([signal.SIGTERM,signal.SIGINT])
        else:
            #Wait for the user to shutdown the service
            if (sys.version_info > (3, 0)):
                input("Server started, press enter to quit...")
            else:
                raw_input("Server started, press enter to quit...")
Exemplo n.º 20
0
    def read(self):

        self.api.app.logger.info("Sense HAT Emulator")
        sensor = SenseHat()
        try:
            humidity = 64 * sensor.humidity / 100
            temperature = sensor.temp
            self.api.app.logger.info(humidity)
            self.api.app.logger.info(temperature)

            if self.type == "humidity":
                self.data_received(round(humidity, 2))
            if self.type == "temperature":
                if self.get_config_parameter("unit", "C") == "C":
                    self.data_received(round(temperature, 2))
                else:
                    self.data_received(round((9.0 / 5.0 * temperature) + 32,
                                             2))
        except Exception as e:
            self.api.app.logger.error("Sense Hat Emulator error")
Exemplo n.º 21
0
def test_joystick_handler(args):
    from weather_station.joystick import joystick_handler
    from sense_emu import SenseHat
    import time

    hat = SenseHat()

    handler = joystick_handler.Stick_Daemon(hat.stick)
    handler.register_callback(joystick_handler.Direction.MIDDLE,
                              joystick_handler.Action.RELEASED,
                              middle_released_callback)
    handler.register_callback(joystick_handler.Direction.MIDDLE,
                              joystick_handler.Action.PRESSED,
                              middle_pressed_callback)
    handler.start()

    while run:
        time.sleep(1)

    print("exiting!")
    return 0
Exemplo n.º 22
0
def main(args):
    import threading
    import time
    from sense_emu import SenseHat
    from weather_station.sensors import SensorManager

    manager = SensorManager.SensorManager(SenseHat())
    manager.start()

    def get_averages():
        print("----------------")
        for sensor in SensorManager.SensorEnum:
            print(sensor.name)
            print(manager.get_average(sensor).value)
        print("----------------")

    for i in range(0, 360):
        print(i)
        time.sleep(1)
        get_averages()

    manager.stop()

    print("exit!")
Exemplo n.º 23
0
def shat():
    sense = SenseHat()
    sense.clear()
    g = (0, 255, 0)
    k = (0, 0, 0,)
    r = (255, 0, 0,)
    y = (255, 255, 0,)



    draw_pixels = [
        g, g, g, g, g, g, g, g,
        g, g, g, g, g, g, g, g,
        g, k, k, g, g, k, k, g,
        g, k, k, g, g, k, k, g, 
        g, g, g, k, k, g, g, g,
        g, g, k, k, k, k, g, g,
        g, g, k, k, k, k, g, g,
        g, g, k, g, g, k, g, g,
    ]


    sense.set_pixels(draw_pixels)
Exemplo n.º 24
0
import socket
import sys
import numpy as np
from time import sleep
from sense_emu import SenseHat
import pickle

import argparse

my_parser = argparse.ArgumentParser()
my_parser.add_argument('-i', action='store', type=str, required=True)
my_parser.add_argument('-p', action='store', type=int, required=True)

args = my_parser.parse_args()

hat = SenseHat()

while True:
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    server_address = (args.i, args.p)

    try:
        message = [hat.temperature, hat.pressure, hat.humidity]
        print('Sending {!r}'.format(message))
        sent = sock.sendto(pickle.dumps(message), server_address)
    finally:
        print('Closing socket')
        sock.close()
    sleep(0.5)
Exemplo n.º 25
0
# *****************************************************
# weather_lab03a.py - Adding low temperature logic
# *****************************************************

# Import SenseHat from the SenseHat Emulator library
# and sleep from the time library
from sense_emu import SenseHat
from time import sleep

# Instantiate (create) a variable to access the SenseHat Emulator
sense = SenseHat()

# Define the number of readings to take
maxReadings = 10

# Define a counter. In programming, most counters begin at 0
counter = 0

# Create two variables to hold the high and low temperatures
highTemp = 0.00
lowTemp = 999.00 # Why set it to 999?

# Print a header
print("#, Temperature, Pressure, Humidity, High Temp, Low Temp")

# This while loop will execute NUM_READINGS times
while counter < maxReadings:

    # Read temperature, humidity and pressure into local variables
    temperature = sense.temperature
    humidity = sense.humidity
Exemplo n.º 26
0
from sense_emu import SenseHat
sense = SenseHat()
blue = (0, 0, 255)
yellow = (255, 255, 0)

sense.show_message("Egham Raspberry Jam is awesome",
                   text_colour=yellow,
                   back_colour=blue)
Exemplo n.º 27
0
def send():
    sense = SenseHat()
    user = request.form['message']
    name = request.form['from']
    sense.show_message(user + " From " + name)
    return ('Message Received')
Exemplo n.º 28
0
import math
from pygame.locals import *
from led import LED
from buttons import Button
import png # pypng

from sense_emu import SenseHat

import copy, time

saved = True
warning = False
pygame.init()
pygame.font.init()

sh=SenseHat()
screen = pygame.display.set_mode((530, 395), 0, 32)
pygame.display.set_caption('Sense HAT Grid Editor')
pygame.mouse.set_visible(1)

background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((0, 51, 25))
colour = (255,0,0) # Set default colour to red
rotation = 0
frame_number  = 1
fps = 4



def setColourRed():
from sense_emu import SenseHat
"""import some functions"""
import random
from random import choice
from random import randint
from time import sleep
"""connect to the senseHat"""
sense = SenseHat()
"""set he colors : red, green, blue, yellow"""
r = (255, 0, 0)
g = (0, 255, 0)
b = (0, 0, 255)
y = (255, 255, 0)
"""define a function for random color"""


def random_colour():
    rand_r = randint(0, 255)
    rand_g = randint(0, 255)
    rand_b = randint(0, 255)
    rand_y = randint(0, 255)
    return (rand_r, rand_g, rand_b)


"""Display text one letter at a time, random colour"""
sense.show_letter("I", random_colour(), back_colour=r)
sleep(0.8)
sense.show_letter("L", random_colour(), back_colour=g)
sleep(0.5)
sense.show_letter("O", random_colour(), back_colour=b)
sleep(0.5)
# reading and writing to the sensehat with python

from sense_emu import SenseHat
from time import sleep

mySenHa = SenseHat()

mySenHa.show_message("Hello", text_colour=[100, 200, 150])

mySenHa.load_image("raspberry.jpg")
sleep(5)

myHumidity = mySenHa.get_humidity()
humidString = str(myHumidity)
mySenHa.show_message(humidString)
Exemplo n.º 31
0
from time import sleep
#from sense_hat import SenseHat
from sense_emu import SenseHat
sense = SenseHat()

y = 4
ball_position = [3, 3]
ball_velocity = [1, 1]

def draw_bat():
    sense.set_pixel(0, y, 255, 255, 255)
    sense.set_pixel(0, y+1, 255, 255, 255)
    sense.set_pixel(0, y-1, 255, 255, 255)
        
def move_up(event):
    global y
    if y > 1 and event.action=='pressed':
        y -= 1
    print(event)

def move_down(event):
    global y
    if y < 6 and event.action=='pressed':
        y += 1
    print(event)

def draw_ball():
    sense.set_pixel(ball_position[0], ball_position[1], 0, 0, 255)
    ball_position[0] += ball_velocity[0]
    ball_position[1] += ball_velocity[1]
    if ball_position[0] == 7:
Exemplo n.º 32
0
from time import sleep
#from sense_hat import SenseHat
from sense_emu import SenseHat
sense = SenseHat()


sense.clear(0, 0, 0)

y = 4
ball_position=[6, 3]
ball_speed=[-1, -1]

def draw_bat():
    sense.set_pixel(0, y, 255, 255, 255)
    sense.set_pixel(0, y+1, 255, 255, 255)
    sense.set_pixel(0, y-1, 255, 255, 255)
        
def ball_play():
    sense.set_pixel(ball_position[0], ball_position[1], 0, 0, 0)

    ball_position[0] += ball_speed[0]
    ball_position[1] += ball_speed[1]

    if ball_position[1] == 0 or ball_position[1] == 7:
        ball_speed[1] = -ball_speed[1]
    if ball_position[0] == 7:
        ball_speed[0] = -ball_speed[0]
    if ball_position[0] == 1 and y-1 <= ball_position[1] <= y+1:
        ball_speed[0] = -ball_speed[0]
    if ball_position[0] == 0:
        return False