<commit_before>#!/usr/bin/python

import os
import sys
import math
import serial
from subprocess import check_call, CalledProcessError
import struct
import function
import random
import common
from color import Color
from time import sleep, time

BAUD_RATE = 38400
NUM_PIXELS = 4
NUM_NODES = 30 
MAX_NODES = 101 
MAX_GROUPS = 16
NUM_RINGS = 2 
BOTTLES_PER_RING = (13, 17, 19, 23, 29)

MAX_PACKET_LEN = 230
CALIBRATION_DURATION = 10
NODE_ID_UNKNOWN = 255

PACKET_SINGLE_LED   = 1  
PACKET_SINGLE_COLOR = 2  
PACKET_COLOR_ARRAY  = 3  
PACKET_PATTERN      = 4  
PACKET_ENTROPY      = 5  
PACKET_START        = 6  
PACKET_CLEAR        = 7  
PACKET_STOP         = 8  
PACKET_POSITION     = 9  
PACKET_DELAY        = 10 
PACKET_ADDRR        = 11 
PACKET_SPEED        = 12 
PACKET_GROUPS       = 13 
PACKET_CALIBRATE    = 14
PACKET_BRIGHTNESS   = 15
PACKET_ANGLE        = 16
PACKET_BOOTLOADER   = 17
PACKET_RESET        = 18
PACKET_RANDOM_COLOR = 19
BROADCAST = 0

# Can't find a good constant for ALT0 in GPIO
ALT0 = 4

def crc16_update(crc, a):
    crc ^= a
    for i in xrange(0, 8):
        if crc & 1:
            crc = (crc >> 1) ^ 0xA001
        else:
            crc = (crc >> 1)
    return crc

def group(grp):
    if grp >= MAX_GROUPS:
        raise ValueError("Invalid group id %d. Max group id is %d." % (grp, MAX_GROUPS))
    return grp | 0x80


class HippieTrap(object):

    def __init__(self, device = "/dev/serial0"):
        self.ser = None
        self.device = device


    def __enter__(self):

        try:
            check_call(["gpio", "-g", "mode", "14", "alt5"])
        except CalledProcessError as err:
            print "Is wiringpi installed? error: ", err
            sys.exit(-1)

        try:
            self.ser = serial.Serial(self.device, 
                                     BAUD_RATE, 
                                     bytesize=serial.EIGHTBITS, 
                                     parity=serial.PARITY_NONE, 
                                     stopbits=serial.STOPBITS_ONE,
                                     timeout=.01)
        except serial.serialutil.SerialException, e:
            print "Cant open serial port: %s" % self.device
            sys.exit(-1)

        # Wait for things to settle, then pipe some characters through the line to get things going
        sleep(.250)

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):

        # sleep just a moment to let the bottles process whatever packet might've
        # been transmitting if we got interrupted
        sleep(.1)
        if self.ser:
            self.ser.close()

        try:
            check_call(["gpio", "-g", "mode", "14", "output"])
        except CalledProcessError as err:
            print "Is wiringpi installed? error: ", err
            sys.exit(-1)

    def send_panic(self):
        while True:
            self.ser.write('M')
            sleep(.0005)

    @staticmethod    
    def power_on():
        try:
            check_call(["gpio", "-1", "write", "37", "1"])
        except CalledProcessError as err:
            print "Is wiringpi installed? error: ", err
            sys.exit(-1)

    @staticmethod    
    def power_off():
        try:
            check_call(["gpio", "-1", "write", "37", "0"])
        except CalledProcessError as err:
            print "Is wiringpi installed? error: ", err
            sys.exit(-1)

    def clear_cruft(self):
        for i in range(32):
            self.ser.write(chr(0))

    def _send_packet(self, dest, type, data):
        if not self.ser:
            return

        if not isinstance(data, bytearray):
            print "data argument to send_packet must be bytearray"
            return

        packet = chr(dest) + chr(type) + data
        crc = 0
        for ch in packet:
            crc = crc16_update(crc, ch)
        packet = struct.pack("<BBB", 0xBE, 0xEF, len(packet) + 2) + packet + struct.pack("<H", crc)
        if len(packet) > MAX_PACKET_LEN:<commit_msg>Software changes for new SSR power control<commit_after>#!/usr/bin/python

import os
import sys
import math
import serial
from subprocess import check_call, CalledProcessError
import struct
import function
import random
import common
from color import Color
from time import sleep, time

BAUD_RATE = 38400
NUM_PIXELS = 4
NUM_NODES = 30 
MAX_NODES = 101 
MAX_GROUPS = 16
NUM_RINGS = 2 
BOTTLES_PER_RING = (13, 17, 19, 23, 29)

MAX_PACKET_LEN = 230
CALIBRATION_DURATION = 10
NODE_ID_UNKNOWN = 255

PACKET_SINGLE_LED   = 1  
PACKET_SINGLE_COLOR = 2  
PACKET_COLOR_ARRAY  = 3  
PACKET_PATTERN      = 4  
PACKET_ENTROPY      = 5  
PACKET_START        = 6  
PACKET_CLEAR        = 7  
PACKET_STOP         = 8  
PACKET_POSITION     = 9  
PACKET_DELAY        = 10 
PACKET_ADDRR        = 11 
PACKET_SPEED        = 12 
PACKET_GROUPS       = 13 
PACKET_CALIBRATE    = 14
PACKET_BRIGHTNESS   = 15
PACKET_ANGLE        = 16
PACKET_BOOTLOADER   = 17
PACKET_RESET        = 18
PACKET_RANDOM_COLOR = 19
BROADCAST = 0

# Can't find a good constant for ALT0 in GPIO
ALT0 = 4

POWER_GPIO_PINS = [ 35, 37, 38, 40 ]

def crc16_update(crc, a):
    crc ^= a
    for i in xrange(0, 8):
        if crc & 1:
            crc = (crc >> 1) ^ 0xA001
        else:
            crc = (crc >> 1)
    return crc

def group(grp):
    if grp >= MAX_GROUPS:
        raise ValueError("Invalid group id %d. Max group id is %d." % (grp, MAX_GROUPS))
    return grp | 0x80


class HippieTrap(object):

    def __init__(self, device = "/dev/serial0"):
        self.ser = None
        self.device = device


    def __enter__(self):

        try:
            check_call(["gpio", "-g", "mode", "14", "alt5"])

            for pin in POWER_GPIO_PINS:
                check_call(["gpio", "-1", "mode", "%d" % pin, "output"])

        except CalledProcessError as err:
            print "Is wiringpi installed? error: ", err
            sys.exit(-1)

        try:
            self.ser = serial.Serial(self.device, 
                                     BAUD_RATE, 
                                     bytesize=serial.EIGHTBITS, 
                                     parity=serial.PARITY_NONE, 
                                     stopbits=serial.STOPBITS_ONE,
                                     timeout=.01)
        except serial.serialutil.SerialException, e:
            print "Cant open serial port: %s" % self.device
            sys.exit(-1)

        # Wait for things to settle, then pipe some characters through the line to get things going
        sleep(.250)

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):

        # sleep just a moment to let the bottles process whatever packet might've
        # been transmitting if we got interrupted
        sleep(.1)
        if self.ser:
            self.ser.close()

        try:
            check_call(["gpio", "-g", "mode", "14", "output"])
        except CalledProcessError as err:
            print "Is wiringpi installed? error: ", err
            sys.exit(-1)

    def send_panic(self):
        while True:
            self.ser.write('M')
            sleep(.0005)

    @staticmethod    
    def power_on():
        try:
            for pin in POWER_GPIO_PINS:
                check_call(["gpio", "-1", "write", "%d" % pin, "1"])
                sleep(.1)

        except CalledProcessError as err:
            print "Is wiringpi installed? error: ", err
            sys.exit(-1)

    @staticmethod    
    def power_off():
        try:
            for pin in POWER_GPIO_PINS:
                check_call(["gpio", "-1", "write", "%d" % pin, "0"])

        except CalledProcessError as err:
            print "Is wiringpi installed? error: ", err
            sys.exit(-1)

    def clear_cruft(self):
        for i in range(32):
            self.ser.write(chr(0))

    def _send_packet(self, dest, type, data):
        if not self.ser:
            return

        if not isinstance(data, bytearray):
            print "data argument to send_packet must be bytearray"
            return

        packet = chr(dest) + chr(type) + data
        crc = 0
        for ch in packet:
            crc = crc16_update(crc, ch)
        packet = struct.pack("<BBB", 0xBE, 0xEF, len(packet) + 2) + packet + struct.pack("<H", crc)
        if len(packet) > MAX_PACKET_LEN:
{'fraction_non_alphanumeric': 0.0950363196125908, 'fraction_numerical': 0.029055690072639227, 'mean_word_length': 1.8041412084181943, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3931889', 'n_tokens_mistral': 2837, 'n_tokens_neox': 2578, 'n_words': 751}