class SenseHATBaseTest(BaseTest): def __init__(self, descriptor, outsubdir, runner): BaseTest.__init__(self, descriptor, outsubdir, runner) self.BASE_DIR = os.path.join(self.project.root, '..') os.environ["LD_LIBRARY_PATH"] = self.BASE_DIR + os.pathsep + os.environ["LD_LIBRARY_PATH"] self.sense = SenseHat() def start(self): self.correlator = CorrelatorHelper(self) self.correlator.start() def clearPixels(self): self.sense.clear() def getPixel(self, x, y): return self.sense.get_pixel(x, y) # 3 bits lost for red, 2 for green and 3 for blue def checkPixel(self, x, y, values): values[0] = int(8*math.floor(values[0] / 8)) values[1] = int(4*math.floor(values[1] / 4)) values[2] = int(8*math.floor(values[2] / 8)) self.assertTrue(self.getPixel(x, y) == values) def getTemperature(self): return self.sense.get_temperature() def getHumidity(self): return self.sense.get_humidity() def getPressure(self): return self.sense.get_pressure()
def test(self): sense = SenseHat() sense.clear() time.sleep(1) sense.clear(tint) time.sleep(2) led_tint = sense.get_pixel(1, 1) self.assertListEqual( tint, led_tint, "Expected tint is {0} but Led tinted to {1}".format( tint, led_tint))
class StressLed(): def __init__(self, cycle_count): self.sense = SenseHat() self.failed_to_tint = {1: 0, 2: 0, 3: 0, 4: 0} self.tint = { 1: [216, 220, 200], 2: [176, 180, 200], 3: [96, 100, 200], 4: [8, 8, 200] } self.cycle_count = cycle_count def tint_led(self, tint): self.sense.clear() self.sense.clear(self.tint[tint]) time.sleep(2) return self.sense.get_pixel(1, 1) def compare_expected_tint_with_actual_led_tint(self, expected_tint, actual_tint): if (self.tint[expected_tint] == actual_tint): print "Passed to tint to tint{0}".format(expected_tint) return True else: self.failed_to_tint[expected_tint] += 1 print "failed to tint to tint{0} expected={1} but actual is{2} ".format( expected_tint, self.tint[expected_tint], actual_tint) return False def print_tint_result(self, tint, passed): if passed: print "{0} times tint to tint{1} passed".format( self.cycle_count, tint) else: print "{0} times tint to tint{1} failed out of {2} execution ".format( self.failed_to_tint[tint], tint, self.cycle_count, tint)
p3 = 0 == os.system('ping -qc 1 www.instagram.com >> /dev/null') p4 = 0 == os.system('ping -qc 1 www.latercera.com >> /dev/null') p5 = 0 == os.system('ping -qc 1 www.amazon.com >> /dev/null') p6 = 0 == os.system('ping -qc 1 www.pcfactory.cL >> /dev/null') now = datetime.datetime.now() if now >= now.replace(hour=8) and now <= now.replace(hour=22): lumi = int(sys.argv[1]) sense.low_light = False else: lumi = int(sys.argv[2]) sense.low_light = True for y in range(1, 8): for x in range(0, 8): p = sense.get_pixel(x, y) p[0] = int(p[0] * (0.2 + max(y, 6) / 10)) p[1] = int(p[1] * (0.2 + max(y, 6) / 10)) p[2] = int(p[2] * (0.2 + max(y, 6) / 10)) sense.set_pixel(x, y - 1, p) enciendeRGB(0, p0, lumi) enciendeRGB(1, p1, lumi) enciendeRGB(2, p2, lumi) enciendeRGB(3, p3, lumi) enciendeRGB(4, p4, lumi) enciendeRGB(5, p5, lumi) enciendeRGB(6, p6, lumi) randomRGB(7, lumi)
elif event.direction =='left': if CX-1 >= 0: CX = CX-1 PC = PC + 1 #If moved if CX != PX or CY != PY: #Hit a mine if MineStr.find('[' + str(CX) + ',' + str(CY) + ']') >= 0: S.set_rotation(270) S.show_message('You Lose!',0.05,R) ColCount = ColTot Lose = 1 else: #Get colour before change if S.get_pixel(CX,CY) == [0,0,0]: ColCount = ColCount+1 #Work out which colour it should be CP = ColourCheck(CX,CY,1) PP = ColourCheck(PX,PY,0) S.set_pixel(CX,CY,CP) S.set_pixel(PX,PY,PP) Lose = 0 #If you win if Lose!= 1: S.set_rotation(270) S.show_message('You win!',0.05,G) ED = datetime.datetime.now() S.show_message('Time take: ' + str(ED-SD),0.05,G)
spain_flag() sleep(3) sense.clear() for i in range(8): #set random green matrix dots for j in range(8): if randint(0,100) < 30: sense.set_pixel(i,j,(0,255,0)) flag = 1 count = 0 while flag: for i in range(8): #dim all for j in range(8): x = sense.get_pixel(i,j)[1] if x > 63: sense.set_pixel(i,j,(1,x-64,1)) elif x > 31: sense.set_pixel(i,j,(0,x-32,0)) for i in range(8): #move green matrix dots for j in range(8): x = sense.get_pixel(i,j)[1] if j>0 and x<63: y = sense.get_pixel(i,j-1) if y[1]>63 and y[0] < 63: sense.set_pixel(i,j,(255,255,255)) if count > 100:
class TestWeather(unittest.TestCase): @classmethod def setUpClass(cls): cls.expected_tint1 = [216, 220, 200] cls.expected_tint2 = [176, 180, 200] cls.expected_tint3 = [96, 100, 200] cls.expected_tint4 = [8, 8, 200] def setUp(self): self.currentTime = datetime.now() self.weather_data = { "base": "stations", "clouds": { "all": 75 }, "cod": 200, "coord": { "lat": 37.37, "lon": -122.04 }, "dt": 1524866340, "id": 420006359, "main": { "humidity": 48, "pressure": 1019, "temp": 65.79, "temp_max": 68, "temp_min": 62.6 }, "name": "Sunnyvale", "sys": { "country": "US", "id": 428, "message": 0.0056, "sunrise": 1524834996, "sunset": 1524884113, "type": 1 }, "visibility": 16093, "weather": [{ "description": "broken clouds", "icon": "04d", "id": 803, "main": "Clouds" }], "wind": { "deg": 360, "speed": 17.22 } } print self.currentTime # print int(time.time()) # print datetime.now() + timedelta(hours=2) # self.sunrise,self.sunrise_epoch,self.sunset,self.sunset_epoch= create_sunset_sunrise(self.currentTime,sunrise_hour=-10,sunset_hour=2) # print self.sunrise # print self.sunset self.sense = SenseHat() self.sense.clear() time.sleep(2) def test_clearing_glass_for_morning(self): expected = TestWeather.expected_tint1 sunrise, sunrise_epoch = create_sunset_sunrise(self.currentTime, hour=2) print "sunrise is {0}".format(str(sunrise)) self.weather_data = change_weather_data(self.weather_data, sunrise=sunrise_epoch) weather3.set_tint(self.weather_data) glass_tint = self.sense.get_pixel(1, 1) self.assertListEqual( glass_tint, expected, "Expected tint was tint1 ({0}) but actual tint is {1}".format( expected, glass_tint)) def test_clearing_glass_post_sunset(self): expected = TestWeather.expected_tint1 sunset, sunset_epoch = create_sunset_sunrise(self.currentTime, hour=-2) print "sunset is {0}".format(str(sunset)) self.weather_data = change_weather_data(self.weather_data, sunset=sunset_epoch) weather3.set_tint(self.weather_data) glass_tint = self.sense.get_pixel(1, 1) self.assertListEqual( glass_tint, expected, "Expected tint was tint1 ({0}) but actual tint is {1}".format( expected, glass_tint)) def test_current_time_between_sunsetPlusOne_and_sunriseSubOne_cloud_40( self): expected = TestWeather.expected_tint2 sunset, sunset_epoch = create_sunset_sunrise(self.currentTime, hour=1) sunrise, sunrise_epoch = create_sunset_sunrise(self.currentTime, hour=-1) print "sunrise is {0}".format(str(sunrise)) print "sunset is {0}".format(str(sunset)) self.weather_data = change_weather_data(self.weather_data, sunrise=sunrise_epoch, sunset=sunset_epoch, cloud=40) weather3.set_tint(self.weather_data) glass_tint = self.sense.get_pixel(1, 1) self.assertListEqual( glass_tint, expected, "Expected tint was tint2 ({0}) but actual tint is {1}".format( expected, glass_tint)) def test_current_time_between_sunsetPlusOne_and_sunriseSubOne_cloud_60( self): expected = TestWeather.expected_tint1 sunset, sunset_epoch = create_sunset_sunrise(self.currentTime, hour=1) sunrise, sunrise_epoch = create_sunset_sunrise(self.currentTime, hour=-1) print "sunrise is {0}".format(str(sunrise)) print "sunset is {0}".format(str(sunset)) self.weather_data = change_weather_data(self.weather_data, sunrise=sunrise_epoch, sunset=sunset_epoch, cloud=60) weather3.set_tint(self.weather_data) glass_tint = self.sense.get_pixel(1, 1) self.assertListEqual( glass_tint, expected, "Expected tint was tint1 ({0}) but actual tint is {1}".format( expected, glass_tint)) def test_current_time_between_sunsetPlusOne_and_sunriseSubOne_cloud_39_visibility_3000( self): expected = TestWeather.expected_tint2 sunset, sunset_epoch = create_sunset_sunrise(self.currentTime, hour=1) sunrise, sunrise_epoch = create_sunset_sunrise(self.currentTime, hour=-1) print "sunrise is {0}".format(str(sunrise)) print "sunset is {0}".format(str(sunset)) self.weather_data = change_weather_data(self.weather_data, sunrise=sunrise_epoch, sunset=sunset_epoch, cloud=39, visibility=3000) weather3.set_tint(self.weather_data) glass_tint = self.sense.get_pixel(1, 1) self.assertListEqual( glass_tint, expected, "Expected tint was tint2 ({0}) but actual tint is {1}".format( expected, glass_tint)) def test_current_time_between_sunsetPlusOne_and_sunriseSubOne_cloud_39_visibility_3001_temp_81( self): expected = TestWeather.expected_tint4 sunset, sunset_epoch = create_sunset_sunrise(self.currentTime, hour=1) sunrise, sunrise_epoch = create_sunset_sunrise(self.currentTime, hour=-1) print "sunrise is {0}".format(str(sunrise)) print "sunset is {0}".format(str(sunset)) self.weather_data = change_weather_data(self.weather_data, sunrise=sunrise_epoch, sunset=sunset_epoch, cloud=39, visibility=3001, temp=81) weather3.use_local_temp = False weather3.set_tint(self.weather_data) time.sleep(2) glass_tint = self.sense.get_pixel(1, 1) self.assertListEqual( glass_tint, expected, "Expected tint was tint4 ({0}) but actual tint is {1}".format( expected, glass_tint)) def test_current_time_between_sunsetPlusOne_and_sunriseSubOne_cloud_39_visibility_3001_temp_66( self): expected = TestWeather.expected_tint3 sunset, sunset_epoch = create_sunset_sunrise(self.currentTime, hour=1) sunrise, sunrise_epoch = create_sunset_sunrise(self.currentTime, hour=-1) print "sunrise is {0}".format(str(sunrise)) print "sunset is {0}".format(str(sunset)) self.weather_data = change_weather_data(self.weather_data, sunrise=sunrise_epoch, sunset=sunset_epoch, cloud=39, visibility=3001, temp=66) weather3.use_local_temp = False weather3.set_tint(self.weather_data) time.sleep(2) glass_tint = self.sense.get_pixel(1, 1) self.assertListEqual( glass_tint, expected, "Expected tint was tint3 ({0}) but actual tint is {1}".format( expected, glass_tint)) def test_current_time_between_sunsetPlusOne_and_sunriseSubOne_cloud_39_visibility_3001_temp_65( self): expected = TestWeather.expected_tint2 sunset, sunset_epoch = create_sunset_sunrise(self.currentTime, hour=1) sunrise, sunrise_epoch = create_sunset_sunrise(self.currentTime, hour=-1) print "sunrise is {0}".format(str(sunrise)) print "sunset is {0}".format(str(sunset)) self.weather_data = change_weather_data(self.weather_data, sunrise=sunrise_epoch, sunset=sunset_epoch, cloud=39, visibility=3001, temp=65) weather3.use_local_temp = False weather3.set_tint(self.weather_data) glass_tint = self.sense.get_pixel(1, 1) self.assertListEqual( glass_tint, expected, "Expected tint was tint2 ({0}) but actual tint is {1}".format( expected, glass_tint))
def fade( pixel ): new_pixel=[] for comp in pixel: if comp>0: new_pixel.append( comp-1) else: new_pixel.append( 0 ) return new_pixel while True: rx=random.randint(0,3) ry=random.randint(0,3) if random.randint(0,100) < 25: col=[ random.randint(0,255), random.randint(0,255), random.randint(0,255) ] if sense.get_pixel(rx,ry)==[0,0,0]: sense.set_pixel(rx, ry, col) sense.set_pixel(7-rx, ry, col) sense.set_pixel(7-rx, 7-ry, col) sense.set_pixel(rx, 7-ry, col) pixels=sense.get_pixels() new_pixels=[] for p in pixels: new_pixels.append( fade( p ) ) sense.set_pixels( new_pixels ) #sleep(0.1)
"blue": [0, 0, 248], "green": [0, 255, 0], "yellow": [255, 255, 0], # as [R,G,B] "cyan": [0, 255, 255], "white": [248, 252, 248], "black": [0, 0, 0], "off": [0, 0, 0], "orange": [248, 124, 0] #[R-7,G-3,B-7] } # End solution to task (2) while running: for event in pygame.event.get(): selected = False if event.type == KEYDOWN: if sense.get_pixel(x, y) == cursor: sense.set_pixel(x, y, color['black']) # Black 0,0,0 means OFF if event.key == K_DOWN and y < 7: y = y + 1 elif event.key == K_UP and y > 0: y = y - 1 elif event.key == K_RIGHT and x < 7: x = x + 1 elif event.key == K_LEFT and x > 0: x = x - 1 elif event.key == K_RETURN: ########################################################### # The following IF statements makes up solution to task (3) if sense.get_pixel(x, y) == color["white"]: sense.set_pixel(x, y, color['blue'])
color[i] += 25 if color[i] > 255: color[i] = 55 return color def blueGradient(): r = 0 g = 255 b = 55 grid = [[rgb(0, 0, 0) for x in range(8)] for y in range(8)] for i in xrange(0, 8): for j in xrange(0, 8): #print("[{},{},{}]".format(r,g,b)) sense.set_pixel(i, j, rgb(r, g, b)) b += 25 g -= 25 blueGradient() try: while True: for i in xrange(0, 8): for j in xrange(0, 8): #print("{}".format(sense.get_pixel(i,j))) sense.set_pixel(i, j, getNextColor(sense.get_pixel(i, j))) sleep(0.02) except KeyboardInterrupt: sense.clear()
rgbVal = [0,0,0] if cTemp <=BLUE_TEMP: rgbVal = [int(255*BRIGHTNESS),int(255*BRIGHTNESS),int(255*BRIGHTNESS)] elif cTemp>=RED_TEMP: rgbVal = [int(255*BRIGHTNESS),0,0] else: #The percent of the way between RED_TEMP and BLUE_TEMP tPerc = (cTemp-BLUE_TEMP)/(RED_TEMP-BLUE_TEMP) rgbVal = [int(x*BRIGHTNESS) for x in [255*tPerc,0,255*(1-tPerc)]] #print("color is {}".format(rgbVal)) #Find next available pixel cDay = (cTime[6]+1)%7 for i in range(int((cTime[2]-1)/7),8): if sense.get_pixel(cDay,i)==[0,0,0]: sense.set_pixel(cDay,i,tuple(rgbVal)) break #Display weather status unknownWeatherFile = "/home/pi/weatherPi/weather_data/unknownWeatherConditions.txt" if not(cTime[3] in range(SLEEP_START,SLEEP_START+SLEEP_DURATION) or cTime[3]+24 in range(SLEEP_START,SLEEP_START+SLEEP_DURATION)): #Not within the sleep time if cConditions in ['Showers in the Vicinity','Rain']: rainAnimation(sense) elif cConditions in ['Cloudy','Mostly Cloudy','Fog']:
class SenseManager(object): def __init__(self, log_mgr, channel): self.log_mgr = log_mgr self.channel = channel self.sense = SenseHat() self.turn_off_display() self.log_mgr.info(self.__class__.__name__, "SenseManager initialized") # Acquire single measure from single channel def read_channel(self): val = None # Acquiring from SenseHat sensors: Temperature, Pressure, Humidity if (self.channel == 1): val = self.sense.get_temperature() elif (self.channel == 2): val = self.sense.get_pressure() else: val = self.sense.get_humidity() self.light_up_pixel() # One digit round val = round(val, 2) return val # ------------------------------------------------------------------------------------------------ # METODI DEDICATI PER IL SENSE-HAT # ------------------------------------------------------------------------------------------------ # Alla pressione del pulsante del sense-hat il programma termina def show_green_sign(self): self.sense.set_pixels(green_sign) # Alla pressione del pulsante del sense-hat il programma termina def turn_off_display(self): self.sense.set_pixels(display_off) def light_up_pixel(self): meas_color = [] pix = [] if (self.channel == 1): meas_color = [255, 0, 0] elif (self.channel == 2): meas_color = [0, 255, 0] else: meas_color = [0, 0, 255] pix = self.next_pixel() self.sense.set_pixel(pix[0], pix[1], meas_color) def next_pixel(self): global X global x global y pix = [] while (self.sense.get_pixel(x, y) != X): x = x + 1 if (x == 8): x = 0 y = y + 1 if (y == 8): self.turn_off_display() x = 0 y = 0 pix.append(x) pix.append(y) return pix
global color #Utilise la variable globale color defini en dehors de la fonction sense.set_pixel( x, y, list_color[color]) #Colore le pixel grace a la liste de couleurs color += 1 if color == 5: color = 0 while pro == True: # Boucle permettant de dessiner event = sense.stick.wait_for_event() #Attend pour une action if event.direction == "right" and event.action == "pressed": # Joystick vers la droite, pixel bouge vers la droite x += 1 if x == 8: #Si on est a l'extremite droite de l'ecran, le pixel apparait du cote gauche x = 0 color = 0 col = sense.get_pixel(x, y) if col == [0, 0, 0]: #Si non colore affiche un point blanc sense.set_pixel(x, y, white) else: sense.set_pixel(x, y, white) #Fait clignoter le curseur sur les couleurs time.sleep(0.1) sense.set_pixel(x, y, col) previous_x = x - 1 #Prend les coordonnees de la position precedente du curseur if previous_x == -1: previous_x = 7 previous_y = y if event.direction == "left" and event.action == "pressed": #Joystick vers la gauche, le pixel vers la gauche x -= 1 if x == -1: # Si on est au bout de l'ecran, le pixel apparait du cote droit a la meme hauteur
] while True: sense.set_pixels(path) sense.set_pixel(charx, chary, b) pitch = sense.get_orientation()['pitch'] roll = sense.get_orientation()['roll'] print('Pitch:', pitch) print('Roll:', roll) if 270 < pitch < 315 and charx < 7: charx += 1 if 45 < pitch < 90 and charx > 0: charx -= 1 if 45 < roll < 90 and chary < 7: chary += 1 if 270 < roll < 315 and chary > 0: chary -= 1 current = sense.get_pixel(charx, chary) if current == x: charx = 0 chary = 0 sleep(0.4)
"cyan": [0, 255, 255], "white": [255, 255, 255], "black": [0, 0, 0], "off": [0, 0, 0], } white = [248, 252, 248] blank = [0, 0, 0] while running: for event in pygame.event.get(): selected = False r = random.randint(0, 255) # using the random number generator g = random.randint(0, 255) b = random.randint(0, 255) if event.type == KEYDOWN: if sense.get_pixel(x, y) == white: sense.set_pixel(x, y, 0, 0, 0) setColor(x, y, color('white')) if event.key == K_DOWN and y < 7: y = y + 1 elif event.key == K_UP and y > 0: y = y - 1 elif event.key == K_RIGHT and x < 7: x = x + 1 elif event.key == K_LEFT and x > 0: x = x - 1 elif event.key == K_RETURN: sense.set_pixel(x, y, r, g, b) selected = True
pontA = pontA + 1 sense.show_message("SCORE:", back_colour=b, text_colour=r) sense.show_message(str(pontR), back_colour=b, text_colour=r) sense.show_message("SCORE:", back_colour=b, text_colour=a) sense.show_message(str(pontA), back_colour=b, text_colour=a) p=b x=3 y=1 sense.clear p=r x=3 y=1 sense.set_pixels(imagef) sense.set_pixel(1, 0, r) sleep(1) if y==7 or sense.get_pixel(x,y+1) != b and y!=1: sleep(0.5) if sense.get_pixel(x,y) == r: sense.set_pixel(x, y, r) sense.set_pixel(1,0,re) sleep(0.5) sense.set_pixel(5,0,a) x=3 y=1 p=a if sense.get_pixel(x,y) == a: sense.set_pixel(x,y,a) sense.set_pixel(5,0,ae) sleep(0.5) sense.set_pixel(1,0,r) x=3
y = 0 sense.set_pixel(x, y, 255, 255, 255) white = [248, 252, 248] blank = [0, 0, 0] while running: for event in pygame.event.get(): selected = False # Option is to use a few set of colours chosen by pressing down repeatedly the joystick r = random.randint(0, 255) # using the random number generator g = random.randint(0, 255) b = random.randint(0, 255) if event.type == KEYDOWN: if sense.get_pixel(x, y) == white: sense.set_pixel(x, y, 0, 0, 0) if event.key == K_DOWN and y < 7: y = y + 1 elif event.key == K_UP and y > 0: y = y - 1 elif event.key == K_RIGHT and x < 7: x = x + 1 elif event.key == K_LEFT and x > 0: x = x - 1 elif event.key == K_RETURN: sense.set_pixel(x, y, r, g, b) selected = True if not selected: if sense.get_pixel(x, y) == blank: sense.set_pixel(x, y, 255, 255, 255)
class SenseManager(object): def __init__(self, log_mgr, channel, send): self.log_mgr = log_mgr self.channel = channel self.sense = SenseHat() self.turn_off_display() self.name = "sense_hat" self.qos = mod_measure_list.QOS() self.send = send self.log_mgr.info(self.__class__.__name__, "SenseManager initialized", 2) # Acquire single measure from single channel def read_channel(self): val = None qos = None # Get timestamp ts = time.time() try: # Acquiring from SenseHat sensors: Temperature, Pressure, Humidity if (self.channel == 1): val = float(self.sense.get_temperature()) elif (self.channel == 2): val = float(self.sense.get_pressure()) else: val = float(self.sense.get_humidity()) qos = self.qos.ONLINE self.light_up_pixel() except: qos = self.qos.ANOMALY self.log_mgr.fatal( "Error processing channel:<" + str(self.channel) + ">", 3) meas_sh = mod_measure_list.Measure(self.channel, val, ts, qos, self.send) return meas_sh def get_name(self): return self.name def close(self): self.log_mgr.info(self.__class__.__name__, "SenseManager closed", 2) try: self.turn_off_display() self.sense.clear() self.sense = None except: self.log_mgr.fatal("Error closing sense_hat", 1) self.channel = None # ------------------------------------------------------------------------------------------------ # METODI DEDICATI PER IL SENSE-HAT # ------------------------------------------------------------------------------------------------ # Alla pressione del pulsante del sense-hat il programma termina def show_green_sign(self): self.sense.set_pixels(green_sign) # Alla pressione del pulsante del sense-hat il programma termina def turn_off_display(self): self.sense.set_pixels(display_off) def light_up_pixel(self): meas_color = [] pix = [] if (self.channel == 1): meas_color = [127, 0, 0] elif (self.channel == 2): meas_color = [0, 127, 0] else: meas_color = [0, 0, 127] pix = self.next_pixel() self.sense.set_pixel(pix[0], pix[1], meas_color) def next_pixel(self): global X x = 0 y = 0 pix = [] while (self.sense.get_pixel(x, y) != X): x = x + 1 if (x == 8): x = 0 y = y + 1 if (y == 8): self.turn_off_display() x = 0 y = 0 pix.append(x) pix.append(y) return pix
if key == "getPixels": if showDebug: print("[ledMatrixBridge] flip vertical") print(sense.get_pixels()) if key == "setPixel": if showDebug: print("[ledMatrixBridge] set single pixel") sense.set_pixel(payload["x"], payload["y"], payload["r"], payload["g"], payload["b"]) if key == "getPixel": if showDebug: print("[ledMatrixBridge] get single pixel") print(sense.get_pixel(payload["x"], payload["y"])) if key == "loadImage": if showDebug: print("[ledMatrixBridge] load image", payload["value"]) sense.load_image(payload["value"], True) if key == "clear": if showDebug: print("[ledMatrixBridge] clear pixels") sense.clear() if key == "showMessage": if showDebug: print("[ledMatrixBridge] show message", payload['msg'])
"green":[0,255,0], "yellow":[255,255,0], # as [R,G,B] "cyan":[0,255,255], "white":[248,252,248], "black":[0,0,0], "off":[0,0,0], } while running: for event in pygame.event.get(): selected=False if event.type == KEYDOWN: if sense.get_pixel(x,y) == cursor: sense.set_pixel(x, y, blank) # Black 0,0,0 means OFF if event.key == K_DOWN and y < 7: y = y + 1 elif event.key == K_UP and y > 0: y = y - 1 elif event.key == K_RIGHT and x < 7: x = x + 1 elif event.key == K_LEFT and x > 0: x = x - 1 elif event.key == K_RETURN: ########################################################## # The following IF statements make up solution to task (4) if count == 1:
} } # Get the date and time cur_time = datetime.now().strftime("%Y%m%d%H%M") # Creates the directory Path("volume/" + cur_time).mkdir(exist_ok=True) # Writes the data in the file data.json with open('volume/' + cur_time + '/data.json', 'w') as write_file: json.dump(data, write_file) time.sleep(5) # Check if there was an error before pixel = sensor.get_pixel(0, 7) # If yes, keep the error marker on the LEDs if pixel[0] != 0: x = [255, 0, 0] o = [0, 0, 0] error = [ o, o, o, o, o, o, x, x, o, o, o, o, o, o, x, x, o, o, o, o, o, o, x, x, o, o, o, o, o, o, x, x, o, o, o, o, o, o, x, x, o, o, o, o, o, o, o, o, o, o, o, o, o, o, x, x, o, o, o, o, o, o, x, x ] sensor.set_pixels(error) else: sensor.clear()
class MatrixController(): WHITE = [255, 255, 255] BLACK = [0, 0, 0] RED = [255, 0, 0] USER_EXIT = 'exit' def __init__(self): self.trying = False self.sense = SenseHat() self.handler = { "up": self.pushed_up, "down": self.pushed_down, "right": self.pushed_right, "left": self.pushed_left, "middle": self.pushed } def get_username(self): os.system("clear") self.sense.clear() print "Enter your Username. Type 'exit' to close the app \n" return raw_input("Username: "******"\nEnter your authentication pattern in the Raspberry Pi" print "\n - Move the joystick to move around" print "\n - Press the joystick to select/deselect" print "\n - Select any spot in the green lines to submit" self.trying = True self.sense.load_image("res/start_pattern.png") self.x, self.y = [3, 3] self.next_x, self.next_y = [3, 3] self.hold_color = MatrixController.BLACK while self.trying: event = self.sense.stick.wait_for_event(emptybuffer=True) self.handler[event.direction](event) self.refresh() if self.trying == False: pattern_entered = self.sense.get_pixels() del pattern_entered[56:] # Delete last row del pattern_entered[7::8] # Delete last coloumn for i in range(len(pattern_entered)): pattern_entered[ i] = pattern_entered[i] != MatrixController.BLACK self.sense.clear() return pattern_entered def exit(self): print "\nBye!!" self.sense.show_message("Bye!!") def display_error(self, error): self.sense.load_image("res/error.png") print "\nAn error has occured: \n" print error print "\nPress Enter to continue" raw_input() self.sense.clear() def display_success(self, user): self.sense.load_image("res/success.png") print "\n\n Welcome " + user['name'] + "!" print "\n We will send you an email to <" + user[ 'mail'] + "> every " + str( user['wait']) + " seconds with the weather data." print "\n Press Ctrl + C to logout" time.sleep(1) self.sense.clear() def animation(self): "One second animation" self.sense.load_image("res/cloud1.png") time.sleep(0.25) self.sense.load_image("res/cloud2.png") time.sleep(0.25) self.sense.load_image("res/cloud3.png") time.sleep(0.25) self.sense.load_image("res/cloud4.png") time.sleep(0.25) def clamp(self, value, min_value=0, max_value=7): "Check it doesn't go out of the boundaries of the matrix" return min(max_value, max(min_value, value)) def pushed_up(self, event): if event.action != ACTION_RELEASED: self.next_y = self.clamp(self.y - 1) def pushed_down(self, event): if event.action != ACTION_RELEASED: self.next_y = self.clamp(self.y + 1) def pushed_left(self, event): if event.action != ACTION_RELEASED: self.next_x = self.clamp(self.x - 1) def pushed_right(self, event): if event.action != ACTION_RELEASED: self.next_x = self.clamp(self.x + 1) def pushed(self, event): if event.action != ACTION_RELEASED: if self.x == 7 or self.y == 7: self.trying = False else: self.toggle_color() def toggle_color(self): "If the joystick is pressed, change the color from Black to Red or viceversa" if self.hold_color == MatrixController.BLACK: self.hold_color = MatrixController.RED else: self.hold_color = MatrixController.BLACK def refresh(self): #Color the current pixel with the proper color before moving self.sense.set_pixel(self.x, self.y, self.hold_color) #Saves the color of the next pixel self.hold_color = self.sense.get_pixel(self.next_x, self.next_y) #Moves to the next pixel, coloring it white self.sense.set_pixel(self.next_x, self.next_y, MatrixController.WHITE) #Updates the current position self.x, self.y = self.next_x, self.next_y
s.set_pixel((sec_stripeX[sec_LED_current]), sec_stripeY[sec_LED_current], sec_pixel_color) # else: # s.set_pixel((sec_stripeX[sec_LED_current]), sec_stripeY[sec_LED_current], nothing) else: wipe_sec_stripe() #--now toggle on the hour-LED------------------ hour_LED_current = get_hour_pixel() if loglevel_deep: print(ticker(), "toggling the hour-LED now:") if loglevel_deep: print(ticker(), "the current hour: ", hour_LED_current, "vs. true hour: ", hour_true) x = (hour_LED_current[0])[0] y = (hour_LED_current[0])[1] if s.get_pixel(x, y) == [0, 0, 0]: was_off = True else: was_off = False if was_off: s.set_pixel(x, y, pink) # s.set_pixel(x, y, hour_stripe_color[hour_true]) if loglevel_deep: print(ticker(), "turned ON hour LED x,y now: ", x, y) if hour_LED_current[1] != (1, 1): x = (hour_LED_current[1])[0] y = (hour_LED_current[1])[1] s.set_pixel(x, y, pink) # s.set_pixel(x, y, hour_stripe_color[hour_true]) if loglevel_deep:
import argparse from _str2bool import str2bool from _return import finish parser = argparse.ArgumentParser(description='Get a single pixel') parser.add_argument('x', type=int, choices=xrange(0, 7), metavar='{ x: 0-7 }', help='0 is on the left, 7 on the right.') parser.add_argument('y', type=int, choices=xrange(0, 7), metavar='{ y: 0-7 }', help='0 is at the top, 7 at the bottom.') args = parser.parse_args() try: from sense_hat import SenseHat sense = SenseHat() result = sense.get_pixel(args.x, args.y) # Returns a list of [R, G, B] representing the colour of an individual LED matrix pixel at the specified X-Y coordinate. finish({"get_pixel": result}) except Exception, e: finish(e, 1)
w,w,w,w,w,w,w,w, r,r,w,r,r,w,r,r, r,r,w,r,r,w,r,r, w,w,w,w,w,w,w,w, r,r,w,r,r,w,r,r, r,r,w,r,r,w,r,r ] sense.set_pixels(image) direction = 2 number = 1 if direction == 2 or direction == 1: for i in range(0,7): if number == 1: for j in range(0,1): tmp1=sense.get_pixel(i,j) sense.set_pixel(i,j,w) if i == 2 or i == 5: i=i+1 elif number == 2: for j in range(3,4): tmp2=sense.get_pixel(i,j) sense.set_pixel(i,j,w) if i==2 or i==5: i=i+1 elif number == 3: for j in range(6,7): tmp3=sense.get_pixel(i,j) sense.set_pixel(i,j,w) if i==2 or i==5: i=i+1
draw_sense(maze[y][x]) sleep (2) # main loop for program while ingame: print "dotx = " + str(dotx) + " | doty " + str(doty) pitch = sense.get_orientation()['pitch'] roll = sense.get_orientation()['roll'] # print "pitch " + str(pitch) # print "roll " + str(roll ) sense.set_pixel(dotx,doty,0,0,0) old_dotx = dotx old_doty = doty dotx,doty = move_dot(pitch,roll,dotx,doty) print "newdotx = " + str(dotx) + " | newdoty = " + str(doty) if (dotx > -1 and dotx <8) and (doty > -1 and doty <8): check_dot = sense.get_pixel(dotx, doty) if check_dot == [248,0,0]: print "red" dotx = old_dotx doty = old_doty if check_dot == [0,252,0]: # green score +=1 sense.show_letter(str(score)) sleep(1) maze[y][x] = maze[y][x] - 1 sense.clear draw_sense(maze[y][x]) # Have you found all 7 if score == 7:
class TestWeather(): def __init__(self, filename): self.expected_tint1 = [216, 220, 200] self.expected_tint2 = [176, 180, 200] self.expected_tint3 = [96, 100, 200] self.expected_tint4 = [8, 8, 200] self.current_time = datetime.now() self.sense = SenseHat() self.morn_even_offset = 1 self.filename = filename self.failed_expected_tint = {1: 0, 2: 0, 3: 0, 4: 0} self.passed_expected_tint = {1: 0, 2: 0, 3: 0, 4: 0} self.file = None self.weather = None self.cloud = None self.temp = None self.sunrise = None self.sunset = None self.visibility = None self.local_temp = None def write_result_in_file(self): self.file = open(self.filename, 'a') self.file.write("\n---------Final result for the day---------\n ") for key in self.passed_expected_tint: self.file.write( "\n{0} times Passed for expected tint{1} \n".format( self.passed_expected_tint[key], key)) for key in self.failed_expected_tint: self.file.write( "\n{0} times Failed for expected tint{1} \n".format( self.failed_expected_tint[key], key)) self.file.close() def check_tint_level(self): self.file = open(self.filename, 'a') self.weather = get_weather() self.cloud = self.weather['clouds']['all'] self.temp = self.weather['main']['temp'] self.sunrise = datetime.fromtimestamp(self.weather['sys']['sunrise']) self.sunset = datetime.fromtimestamp(self.weather['sys']['sunset']) self.visibility = self.weather['visibility'] self.current_time = datetime.now() self.local_temp = self.sense.get_temperature() * 1.8 + 32 current_tint = self.sense.get_pixel(1, 1) if (self.current_time.time().hour < (self.sunrise.hour - self.morn_even_offset)): if current_tint == self.expected_tint1: self.file.write( "sunrise is {0} and current time time is {1}".format( self.sunrise, self.current_time)) self.file.write( " expected tint is tint1={0} which is equal to actual tint={1} " .format(self.expected_tint1, current_tint)) self.file.write("\n----------pas-------\n") self.passed_expected_tint[1] += 1 else: self.file.write( "sunrise is {0} and current time time is {1}".format( self.sunrise, self.current_time)) self.file.write( " expected tint is tint1={0} but actual tint is {1} ". format(self.expected_tint1, current_tint)) self.file.write("\n----------Failed-------\n") self.failed_expected_tint[1] += 1 elif (self.current_time.time().hour > (self.sunset.hour + self.morn_even_offset)): if current_tint == self.expected_tint1: self.file.write( "sunset is {0} and current time time is {1}".format( self.sunset, self.current_time)) self.file.write( " expected tint is tint1={0} which is equal to actual tint={1} " .format(self.expected_tint1, current_tint)) self.file.write("\n----------pas-------\n") self.passed_expected_tint[1] += 1 else: self.file.write( "sunset is {0} and current time time is {1}".format( self.sunrise, self.current_time)) self.file.write( " expected tint is tint1={0} but actual tint is {1} ". format(self.expected_tint1, current_tint)) self.file.write("\n----------Failed-------\n") self.failed_expected_tint[1] += 1 elif (self.cloud >= 40 or self.visibility <= 3000): if (self.cloud >= 60): if current_tint == self.expected_tint1: self.file.write( " hour of sunrise-1 {0} <= hour of current time {1} <= hour of sunset+1 {2}" .format(self.sunrise.hour - 1, self.current_time.time().hour, self.sunset.hour + 1)) self.file.write(" cloud is {0} >= 60".format(self.cloud)) self.file.write( " expected tint is tint1={0} which is equal to actual tint={1} " .format(self.expected_tint1, current_tint)) self.file.write("\n----------pas-------\n") self.passed_expected_tint[1] += 1 else: self.file.write( " hour of sunrise-1 {0} <= hour of current time {1} <= hour of sunset+1 {2}" .format(self.sunrise.hour - 1, self.current_time.time().hour, self.sunset.hour + 1)) self.file.write(" cloud is {0}>=60".format(self.cloud)) self.file.write( " expected tint is tint1={0} but actual tint is {1} ". format(self.expected_tint1, current_tint)) self.file.write("\n----------Failed-------\n") self.failed_expected_tint[1] += 1 else: if current_tint == self.expected_tint2: self.file.write( " hour of sunrise-1 {0} <= hour of current time {1} <= hour of sunset+1 {2}" .format(self.sunrise.hour - 1, self.current_time.time().hour, self.sunset.hour + 1)) self.file.write( " cloud is {0} < 60 and visibility is {1}".format( self.cloud, self.visibility)) self.file.write( " expected tint is tint2={0} which is equal to actual tint={1} " .format(self.expected_tint2, current_tint)) self.file.write("\n----------pas-------\n") self.passed_expected_tint[2] += 1 else: self.file.write( " hour of sunrise-1 {0} <= hour of current time {1} <= hour of sunset+1 {2}" .format(self.sunrise.hour - 1, self.current_time.time().hour, self.sunset.hour + 1)) self.file.write( " cloud is {0} < 60 and visibility is {1}".format( self.cloud, self.visibility)) self.file.write( " expected tint is tint2={0} but actual tint is {1} ". format(self.expected_tint2, current_tint)) self.file.write("\n----------Failed-------\n") self.failed_expected_tint[2] += 1 elif (self.local_temp > 80): if current_tint == self.expected_tint4: self.file.write( " hour of sunrise-1 {0} <= hour of current time {1} <= hour of sunset+1 {2}" .format(self.sunrise.hour - 1, self.current_time.time().hour, self.sunset.hour + 1)) self.file.write( " cloud is {0} < 40 and visibility is {1}> 3000 and ". format(self.cloud, self.visibility)) self.file.write("environment temperature is {0} > 80".format( self.local_temp)) self.file.write( " expected tint is tint4={0} which is equal to actual tint={1} " .format(self.expected_tint4, current_tint)) self.file.write("\n----------pas-------\n") self.passed_expected_tint[4] += 1 else: self.file.write( " hour of sunrise-1 {0} <= hour of current time {1} <= hour of sunset+1 {2}" .format(self.sunrise.hour - 1, self.current_time.time().hour, self.sunset.hour + 1)) self.file.write( " cloud is {0} < 40 and visibility is {1}> 3000 and ". format(self.cloud, self.visibility)) self.file.write("environment temperature is {0} > 80".format( self.local_temp)) self.file.write( " expected tint is tint4={0} but actual tint is {1} ". format(self.expected_tint4, current_tint)) self.file.write("\n----------Failed-------\n") self.failed_expected_tint[4] += 1 elif (self.local_temp > 65): if current_tint == self.expected_tint3: self.file.write( " hour of sunrise-1 {0} <= hour of current time {1} <= hour of sunset+1 {2}" .format(self.sunrise.hour - 1, self.current_time.time().hour, self.sunset.hour + 1)) self.file.write( " cloud is {0} < 40 and visibility is {1}> 3000 and". format(self.cloud, self.visibility)) self.file.write( "65 < environment temperature is {0} <= 80".format( self.local_temp)) self.file.write( " expected tint is tint3={0} which is equal to actual tint={1} " .format(self.expected_tint3, current_tint)) self.file.write("\n----------pas-------\n") self.passed_expected_tint[3] += 1 else: self.file.write( " hour of sunrise-1 {0} <= hour of current time {1} <= hour of sunset+1 {2}" .format(self.sunrise.hour - 1, self.current_time.time().hour, self.sunset.hour + 1)) self.file.write( " cloud is {0} < 40 and visibility is {1}> 3000 and". format(self.cloud, self.visibility)) self.file.write( "65 < environment temperature is {0} <= 80".format( self.local_temp)) self.file.write( " expected tint is tint3={0} but actual tint is {1} ". format(self.expected_tint3, current_tint)) self.file.write("\n----------Failed-------\n") self.failed_expected_tint[3] += 1 else: if current_tint == self.expected_tint2: self.file.write( " hour of sunrise-1 {0} <= hour of current time {1} <= hour of sunset+1 {2}" .format(self.sunrise.hour - 1, self.current_time.time().hour, self.sunset.hour + 1)) self.file.write( " cloud is {0} < 40 and visibility is {1}> 3000 and". format(self.cloud, self.visibility)) self.file.write(" environment temperature is {0} <= 65".format( self.local_temp)) self.file.write( " expected tint is tint2={0} which is equal to actual tint={1} " .format(self.expected_tint2, current_tint)) self.file.write("\n----------pas-------\n") self.passed_expected_tint[2] += 1 else: self.file.write( " hour of sunrise-1 {0} <= hour of current time {1} <= hour of sunset+1 {2}" .format(self.sunrise.hour - 1, self.current_time.time().hour, self.sunset.hour + 1)) self.file.write( " cloud is {0} < 40 and visibility is {1}> 3000 and". format(self.cloud, self.visibility)) self.file.write(" environment temperature is {0} <= 65".format( self.local_temp)) self.file.write( " expected tint is tint2={0} but actual tint is {1} ". format(self.expected_tint2, current_tint)) self.file.write("\n----------Failed-------\n") self.failed_expected_tint[2] += 1 self.file.close()
def set_color(x, y): global color sense.set_pixel(x, y, list_color[color]) color += 1 if color == 5: color = 0 while pro == True: event = sense.stick.wait_for_event() if event.direction == "right" and event.action == "pressed": x += 1 if x == 8: x = 0 color = 0 col = sense.get_pixel(x, y) if col == [0, 0, 0]: sense.set_pixel(x, y, white) else: sense.set_pixel(x, y, white) time.sleep(0.1) sense.set_pixel(x, y, col) previous_x = x - 1 if previous_x == -1: previous_x = 7 previous_y = y if event.direction == "left" and event.action == "pressed": x -= 1 if x == -1: x = 7