ToinasMaker

Untitled

Sep 28th, 2018
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.95 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 ([email protected])
  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 csv
  22. from mpsse import *
  23. import csv
  24. import pandas as pd
  25. import numpy
  26. from IPython.display import display as ds
  27.  
  28. hashtag1 = "#IntelMakers"
  29. hashtag2 = "#GiraMexicoPorSiempre"
  30. hashtag3= "#ToinasMakerRegresa"
  31.  
  32. intel_blue=[0,0,255]
  33. black=[0,0,0]
  34. white=[255,255,255]
  35. red=[255,0,0]
  36. # Open/create a file to append data to
  37.  
  38.  
  39. #csvFile = open('result.csv', 'a')
  40. #Use csv writer
  41.  
  42. filename='/home/upsquared/Adafruit_NeoPixel_FTDI/tweet.csv'
  43. csvFile = open('/home/upsquared/Adafruit_NeoPixel_FTDI/tweet.csv', 'rb')
  44. csvWriter = csv.writer(csvFile)
  45.  
  46. # Bit values which represent the zero and one bit pulses.
  47. _ZERO = bytearray([0b11100000])
  48. _ONE  = bytearray([0b11111000])
  49.  
  50.  
  51. def _build_byte_lookup():
  52.     """Return lookup table to map from every byte value 0-255 and the associated
  53.     raw SPI data."""
  54.     lookup = {}
  55.     for i in range(256):
  56.         value = bytearray()
  57.         for j in range(7, -1, -1):
  58.             if ((i >> j) & 1) == 0:
  59.                 value += _ZERO
  60.             else:
  61.                 value += _ONE
  62.         lookup[i] = value
  63.     return lookup
  64.  
  65. _byte_lookup = _build_byte_lookup()
  66.  
  67. def get_default_mpsse(speed_mhz):
  68.     """Open the first MPSSE device found and return it.  Throws an exception if
  69.     no MPSSE device is found."""
  70.     from mpsse import MPSSE
  71.     mpsse = MPSSE(SPI0, speed_mhz, MSB)
  72.     if mpsse is None:
  73.         RuntimeError('Could not find a connected MPSSE device!')
  74.     return mpsse
  75.  
  76. def color(r, g, b):
  77.     """Convert an RGB triplet of 0-255 values to a 24 bit representation."""
  78.     if r < 0 or r > 255 or g < 0 or g > 255 or b < 0 or b > 255:
  79.         raise ValueError('Color values must be 0 to 255.')
  80.     return (r << 16) | (g << 8) | b
  81.  
  82. def color_to_rgb(c):
  83.     """Convert a 24 bit color to RGB triplets."""
  84.     return ((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF)
  85. def _encode_color_grb(c):
  86.     """Encode an RGB tuple into NeoPixel GRB 24 byte SPI bit stream."""
  87.     return _byte_lookup[c[1]] + _byte_lookup[c[0]] + _byte_lookup[c[2]]
  88.  
  89. def _encode_color_rgb(c):
  90.     """Encode an RGB tuple into NeoPixel RGB 24 byte SPI bit stream."""
  91.     return _byte_lookup[c[0]] + _byte_lookup[c[1]] + _byte_lookup[c[2]]
  92.  
  93. class Adafruit_NeoPixel(object):
  94.    
  95.     def __init__(self, n, mpsse=None, neo_rgb=False, neo_khz400=False):
  96.         """Create set of NeoPixels.
  97.  
  98.         The only required parameter is the number of NeoPixels.  By default the
  99.         first MPSSE device found will be used, and it is assumed to be NeoPixels
  100.         which support 800khz GRB signals.  Set either neo_rgb or neo_khz400
  101.         keywoard parameters to True to use RGB or 400 khz NeoPixels respectively.
  102.  
  103.         """
  104.         print('starting Adafruit_NeoPixel class')
  105.         self._n = n
  106.         self._pixels = [0] * n
  107.         # Initialize the mpsse to a default one if not explicitly set.
  108.         if mpsse is None:
  109.             # Default to 6mhz, unless overridden to 3mhz.
  110.             speed = 3000000 if neo_khz400 else 6000000
  111.             mpsse = get_default_mpsse(speed)
  112.         self.setMPSSE(mpsse)
  113.         # Default to GRB encoding, unless overridden to RGB.
  114.         self._encode = _encode_color_rgb if neo_rgb else _encode_color_grb
  115.         self._brightness = 1.0
  116.         self._lastupdate = 0
  117.  
  118.     def close(self):
  119.         """Close the NeoPixel MPSSE connection."""
  120.         if self._mpsse is not None:
  121.             self._mpsse.Close()
  122.  
  123.     def show(self):
  124.         """Write the current pixel data to the NeoPixels."""
  125.         # Ensure there's at least a 50 micro-second delay between show calls.
  126.         delta = time.time() - self._lastupdate
  127.         if delta < 0.00005:
  128.             time.sleep(0.00005 - delta)
  129.         print('starting show')
  130.         self._mpsse.Start()
  131.         # Scale pixels based on brightness and accumulate raw SPI bitstream.
  132.         rgb = itertools.imap(color_to_rgb, self._pixels)
  133.         scaled = itertools.imap(lambda c: (int(c[0] * self._brightness),
  134.                            int(c[1] * self._brightness),
  135.                            int(c[2] * self._brightness)),
  136.                     rgb)
  137.         encoded = itertools.imap(self._encode, scaled)
  138.         # Send data to the wire.
  139.         self._mpsse.Write(str(reduce(operator.add, encoded)))
  140.         self._mpsse.Stop()
  141.         self._lastupdate = time.time()
  142.  
  143.     def setMPSSE(self, mpsse):
  144.         """Change the MPSSE device associated with this NeoPixel instance."""
  145.         if mpsse is None:
  146.             raise ValueError('MPSSE is null.')
  147.         self._mpsse = mpsse
  148.  
  149.     def setPixelColorRGB(self, n, r, g, b):
  150.         """Update pixel at position n to the provided RGB color."""
  151.         self.setPixelColor(n, color(r, g, b))
  152.  
  153.     def setPixelColor(self, n, c):
  154.         """Update pixel at position n to the provided 24 bit RGB color."""
  155.         self._checkIndex(n)
  156.         if not isinstance(c, int):
  157.             raise ValueError('Expected integer value for color.')
  158.         self._pixels[n] = c
  159.  
  160.     def setBrightness(self, b):
  161.         """Scale brightness of NeoPixels to provided value that is between 0 and
  162.         1.0.  A value of 0 is completely dark and 1.0 is normal color brightness.
  163.         Note that brightness is only reflected in the final output shown to the
  164.         hardware and not getPixels or getPixelColor."""
  165.         if b < 0.0 or b > 1.0:
  166.             raise ValueError('Brightness must be 0 to 1.0.')
  167.         self._brightness = b
  168.  
  169.     def getPixels(self):
  170.         """Return all the pixels as an array of 24 bit RGB colors."""
  171.         return self._pixels
  172.  
  173.     def numPixels(self):
  174.         """Return the number of NeoPixels."""
  175.         return self._n
  176.  
  177.     def getPixelColor(self, n):
  178.         """Return the 24 bit RGB color of the pixel at position n."""
  179.         self._checkIndex(n)
  180.         return self._pixels[n]
  181.  
  182.     def _checkIndex(self, n):
  183.         if n < 0 or n >= self._n:
  184.             raise ValueError('Pixel id {0} is outside the range of expected values.'.format(n))
  185.  
  186. def Image_Setup():
  187.        
  188.     """device = Adafruit_NeoPixel(256)     
  189.     device.setBrightness(0.01)"""
  190.  
  191.  
  192.     intel_blue=[0,0,255]
  193.     black=[0,0,0]
  194.     white=[255,255,255]
  195.     red=[255,0,0]
  196.  
  197.     image_no_color=[0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,
  198.     0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,
  199.     0,0,0,1,1,2,2,2,2,2,2,2,1,1,0,0,
  200.     0,0,0,1,1,2,2,2,2,2,2,2,1,1,0,0,
  201.     0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,
  202.     0,0,0,1,1,2,1,1,2,1,1,2,1,1,0,0,
  203.     0,0,0,1,1,2,1,1,2,1,1,2,1,1,0,0,
  204.     0,0,0,1,1,2,2,2,2,2,2,2,1,1,0,0,
  205.     0,0,0,0,1,1,2,2,2,2,2,1,1,0,0,0,
  206.     0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,
  207.     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  208.     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  209.     0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,
  210.     0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,
  211.     0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,
  212.     0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0]
  213.  
  214.     image = []
  215.     for idx in range(len(image_no_color)):
  216.         if image_no_color[idx] == 0:
  217.             image.append(white)
  218.         if image_no_color[idx]== 1:
  219.             image.append(intel_blue)
  220.         if image_no_color[idx]== 2:
  221.             image.append(black)
  222.     return image
  223.  
  224. def Free_Image_Setup():
  225.     """device = Adafruit_NeoPixel(256)     
  226.     device.setBrightness(0.01)"""
  227.  
  228.  
  229.     intel_blue=[0,0,255]
  230.     black=[0,0,0]
  231.     white=[255,255,255]
  232.     red=[255,0,0]
  233.  
  234.     image=[white,  black,  white,  black,  white,  black,  white,  black,  white]
  235.     return image
  236. def printdiffs(df_in)
  237.     df_in = find_diffs(df_in)
  238.     return df_in
  239.    
  240. def find_diffs(df_in):
  241.     df_latest = pd.read_csv(filename)
  242.     # print("old frame is:\n{}".format(df_in)) 
  243.     # print("newdata frame is:\n{}".format(df_latest))
  244.     diff_df = pd.merge(df_latest, df_in, how='outer', indicator='Exist')
  245.  
  246.     diff_df = diff_df.loc[diff_df['Exist'] != 'both']
  247.     # print 'new dataframe size is' + str(df_in.size)
  248.    
  249.     if diff_df.size >= 1:
  250.         print 'diff found' + str(diff_df.size)
  251.         # print str(diff_df.size)
  252.         ds_list = df_latest.values[-1].tolist()
  253.         print ds_list[1]
  254.         #print "just the value" + str(df_latest[1])
  255.         df_in = df_latest
  256.     return df_in
  257.  
  258. def blit(image, img_width, location, frame_size):
  259.     frame=[black] * frame_size ** 2
  260.     vert_offset=0
  261.  
  262.     img_lines = [image[x:x+img_width] for x in range(0,len(image),img_width)]
  263.     for line in img_lines:
  264.         for idx, value in enumerate(line):
  265.         coord = idx+vert_offset+(location[0] % frame_size)+((location[1] % frame_size)*frame_size)
  266.         # HANDLE EDGE SCROLLING
  267.         print coord, idx, vert_offset, (vert_offset+(location[1]*frame_size)+frame_size)-1, location, frame_size
  268.         if (coord > (vert_offset+(location[1]*frame_size)+frame_size)-1):
  269.         coord = coord - frame_size
  270.  
  271.         coord = coord % (frame_size ** 2)
  272.             frame[coord] = value
  273.         vert_offset += frame_size
  274.     return frame
  275.  
  276. def display(width, frame):
  277.  
  278.     lines = [frame[x:x+width] for x in range(0,len(frame),width)]
  279.     flipped_frame =[]
  280.     for idx,line in enumerate(lines):
  281.     if idx % 2 == 0:
  282.         flipped_frame+=reversed(line)
  283.     else:
  284.         flipped_frame+=line
  285.  
  286.     for idx, color in enumerate(flipped_frame):
  287.     device.setPixelColorRGB(idx, color[0], color[1], color[2])
  288.     device.show()
  289.  
  290. def Vertical_Scroll(image):
  291.     x=0
  292.     y=0
  293.     vert=1
  294.     horiz=0
  295.     while 1:
  296.             #frame = blit(image, 3, [x,int(y)], 16)
  297.         frame = blit(image, 16, [x,int(y)], 16)
  298.         print frame    
  299.         display(16, frame)
  300.         time.sleep(0.5)
  301.        
  302.        
  303. def Horizontal_Scroll(image):
  304.     x=0
  305.     y=0
  306.     vert=0
  307.     horiz=1
  308.    
  309.     while 1:
  310.             #frame = blit(image, 3, [x,int(y)], 16)
  311.         frame = blit(image, 16, [x,int(y)], 16)
  312.         print frame    
  313.         display(16, frame)
  314.             time.sleep(0.5)
  315.  
  316. if __name__ == "__main__":
  317.     device = Adafruit_NeoPixel(256)    
  318.     device.setBrightness(0.01)
  319.     df_last = pd.DataFrame()
  320.     df_in = pd.DataFrame()
  321.     df_in = pd.read_csv(filename)  
  322.     i=0
  323.    
  324.     while True:  
  325.         print("Polling Tweets")
  326.         df_in= printdiffs(df_in)
  327.         time.sleep(7)
  328.         i = i +1
  329.    
  330.         if (df_in.size == 1):
  331.            
  332.             imageToDisplay=Image_Setup()
  333.             print(imageToDisplay)
  334.             Horizontal_Scroll(imageToDisplay)
  335.         else:
  336.             imageToDisplay=Free_Image_Setup()
  337.             print(imageToDisplay)
  338.             Horizontal_Scroll(imageToDisplay)
  339.  
  340.         #time.sleep(0.5)
  341.     #Go back and make sure nthat when there is more than one  tweet we display all
Advertisement
Add Comment
Please, Sign In to add comment