Advertisement
ToinasMaker

Untitled

Sep 25th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.39 KB | None | 0 0
  1. """Port of the Adafruit NeoPixel library to python using the FTDI MPSSE.
  2.  
  3. Learn more about NeoPixels here:
  4.  http://learn.adafruit.com/adafruit-neopixel-uberguide/overview
  5.  
  6. This library is meant to be used with a FT232H USB to MPSSE chip or cable, like
  7. the C232HM-EDHSL-0 here:
  8.  http://www.ftdichip.com/Products/Cables/USBMPSSE.htm
  9.  
  10. This library requires the libmpsse library to be installed with python support:
  11.  https://code.google.com/p/libmpsse/
  12.  
  13. Created by Tony DiCola (tony@tonydicola.com)
  14. Released under an MIT license (http://opensource.org/licenses/MIT)
  15.  
  16. """
  17.  
  18. import itertools
  19. import operator
  20. import time
  21. import twittercredentials
  22. import csv
  23. import platform
  24. from tweepy import Stream
  25. from tweepy import OAuthHandler
  26. from tweepy.streaming import StreamListener
  27. from mpsse import *
  28.  
  29. import time
  30. import os
  31.  
  32. hashtag1 = "#IntelMakers"
  33. hashtag2 = "#GiraMexicoPorSiempre"
  34. hashtag3= "#ToinasMakerRegresa"
  35.  
  36. # Open/create a file to append data to
  37.  
  38.  
  39.  
  40. #csvFile = open('result.csv', 'a')
  41. #Use csv writer
  42.  
  43. # csvFile = "windows_path"
  44. if os.name == 'posix':
  45.     csvFile = open('/home/upsquared/Adafruit_NeoPixel_FTDI/tweet.csv','a')
  46. else:
  47.     csvFile = open('C:/code/IntelligentSuit/tweet.csv', 'a')
  48.  
  49. csvWriter = csv.writer(csvFile)
  50.  
  51. # Bit values which represent the zero and one bit pulses.
  52. _ZERO = bytearray([0b11100000])
  53. _ONE  = bytearray([0b11111000])
  54.  
  55.  
  56. def _build_byte_lookup():
  57.     """Return lookup table to map from every byte value 0-255 and the associated
  58.     raw SPI data."""
  59.     lookup = {}
  60.     for i in range(256):
  61.         value = bytearray()
  62.         for j in range(7, -1, -1):
  63.             if ((i >> j) & 1) == 0:
  64.                 value += _ZERO
  65.             else:
  66.                 value += _ONE
  67.         lookup[i] = value
  68.     return lookup
  69.  
  70. _byte_lookup = _build_byte_lookup()
  71.  
  72. def get_default_mpsse(speed_mhz):
  73.     """Open the first MPSSE device found and return it.  Throws an exception if
  74.     no MPSSE device is found."""
  75.     from mpsse import MPSSE
  76.     mpsse = MPSSE(SPI0, speed_mhz, MSB)
  77.     if mpsse is None:
  78.         RuntimeError('Could not find a connected MPSSE device!')
  79.     return mpsse
  80.  
  81. def color(r, g, b):
  82.     """Convert an RGB triplet of 0-255 values to a 24 bit representation."""
  83.     if r < 0 or r > 255 or g < 0 or g > 255 or b < 0 or b > 255:
  84.         raise ValueError('Color values must be 0 to 255.')
  85.     return (r << 16) | (g << 8) | b
  86.  
  87. def color_to_rgb(c):
  88.     """Convert a 24 bit color to RGB triplets."""
  89.     return ((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF)
  90. def _encode_color_grb(c):
  91.     """Encode an RGB tuple into NeoPixel GRB 24 byte SPI bit stream."""
  92.     return _byte_lookup[c[1]] + _byte_lookup[c[0]] + _byte_lookup[c[2]]
  93.  
  94. def _encode_color_rgb(c):
  95.     """Encode an RGB tuple into NeoPixel RGB 24 byte SPI bit stream."""
  96.     return _byte_lookup[c[0]] + _byte_lookup[c[1]] + _byte_lookup[c[2]]
  97.  
  98. class listener(StreamListener):
  99.     # def on_data(self, data):
  100.         # tweet = data.split(',"text":"')[1].split('","source')[0]
  101.         # if(tweet):
  102.             # #replace with custom tag 1
  103.             # if ('#ToinasMakerRegresa' in tweet):
  104.                 # print(tweet+"\n")
  105.                 # time.sleep(5)
  106.             # #replace with custom tag 2        
  107.             # elif(hashtag2 in tweet):
  108.                 # print(tweet+"\n")
  109.                 # time.sleep(5)
  110.             # #replace with custom tag 3
  111.             # elif(hashtag3 in tweet):
  112.                 # print(tweet+"\n")
  113.                 # time.sleep(5)
  114.         # return(True)
  115.     def on_status(self, status):
  116.         print 'Tweet text:' + status.text
  117.        
  118.         # csvFile = "windows_path"
  119.         if os.name == 'posix':
  120.             csvFile = open('/home/upsquared/Adafruit_NeoPixel_FTDI/tweet.csv','a')
  121.         else:
  122.             csvFile = open('C:/code/IntelligentSuit/tweet.csv', 'a')
  123.         try:
  124.            
  125.         #Use csv writer
  126.             csvWriter = csv.writer(csvFile)
  127.             csvWriter.writerow([status.created_at, status.text.encode('utf-8')])
  128.             csvFile.close()
  129.             Adafruit_Main()
  130.             return(True)
  131.         except:
  132.             time.sleep(5)
  133.             csvWriter.writerow([status.created_at, status.text.encode('utf-8')])
  134.             print("file is already open")
  135.             raise
  136.        
  137.     def on_error(self, status_code):
  138.         print('Got an error with status code: ' + str(status_code))
  139.         return(True) # To continue listening
  140.  
  141.     def on_timeout(self):
  142.         print('Timeout...')
  143.         return(True) # To continue listening
  144.        
  145.    
  146.     # def on_error(self, status):
  147.         # if status == 420:
  148.             # #returning False on_data method in case rate limit occurs
  149.             # return False
  150.         # print(status)
  151. #if __name__ == '__main__':  #function def
  152. def Stream_Main():
  153.     print "Start Stream class"
  154.     auth = OAuthHandler(twittercredentials.CONSUMER_KEY, twittercredentials.CONSUMER_SECRET)
  155.     auth.set_access_token(twittercredentials.ACCESS_TOKEN, twittercredentials.ACCESS_TOKEN_SECRET)
  156.  
  157.     twitterStream = Stream(auth, listener())
  158. #replace hashtags with custom tags below. ALSO: replace tags in lines #30, #48, and #66
  159. #print("tracking: " + hashtag1 + "," + hashtag2 + "," + hashtag3)
  160.    
  161.     #twitterStream.filter(track=[hashtag1, hashtag2, hashtag3])
  162.     twitterStream.filter(track=[hashtag1])
  163.  
  164.    
  165.    
  166. class Adafruit_NeoPixel(object):
  167.    
  168.     def __init__(self, n, mpsse=None, neo_rgb=False, neo_khz400=False):
  169.         """Create set of NeoPixels.
  170.  
  171.         The only required parameter is the number of NeoPixels.  By default the
  172.         first MPSSE device found will be used, and it is assumed to be NeoPixels
  173.         which support 800khz GRB signals.  Set either neo_rgb or neo_khz400
  174.         keywoard parameters to True to use RGB or 400 khz NeoPixels respectively.
  175.  
  176.         """
  177.         print('starting Adafruit_NeoPixel class')
  178.         self._n = n
  179.         self._pixels = [0] * n
  180.         # Initialize the mpsse to a default one if not explicitly set.
  181.         if mpsse is None:
  182.             # Default to 6mhz, unless overridden to 3mhz.
  183.             speed = 3000000 if neo_khz400 else 6000000
  184.             mpsse = get_default_mpsse(speed)
  185.         self.setMPSSE(mpsse)
  186.         # Default to GRB encoding, unless overridden to RGB.
  187.         self._encode = _encode_color_rgb if neo_rgb else _encode_color_grb
  188.         self._brightness = 1.0
  189.         self._lastupdate = 0
  190.  
  191.     def close(self):
  192.         """Close the NeoPixel MPSSE connection."""
  193.         if self._mpsse is not None:
  194.             self._mpsse.Close()
  195.  
  196.     def show(self):
  197.         """Write the current pixel data to the NeoPixels."""
  198.         # Ensure there's at least a 50 micro-second delay between show calls.
  199.         delta = time.time() - self._lastupdate
  200.         if delta < 0.00005:
  201.             time.sleep(0.00005 - delta)
  202.         print('starting show')
  203.         self._mpsse.Start()
  204.         # Scale pixels based on brightness and accumulate raw SPI bitstream.
  205.         rgb = itertools.imap(color_to_rgb, self._pixels)
  206.         scaled = itertools.imap(lambda c: (int(c[0] * self._brightness),
  207.                            int(c[1] * self._brightness),
  208.                            int(c[2] * self._brightness)),
  209.                     rgb)
  210.         encoded = itertools.imap(self._encode, scaled)
  211.         # Send data to the wire.
  212.         self._mpsse.Write(str(reduce(operator.add, encoded)))
  213.         self._mpsse.Stop()
  214.         self._lastupdate = time.time()
  215.  
  216.     def setMPSSE(self, mpsse):
  217.         """Change the MPSSE device associated with this NeoPixel instance."""
  218.         if mpsse is None:
  219.             raise ValueError('MPSSE is null.')
  220.         self._mpsse = mpsse
  221.  
  222.     def setPixelColorRGB(self, n, r, g, b):
  223.         """Update pixel at position n to the provided RGB color."""
  224.         self.setPixelColor(n, color(r, g, b))
  225.  
  226.     def setPixelColor(self, n, c):
  227.         """Update pixel at position n to the provided 24 bit RGB color."""
  228.         self._checkIndex(n)
  229.         if not isinstance(c, int):
  230.             raise ValueError('Expected integer value for color.')
  231.         self._pixels[n] = c
  232.  
  233.     def setBrightness(self, b):
  234.         """Scale brightness of NeoPixels to provided value that is between 0 and
  235.         1.0.  A value of 0 is completely dark and 1.0 is normal color brightness.
  236.         Note that brightness is only reflected in the final output shown to the
  237.         hardware and not getPixels or getPixelColor."""
  238.         if b < 0.0 or b > 1.0:
  239.             raise ValueError('Brightness must be 0 to 1.0.')
  240.         self._brightness = b
  241.  
  242.     def getPixels(self):
  243.         """Return all the pixels as an array of 24 bit RGB colors."""
  244.         return self._pixels
  245.  
  246.     def numPixels(self):
  247.         """Return the number of NeoPixels."""
  248.         return self._n
  249.  
  250.     def getPixelColor(self, n):
  251.         """Return the 24 bit RGB color of the pixel at position n."""
  252.         self._checkIndex(n)
  253.         return self._pixels[n]
  254.  
  255.     def _checkIndex(self, n):
  256.         if n < 0 or n >= self._n:
  257.             raise ValueError('Pixel id {0} is outside the range of expected values.'.format(n))
  258.  
  259. #if __name__== '__main__':
  260. def Adafruit_Main():
  261.        
  262.     device = Adafruit_NeoPixel(256)    
  263.     device.setBrightness(0.01)
  264.  
  265.  
  266.     intel_blue=[0,0,255]
  267.     black=[0,0,0]
  268.     white=[255,255,255]
  269.     red=[255,0,0]
  270.  
  271. #square image
  272. #image=[white,  black,  white,  black,  white,  black,  white,  black,  white]
  273.  
  274.     image_no_color=[0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,
  275.     0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,
  276.     0,0,0,1,1,2,2,2,2,2,2,2,1,1,0,0,
  277.     0,0,0,1,1,2,2,2,2,2,2,2,1,1,0,0,
  278.     0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,
  279.     0,0,0,1,1,2,1,1,2,1,1,2,1,1,0,0,
  280.     0,0,0,1,1,2,1,1,2,1,1,2,1,1,0,0,
  281.     0,0,0,1,1,2,2,2,2,2,2,2,1,1,0,0,
  282.     0,0,0,0,1,1,2,2,2,2,2,1,1,0,0,0,
  283.     0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,
  284.     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  285.     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  286.     0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,
  287.     0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,
  288.     0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,
  289.     0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0]
  290.  
  291.     image = []
  292.  
  293.     for idx in range(len(image_no_color)):
  294.         if image_no_color[idx] == 0:
  295.             image.append(white)
  296.         if image_no_color[idx]== 1:
  297.             image.append(intel_blue)
  298.         if image_no_color[idx]== 2:
  299.             image.append(black)
  300.  
  301.  
  302.  
  303. def blit(image, img_width, location, frame_size):
  304.     frame=[black] * frame_size ** 2
  305.     vert_offset=0
  306.  
  307.     img_lines = [image[x:x+img_width] for x in range(0,len(image),img_width)]
  308.     for line in img_lines:
  309.         for idx, value in enumerate(line):
  310.         coord = idx+vert_offset+(location[0] % frame_size)+((location[1] % frame_size)*frame_size)
  311.         # HANDLE EDGE SCROLLING
  312.         print coord, idx, vert_offset, (vert_offset+(location[1]*frame_size)+frame_size)-1, location, frame_size
  313.         if (coord > (vert_offset+(location[1]*frame_size)+frame_size)-1):
  314.         coord = coord - frame_size
  315.  
  316.         coord = coord % (frame_size ** 2)
  317.             frame[coord] = value
  318.         vert_offset += frame_size
  319.     return frame
  320.  
  321. def display(width, frame):
  322.  
  323.     lines = [frame[x:x+width] for x in range(0,len(frame),width)]
  324.     flipped_frame =[]
  325.     for idx,line in enumerate(lines):
  326.     if idx % 2 == 0:
  327.         flipped_frame+=reversed(line)
  328.     else:
  329.         flipped_frame+=line
  330.  
  331.     for idx, color in enumerate(flipped_frame):
  332.     device.setPixelColorRGB(idx, color[0], color[1], color[2])
  333.     device.show()
  334.  
  335. def Vertical_Scroll():
  336.     x=0
  337.     y=0
  338.         vert=1
  339.         horiz=0
  340.     while 1:
  341.             #frame = blit(image, 3, [x,int(y)], 16)
  342.         frame = blit(image, 16, [x,int(y)], 16)
  343.         print frame    
  344.             display(16, frame)
  345.         time.sleep(0.5)
  346.        
  347.        
  348. def Horizontal_Scroll():
  349.     x=0
  350.     y=0
  351.         vert=0
  352.         horiz=1
  353.     while 1:
  354.             #frame = blit(image, 3, [x,int(y)], 16)
  355.         frame = blit(image, 16, [x,int(y)], 16)
  356.         print frame    
  357.             display(16, frame)
  358.         time.sleep(0.5)
  359.  
  360. if __name__ == "__main__":
  361.     #Adafruit_Main()   
  362.     Stream_Main()
  363.     Horizontal_Scroll()
  364.     """x=0
  365.     y=0
  366.        vert=0
  367.        horiz=1
  368.     while 1:
  369.            #frame = blit(image, 3, [x,int(y)], 16)
  370.         frame = blit(image, 16, [x,int(y)], 16)
  371.         print frame    
  372.            display(16, frame)
  373.         time.sleep(0.5)
  374.  
  375.            if vert:
  376.                y+=1
  377.            else:
  378.                y-=1
  379.            if horiz:
  380.             x+=1
  381.            else:
  382.                x-=1
  383.    
  384.         if x>=16-3:
  385.                horiz=0
  386.         if x<=0:
  387.                horiz=1
  388.  
  389.         if y>=16-3:
  390.                vert=0
  391.         if y<=0:
  392.                vert=1#"""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement