Exemplo n.º 1
0
def main():
    fan1 = Fan(Fan.FAST, True, 10, "yellow")
    fan2 = Fan(Fan.MEDIUM, False, 5, "blue")
    print(f"For fan1: Speed = {fan1.getSpeed()}, Radius = {fan1.getRadius()}"\
        f", Color: {fan1.getColor()}, On = {fan1.getOn()}")
    print(f"For fan1: Speed = {fan2.getSpeed()}, Radius = {fan2.getRadius()}"\
        f", Color: {fan2.getColor()}, On = {fan2.getOn()}")
Exemplo n.º 2
0
 def __init__(self):
     self._logger = Logger("Thermostat",
                           lvl=Logger.INFO,
                           file="/home/pi/MVP/logs/state.log")
     self._logger.debug("initialize Thermostat object")
     self._temp = SI7021(self._logger)
     self._fan = Fan(self._logger)
Exemplo n.º 3
0
class Thermostat(object):
    """Code associated with the thermostat controller"""
    def __init__(self):
        self._logger = Logger("Thermostat",
                              lvl=Logger.INFO,
                              file="/home/pi/MVP/logs/state.log")
        self._logger.debug("initialize Thermostat object")
        self._temp = SI7021(self._logger)
        self._fan = Fan(self._logger)

    def check(self, temp=None):
        """Adjust the fan depending upon the temperature
               Args:
                   temp: optional test temperature
               Returns:
                   None
               Raises:
                   None
        """
        if temp == None:
            temp = self._temp.get_tempC()
        # Get target temperature from file
        target_temp = env['thermostat']['targetTemp']
        msg = "{} {} {} {}".format("Temp:", temp, " Target Temp:", target_temp)
        self._logger.debug(msg)
        if temp > target_temp:
            self._fan.set(Fan.ON)
        else:
            self._fan.set(Fan.OFF)
Exemplo n.º 4
0
class CO2_stat(object):
    """Code associated with the thermostat controller"""
    def __init__(self):
        self.logger = Logger("CO2_stat")
        self.logger.debug("initialize CO2 controller object")
        self._co2 = SCD30(self.logger)
        self._fan = Fan(self.logger)

    def check(self, co2=None, test=False):
        """Adjust the fan depending upon the CO2
               Args:
                   temp: optional test CO2
               Returns:
                   None
               Raises:
                   None
        """
        target_co2 = TARGET_CO2
        if co2 == None:
            co2, temp, rh = self._co2.get_data()
        msg = "{} {} {} {}".format("CO2:", co2, " Target CO2:", target_co2)
        # Get target temperature from file

        self.logger.info(msg)
        if co2 > target_co2:
            self._fan.set(Fan.ON)
        else:
            self._fan.set(Fan.OFF)
Exemplo n.º 5
0
 def __init__(self, data, scheduler):
     threading.Thread.__init__(self)
     self.status = Control.State.off
     self.data = data
     self.scheduler = scheduler
     self.run_optional = False
     self.fans = {
         Control.fan_in1: Fan(CONFIG.Fans.fan_in1, delay=15),
         Control.fan_in2: Fan(CONFIG.Fans.fan_in2, delay=10),
         Control.fan_out: Fan(CONFIG.Fans.fan_out, delay=5),
         Control.fan_box: Fan(CONFIG.Fans.fan_box, delay=0)
     }
     self._running = True
Exemplo n.º 6
0
def adjust_thermostat(temp=None, test=False):
    """Adjust the fan depending upon the temperature
           Args:
               temp: current temperature; in None, get from sensor
           Returns:
               None
           Raises:
               None
    """
    if temp == None:
        temp_sensor = SI7021()
        temp = temp_sensor.get_tempC()
    fan = Fan()
    fan.adjust(temp, test)
Exemplo n.º 7
0
def adjust_thermostat(temp=None, test=False):
    """Adjust the fan depending upon the temperature
           Args:
               temp: current temperature; in None, get from sensor
           Returns:
               None
           Raises:
               None
    """
    if temp == None:
        sensor = TempSensor()
        temp = sensor.check_temperature()
    fan = Fan()
    fan.adjust(temp, test)
Exemplo n.º 8
0
def fan_operations():
    content=request.json 
    if request.method == 'PUT':
        index = content['index']
        max_speed = content['max_speed']
        fans[index].set_max_rpm(max_speed)
        return 'Fan Speed Updated'

    if request.method == 'GET':
        return jsonify([f.serialize() for f in fans])

    if request.method == 'POST':
        max_speed = content['max_speed']
        new_fan = Fan(monitor, len(fans), max_speed)
        fans.append(new_fan)
        return "Succesfully created fan ", len(fans)-1
from Fan import Fan

fan1 = Fan(3, 10, "yellow", True)
fan2 = Fan(2, 5, "blue", False)

print("fan1's speed is", fan1.getSpeed(), "radius is", fan1.getRadius(),
      "color is", fan1.getColor(), "on is", fan1.getOn())

print("fan2's speed is", fan2.getSpeed(), "radius is", fan2.getRadius(),
      "color is", fan2.getColor(), "on is", fan2.getOn())
Exemplo n.º 10
0
def main():

    # 객체1 : fan1
    fan1 = Fan()

    # 객체2 : fan2
    fan2 = Fan()

    # fan1의 속성 변경
    # 속도 = 가장 빠름
    # 색상 = 노랑
    # 전원 = 켜짐
    fan1.setSpeed(fan1.FAST)
    fan1.setRadius(10.0)
    fan1.setColor("Yellow")
    fan1.setOn(True)

    # fan2의 속성 변경
    # 속도 = 중간
    # 색상 = 파랑
    # 전원 = 꺼짐
    fan2.setSpeed(fan2.MEDIUM)
    fan2.setRadius(5.0)
    fan2.setColor("Blue")
    fan2.setOn(False)

    # 결과 출력
    print("**** 객체1 ****")
    print("속도 :", fan1.getSpeed())
    print("크기 :", fan1.getRadius())
    print("색상 :", fan1.getColor())
    print("전원 :", fan1.getOn())

    print()
    print()

    print("**** 객체2 ****")
    print("속도 :", fan2.getSpeed())
    print("크기 :", fan2.getRadius())
    print("색상 :", fan2.getColor())
    print("전원 :", fan2.getOn())
Exemplo n.º 11
0
    def __init__(self):
        logging.info("Redeem initializing "+version)

        self.printer = Printer()

        # Parse the config
        self.printer.config = CascadingConfigParser(['/etc/redeem/default.cfg', '/etc/redeem/local.cfg'])

        # Get the revision from the Config file
        self.revision = self.printer.config.get('System', 'revision', "A4")
        logging.info("Replicape revision "+self.revision)

        

        # Init the end stops
        EndStop.callback = self.end_stop_hit
        EndStop.inputdev = self.printer.config.get("Endstops","inputdev");

        if self.revision == "A4":
            self.printer.end_stops["X1"] = EndStop("GPIO3_21", 112, "X1", self.printer.config.getboolean("Endstops", "invert_X1"))
            self.printer.end_stops["X2"] = EndStop("GPIO0_30", 113, "X2", self.printer.config.getboolean("Endstops", "invert_X2"))
            self.printer.end_stops["Y1"] = EndStop("GPIO1_17", 114, "Y1", self.printer.config.getboolean("Endstops", "invert_Y1"))
            self.printer.end_stops["Y2"] = EndStop("GPIO1_19", 115, "Y2", self.printer.config.getboolean("Endstops", "invert_Y2"))
            self.printer.end_stops["Z1"] = EndStop("GPIO0_31", 116, "Z1", self.printer.config.getboolean("Endstops", "invert_Z1"))
            self.printer.end_stops["Z2"] = EndStop("GPIO0_4" , 117, "Z2", self.printer.config.getboolean("Endstops", "invert_Z2"))
        else:
            self.printer.end_stops["X1"] = EndStop("GPIO0_14", 112, "X1", self.printer.config.getboolean("Endstops", "invert_X1"))
            self.printer.end_stops["X2"] = EndStop("GPIO3_21", 113, "X2", self.printer.config.getboolean("Endstops", "invert_X2"))
            self.printer.end_stops["Y1"] = EndStop("GPIO2_2",  114, "Y1", self.printer.config.getboolean("Endstops", "invert_Y1"))
            self.printer.end_stops["Y2"] = EndStop("GPIO0_31", 115, "Y2", self.printer.config.getboolean("Endstops", "invert_Y2"))
            self.printer.end_stops["Z1"] = EndStop("GPIO0_30", 116, "Z1", self.printer.config.getboolean("Endstops", "invert_Z1"))
            self.printer.end_stops["Z2"] = EndStop("GPIO0_4",  117, "Z2", self.printer.config.getboolean("Endstops", "invert_Z2"))
            
        if self.revision == "A3":
            Stepper.revision = "A3"
            Stepper.ENABLED = 6
            Stepper.SLEEP   = 5
            Stepper.RESET   = 4
            Stepper.DECAY   = 0

        # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
        self.printer.steppers["X"] = Stepper("GPIO0_27", "GPIO1_29", "GPIO2_4",  0, "X",  self.printer.end_stops["X1"], 0,0) 
        self.printer.steppers["Y"] = Stepper("GPIO1_12", "GPIO0_22", "GPIO2_5",  1, "Y",  self.printer.end_stops["Y1"], 1,1)  
        self.printer.steppers["Z"] = Stepper("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, "Z",  self.printer.end_stops["Z1"], 2,2)  
        self.printer.steppers["E"] = Stepper("GPIO1_28", "GPIO1_15", "GPIO2_1",  3, "Ext1", None,3,3)
        self.printer.steppers["H"] = Stepper("GPIO1_13", "GPIO1_14", "GPIO2_3",  4, "Ext2", None,4,4)

        # Enable the steppers and set the current, steps pr mm and microstepping  
        for name, stepper in self.printer.steppers.iteritems():
            stepper.set_current_value(self.printer.config.getfloat('Steppers', 'current_'+name)) 
            if self.printer.config.getboolean('Steppers', 'enabled_'+name):
                stepper.set_enabled()
            else:
                stepper.set_disabled()
            stepper.set_steps_pr_mm(self.printer.config.getfloat('Steppers', 'steps_pr_mm_'+name))         
            stepper.set_microstepping(self.printer.config.getint('Steppers', 'microstepping_'+name)) 
            stepper.direction = self.printer.config.getint('Steppers', 'direction_'+name)
            stepper.set_decay(self.printer.config.getboolean("Steppers", "slow_decay_"+name))

		# Commit changes for the Steppers
        Stepper.commit()

        # Find the path of the thermistors
        path = "/sys/bus/iio/devices/iio:device0/in_voltage"

        # init the 3 thermistors
        therm_ext1 = Thermistor(path+"4_raw", "MOSFET Ext 1", self.printer.config.get('Heaters', "ext1_temp_chart"))
        therm_hbp  = Thermistor(path+"6_raw", "MOSFET HBP",   self.printer.config.get('Heaters', "hbp_temp_chart"))
        therm_ext2 = Thermistor(path+"5_raw", "MOSFET Ext 2", self.printer.config.get('Heaters', "ext2_temp_chart"))

        path = self.printer.config.get('Cold-ends', 'path', 0)
        if os.path.exists(path):
            self.printer.cold_ends.append(ColdEnd(path, "Cold End 1"))
            logging.info("Found Cold end on "+path)
        else:
            logging.info("No cold end present in path: "+path)            
		
        # Init the 3 heaters. Argument is channel number
        if self.revision == "A3":
          mosfet_ext1 = Mosfet(3)
          mosfet_ext2 = Mosfet(4)
          mosfet_hbp  = Mosfet(5)
        else:
          mosfet_ext1 = Mosfet(5)
          mosfet_ext2 = Mosfet(3)
          mosfet_hbp  = Mosfet(4)

        # Make extruder 1
        self.printer.heaters['E'] = Extruder(self.printer.steppers["E"], therm_ext1, mosfet_ext1, "Ext1", self.printer.config.getboolean('Heaters', 'ext1_onoff_control'))
        self.printer.heaters['E'].set_p_value(self.printer.config.getfloat('Heaters', "ext1_pid_p"))
        self.printer.heaters['E'].set_d_value(self.printer.config.getfloat('Heaters', "ext1_pid_d"))
        self.printer.heaters['E'].set_i_value(self.printer.config.getfloat('Heaters', "ext1_pid_i"))
        self.printer.heaters['E'].ok_range = self.printer.config.getfloat('Heaters', "ext1_ok_range")

        # Make Heated Build platform 
        self.printer.heaters['HBP'] = HBP( therm_hbp, mosfet_hbp, self.printer.config.getboolean('Heaters', 'hbp_onoff_control'))       
        self.printer.heaters['HBP'].set_p_value(self.printer.config.getfloat('Heaters', "hbp_pid_p"))
        self.printer.heaters['HBP'].set_d_value(self.printer.config.getfloat('Heaters', "hbp_pid_i"))     
        self.printer.heaters['HBP'].set_i_value(self.printer.config.getfloat('Heaters', "hbp_pid_d"))
        self.printer.heaters['HBP'].ok_range = self.printer.config.getfloat('Heaters', "hbp_ok_range")

        # Make extruder 2.
        self.printer.heaters['H'] = Extruder(self.printer.steppers["H"], therm_ext2, mosfet_ext2, "Ext2", self.printer.config.getboolean('Heaters', 'ext2_onoff_control'))
        self.printer.heaters['H'].set_p_value(self.printer.config.getfloat('Heaters', "ext2_pid_p"))
        self.printer.heaters['H'].set_d_value(self.printer.config.getfloat('Heaters', "ext2_pid_i"))     
        self.printer.heaters['H'].set_i_value(self.printer.config.getfloat('Heaters', "ext2_pid_d"))
        self.printer.heaters['H'].ok_range = self.printer.config.getfloat('Heaters', "ext2_ok_range")        

        # Init the three fans. Argument is PWM channel number
        self.printer.fans=[]
        if self.revision == "A3":
            self.printer.fans.append(Fan(1))
            self.printer.fans.append(Fan(2))
            self.printer.fans.append(Fan(0))
        else:
            self.printer.fans.append(Fan(8))
            self.printer.fans.append(Fan(9))
            self.printer.fans.append(Fan(10))

        Fan.set_PWM_frequency(100)
         
        for f in self.printer.fans:
            f.set_value(0)

        # Make a queue of commands
        self.commands = Queue.Queue(10)

        # Set up USB, this receives messages and pushes them on the queue
        self.usb = USB(self.commands)		
        # Virtual TTY 
        self.pipe = Pipe(self.commands)
        #self.pipe.set_send_reponse(False)
        self.ethernet = Ethernet(self.commands)
        
        # Init the path planner     
        Path.axis_config = int(self.printer.config.get('Geometry', 'axis_config'))
        Path.max_speed_x = float(self.printer.config.get('Steppers', 'max_speed_x'))
        Path.max_speed_y = float(self.printer.config.get('Steppers', 'max_speed_y'))
        Path.max_speed_z = float(self.printer.config.get('Steppers', 'max_speed_z'))
        Path.max_speed_e = float(self.printer.config.get('Steppers', 'max_speed_e'))
        Path.max_speed_h = float(self.printer.config.get('Steppers', 'max_speed_h'))

        Path.home_speed_x = float(self.printer.config.get('Steppers', 'home_speed_x'))
        Path.home_speed_y = float(self.printer.config.get('Steppers', 'home_speed_y'))
        Path.home_speed_z = float(self.printer.config.get('Steppers', 'home_speed_z'))
        Path.home_speed_e = float(self.printer.config.get('Steppers', 'home_speed_e'))
        Path.home_speed_h = float(self.printer.config.get('Steppers', 'home_speed_h'))

        dirname = os.path.dirname(os.path.realpath(__file__))

        # Create the firmware compiler
        pru_firmware = PruFirmware(dirname+"/../firmware/firmware_runtime.p",dirname+"/../firmware/firmware_runtime.bin",dirname+"/../firmware/firmware_endstops.p",dirname+"/../firmware/firmware_endstops.bin",self.revision,self.printer.config,"/usr/bin/pasm")

        self.printer.path_planner = PathPlanner(self.printer.steppers, pru_firmware)
        self.printer.path_planner.set_acceleration(float(self.printer.config.get('Steppers', 'acceleration'))) 

        travel={}
        offset={}
        for axis in ['X','Y','Z']:
            travel[axis] = self.printer.config.getfloat('Geometry', 'travel_'+axis.lower())
            offset[axis] = self.printer.config.getfloat('Geometry', 'offset_'+axis.lower())

        self.printer.path_planner.set_travel_length(travel)
        self.printer.path_planner.set_center_offset(offset)

        self.printer.processor = GCodeProcessor(self.printer);

        # After the firmwares are loaded, the endstop states can be updated.
        for k, endstop in self.printer.end_stops.iteritems():
            logging.debug("Endstop "+endstop.name+" hit? : "+ str(endstop.read_value()))

        self.running = True

        # Signal everything ready
        logging.info("Redeem ready")
Exemplo n.º 12
0
Arquivo: 7_4.py Projeto: bvba/python
from Fan import Fan
# Fan 파일에서 Fan 클래스 import

fan1 = Fan(Fan.FAST, 10, "yellow", True)  # fan1 객체 생성
fan2 = Fan(Fan.MEDIUM, 5, "blue", False)  # fan2 객체 생성

fan1.print()
fan2.print()  # fan1, fan2 객체의 필드 값 출력
Exemplo n.º 13
0
    def __init__(self):
        logging.info("Replicape initializing "+version)
        self.config = ConfigParser.ConfigParser()
        self.config.readfp(open('config/default.cfg'))

        # Make a list of steppers
        self.steppers = {}

        # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
        self.steppers["X"] = SMD("GPIO0_27", "GPIO1_29", "GPIO2_4",  0, "X") 
        self.steppers["Y"] = SMD("GPIO1_12", "GPIO0_22", "GPIO2_5",  1, "Y")  
        self.steppers["Z"] = SMD("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, "Z")  
        self.steppers["H"] = SMD("GPIO1_28", "GPIO1_15", "GPIO2_1",  3, "Ext1")
        self.steppers["E"] = SMD("GPIO1_13", "GPIO1_14", "GPIO2_3",  4, "Ext2")

        # Enable the steppers and set the current, steps pr mm and microstepping  
        for name, stepper in self.steppers.iteritems():
            stepper.setCurrentValue(self.config.getfloat('Steppers', 'current_'+name)) 
            stepper.setEnabled(self.config.getboolean('Steppers', 'enabled_'+name)) 
            stepper.set_steps_pr_mm(self.config.getfloat('Steppers', 'steps_pr_mm_'+name))         
            stepper.set_microstepping(self.config.getint('Steppers', 'microstepping_'+name)) 
            stepper.set_decay(0) 

		# Commit changes for the Steppers
        SMD.commit()

        # Find the path of the thermostors
        path = "/sys/bus/iio/devices/iio:device0/in_voltage"

        # init the 3 thermistors
        self.therm_ext1 = Thermistor(path+"4_raw", "MOSFET Ext 1", "B57561G0103F000") # Epcos 10K
        self.therm_hbp  = Thermistor(path+"6_raw", "MOSFET HBP",   "B57560G104F")	  # Epcos 100K
        self.therm_ext2 = Thermistor(path+"5_raw", "MOSFET Ext 2", "B57561G0103F000") # Epcos 10K

        if os.path.exists("/sys/bus/w1/devices/28-000002e34b73/w1_slave"):
            self.cold_end_1 = W1("/sys/bus/w1/devices/28-000002e34b73/w1_slave", "Cold End 1")
		
        # init the 3 heaters
        self.mosfet_ext1 = Mosfet(3)
        self.mosfet_ext2 = Mosfet(4)
        self.mosfet_hbp  = Mosfet(5)

        # Make extruder 1
        self.ext1 = Extruder(self.steppers["E"], self.therm_ext1, self.mosfet_ext1, "Ext1")
        self.ext1.setPvalue(0.1)
        self.ext1.setDvalue(0.3)     
        self.ext1.setIvalue(0.0)

        # Make Heated Build platform 
        self.hbp = HBP( self.therm_hbp, self.mosfet_hbp)       

        # Make extruder 2.
        self.ext2 = Extruder(self.steppers["H"], self.therm_ext2, self.mosfet_ext2, "Ext2")
        self.ext1.setPvalue(0.1)
        self.ext1.setDvalue(0.3)     
        self.ext1.setIvalue(0.0)

        self.current_tool = "E"

        # Init the three fans
        self.fan_1 = Fan(1)
        self.fan_2 = Fan(2)
        self.fan_3 = Fan(0)
        self.fans = {0: self.fan_1, 1:self.fan_2, 2:self.fan_3 }

        self.fan_1.setPWMFrequency(100)

        # Init the end stops
        self.end_stops = {}
        self.end_stops["Y1"] = EndStop("GPIO2_2", self.steppers, 1, "Y1")
        self.end_stops["X1"] = EndStop("GPIO0_14", self.steppers, 2, "X1")
        self.end_stops["Z1"] = EndStop("GPIO0_30", self.steppers, 3, "Z1")
        self.end_stops["Y2"] = EndStop("GPIO3_21", self.steppers, 4, "Y2")
        self.end_stops["X2"] = EndStop("GPIO0_31", self.steppers, 5, "X2")
        self.end_stops["Z2"] = EndStop("GPIO0_4", self.steppers, 6, "Z2")
        
        # Make a queue of commands
        self.commands = Queue.Queue(10)

        # Set up USB, this receives messages and pushes them on the queue
        #self.usb = USB(self.commands)		
        self.pipe = Pipe(self.commands)
        self.ethernet = Ethernet(self.commands)
        
        # Init the path planner
        self.movement = "RELATIVE"
        self.feed_rate = 3000.0
        self.current_pos = {"X":0.0, "Y":0.0, "Z":0.0, "E":0.0,"H":0.0}
        self.acceleration = 0.3
        Path.axis_config = int(self.config.get('Geometry', 'axis_config'))
        Path.max_speed_x = float(self.config.get('Steppers', 'max_speed_x'))
        Path.max_speed_y = float(self.config.get('Steppers', 'max_speed_y'))
        Path.max_speed_z = float(self.config.get('Steppers', 'max_speed_z'))
        Path.max_speed_e = float(self.config.get('Steppers', 'max_speed_e'))
        Path.max_speed_h = float(self.config.get('Steppers', 'max_speed_h'))

        self.path_planner = Path_planner(self.steppers, self.current_pos)         
        self.path_planner.set_acceleration(self.acceleration) 

        

        # Signal everything ready
        logging.info("Replicape ready")
        print "Replicape ready" 
Exemplo n.º 14
0
    def __init__(self):
        """ Init """
        logging.info("Redeem initializing " + version)

        self.printer = Printer()

        # Parse the config files.
        self.printer.config = CascadingConfigParser([
            '/etc/redeem/default.cfg', '/etc/redeem/printer.cfg',
            '/etc/redeem/local.cfg'
        ])

        # Get the revision and loglevel from the Config file
        self.revision = self.printer.config.get('System', 'revision', "A4")
        level = self.printer.config.getint('System', 'loglevel')
        if level > 0:
            logging.getLogger().setLevel(level)

        logging.info("Replicape revision " + self.revision)

        # Init the end stops
        EndStop.callback = self.end_stop_hit
        EndStop.inputdev = self.printer.config.get("Endstops", "inputdev")

        if self.revision == "A4" or self.revision == "A4A":
            self.printer.end_stops["X1"] = EndStop(
                "GPIO3_21", 112, "X1",
                self.printer.config.getboolean("Endstops", "invert_X1"))
            self.printer.end_stops["X2"] = EndStop(
                "GPIO0_30", 113, "X2",
                self.printer.config.getboolean("Endstops", "invert_X2"))
            self.printer.end_stops["Y1"] = EndStop(
                "GPIO1_17", 114, "Y1",
                self.printer.config.getboolean("Endstops", "invert_Y1"))
            self.printer.end_stops["Y2"] = EndStop(
                "GPIO1_19", 115, "Y2",
                self.printer.config.getboolean("Endstops", "invert_Y2"))
            self.printer.end_stops["Z1"] = EndStop(
                "GPIO0_31", 123, "Z1",
                self.printer.config.getboolean("Endstops", "invert_Z1"))
            self.printer.end_stops["Z2"] = EndStop(
                "GPIO0_4", 117, "Z2",
                self.printer.config.getboolean("Endstops", "invert_Z2"))
        else:
            self.printer.end_stops["X1"] = EndStop(
                "GPIO0_14", 112, "X1",
                self.printer.config.getboolean("Endstops", "invert_X1"))
            self.printer.end_stops["X2"] = EndStop(
                "GPIO3_21", 113, "X2",
                self.printer.config.getboolean("Endstops", "invert_X2"))
            self.printer.end_stops["Y1"] = EndStop(
                "GPIO2_2", 114, "Y1",
                self.printer.config.getboolean("Endstops", "invert_Y1"))
            self.printer.end_stops["Y2"] = EndStop(
                "GPIO0_31", 115, "Y2",
                self.printer.config.getboolean("Endstops", "invert_Y2"))
            self.printer.end_stops["Z1"] = EndStop(
                "GPIO0_30", 123, "Z1",
                self.printer.config.getboolean("Endstops", "invert_Z1"))
            self.printer.end_stops["Z2"] = EndStop(
                "GPIO0_4", 117, "Z2",
                self.printer.config.getboolean("Endstops", "invert_Z2"))

        if self.revision == "A3":
            Stepper.revision = "A3"
            Stepper.ENABLED = 6
            Stepper.SLEEP = 5
            Stepper.RESET = 4
            Stepper.DECAY = 0

        # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
        self.printer.steppers["X"] = Stepper("GPIO0_27", "GPIO1_29", "GPIO2_4",
                                             0, "X",
                                             self.printer.end_stops["X1"], 0,
                                             0)
        self.printer.steppers["Y"] = Stepper("GPIO1_12", "GPIO0_22", "GPIO2_5",
                                             1, "Y",
                                             self.printer.end_stops["Y1"], 1,
                                             1)
        self.printer.steppers["Z"] = Stepper("GPIO0_23", "GPIO0_26",
                                             "GPIO0_15", 2, "Z",
                                             self.printer.end_stops["Z1"], 2,
                                             2)
        self.printer.steppers["E"] = Stepper("GPIO1_28", "GPIO1_15", "GPIO2_1",
                                             3, "E", None, 3, 3)
        self.printer.steppers["H"] = Stepper("GPIO1_13", "GPIO1_14", "GPIO2_3",
                                             4, "H", None, 4, 4)

        # Enable the steppers and set the current, steps pr mm and
        # microstepping
        for name, stepper in self.printer.steppers.iteritems():
            stepper.set_current_value(
                self.printer.config.getfloat('Steppers', 'current_' + name))
            stepper.in_use = self.printer.config.getboolean(
                'Steppers', 'in_use_' + name)
            stepper.set_steps_pr_mm(
                self.printer.config.getfloat('Steppers',
                                             'steps_pr_mm_' + name))
            stepper.set_microstepping(
                self.printer.config.getint('Steppers',
                                           'microstepping_' + name))
            stepper.direction = self.printer.config.getint(
                'Steppers', 'direction_' + name)
            stepper.set_decay(
                self.printer.config.getboolean("Steppers",
                                               "slow_decay_" + name))
            stepper.has_endstop = self.printer.config.getboolean(
                'Endstops', 'has_' + name)

        # Commit changes for the Steppers
        Stepper.commit()

        # Find the path of the thermistors
        path = "/sys/bus/iio/devices/iio:device0/in_voltage"

        # init the 3 thermistors
        therm_ext1 = Thermistor(
            path + "4_raw", "MOSFET Ext 1",
            self.printer.config.get('Heaters', "ext1_temp_chart"))
        therm_hbp = Thermistor(
            path + "6_raw", "MOSFET HBP",
            self.printer.config.get('Heaters', "hbp_temp_chart"))
        therm_ext2 = Thermistor(
            path + "5_raw", "MOSFET Ext 2",
            self.printer.config.get('Heaters', "ext2_temp_chart"))

        path = self.printer.config.get('Cold-ends', 'path', 0)
        if os.path.exists(path):
            self.printer.cold_ends.append(ColdEnd(path, "Cold End 0"))
            logging.info("Found Cold end on " + path)
        else:
            logging.info("No cold end present in path: " + path)

        # Init the 3 heaters. Argument is channel number
        if self.revision == "A3":
            mosfet_ext1 = Mosfet(3)
            mosfet_ext2 = Mosfet(5)
            mosfet_hbp = Mosfet(4)
        else:
            mosfet_ext1 = Mosfet(5)
            mosfet_ext2 = Mosfet(3)
            mosfet_hbp = Mosfet(4)

        # Make extruder 1
        self.printer.heaters['E'] = Extruder(
            self.printer.steppers["E"], therm_ext1, mosfet_ext1, "Ext1",
            self.printer.config.getboolean('Heaters', 'ext1_onoff_control'))
        self.printer.heaters['E'].P = self.printer.config.getfloat(
            'Heaters', "ext1_pid_p")
        self.printer.heaters['E'].I = self.printer.config.getfloat(
            'Heaters', "ext1_pid_i")
        self.printer.heaters['E'].D = self.printer.config.getfloat(
            'Heaters', "ext1_pid_d")
        self.printer.heaters['E'].ok_range = self.printer.config.getfloat(
            'Heaters', "ext1_ok_range")

        # Make Heated Build platform
        self.printer.heaters['HBP'] = HBP(
            therm_hbp, mosfet_hbp,
            self.printer.config.getboolean('Heaters', 'hbp_onoff_control'))
        self.printer.heaters['HBP'].P = self.printer.config.getfloat(
            'Heaters', "hbp_pid_p")
        self.printer.heaters['HBP'].I = self.printer.config.getfloat(
            'Heaters', "hbp_pid_i")
        self.printer.heaters['HBP'].D = self.printer.config.getfloat(
            'Heaters', "hbp_pid_d")
        self.printer.heaters['HBP'].ok_range = self.printer.config.getfloat(
            'Heaters', "hbp_ok_range")

        # Make extruder 2.
        self.printer.heaters['H'] = Extruder(
            self.printer.steppers["H"], therm_ext2, mosfet_ext2, "Ext2",
            self.printer.config.getboolean('Heaters', 'ext2_onoff_control'))
        self.printer.heaters['H'].P = self.printer.config.getfloat(
            'Heaters', "ext2_pid_p")
        self.printer.heaters['H'].I = self.printer.config.getfloat(
            'Heaters', "ext2_pid_i")
        self.printer.heaters['H'].D = self.printer.config.getfloat(
            'Heaters', "ext2_pid_d")
        self.printer.heaters['H'].ok_range = self.printer.config.getfloat(
            'Heaters', "ext2_ok_range")

        # Init the three fans. Argument is PWM channel number
        self.printer.fans = []
        if self.revision == "A3":
            self.printer.fans.append(Fan(0))
            self.printer.fans.append(Fan(1))
            self.printer.fans.append(Fan(2))
        else:
            self.printer.fans.append(Fan(8))
            self.printer.fans.append(Fan(9))
            self.printer.fans.append(Fan(10))

        Fan.set_PWM_frequency(100)

        for f in self.printer.fans:
            f.set_value(0)

        # Connect the cold end 0 to fan 2
        # This is very "Thing" specific, should be configurable somehow.
        if len(self.printer.cold_ends):
            self.printer.coolers.append(
                Cooler(self.printer.cold_ends[0], self.printer.fans[2],
                       "Cooler0", False))
            self.printer.coolers[0].ok_range = 4
            self.printer.coolers[0].set_target_temperature(60)
            self.printer.coolers[0].enable()

            # Make a queue of commands
        self.printer.commands = JoinableQueue(10)

        # Make a queue of commands that should not be buffered
        self.printer.unbuffered_commands = JoinableQueue(10)

        # Init the path planner
        Path.axis_config = int(
            self.printer.config.get('Geometry', 'axis_config'))
        Path.max_speeds[0] = float(
            self.printer.config.get('Steppers', 'max_speed_x'))
        Path.max_speeds[1] = float(
            self.printer.config.get('Steppers', 'max_speed_y'))
        Path.max_speeds[2] = float(
            self.printer.config.get('Steppers', 'max_speed_z'))
        Path.max_speeds[3] = float(
            self.printer.config.get('Steppers', 'max_speed_e'))
        Path.max_speeds[4] = float(
            self.printer.config.get('Steppers', 'max_speed_h'))

        Path.home_speed[0] = float(
            self.printer.config.get('Steppers', 'home_speed_x'))
        Path.home_speed[1] = float(
            self.printer.config.get('Steppers', 'home_speed_y'))
        Path.home_speed[2] = float(
            self.printer.config.get('Steppers', 'home_speed_z'))
        Path.home_speed[3] = float(
            self.printer.config.get('Steppers', 'home_speed_e'))
        Path.home_speed[4] = float(
            self.printer.config.get('Steppers', 'home_speed_h'))

        Path.steps_pr_meter[0] = self.printer.steppers["X"].get_steps_pr_meter(
        )
        Path.steps_pr_meter[1] = self.printer.steppers["Y"].get_steps_pr_meter(
        )
        Path.steps_pr_meter[2] = self.printer.steppers["Z"].get_steps_pr_meter(
        )
        Path.steps_pr_meter[3] = self.printer.steppers["E"].get_steps_pr_meter(
        )
        Path.steps_pr_meter[4] = self.printer.steppers["H"].get_steps_pr_meter(
        )

        dirname = os.path.dirname(os.path.realpath(__file__))

        # Create the firmware compiler
        pru_firmware = PruFirmware(
            dirname + "/../firmware/firmware_runtime.p",
            dirname + "/../firmware/firmware_runtime.bin",
            dirname + "/../firmware/firmware_endstops.p",
            dirname + "/../firmware/firmware_endstops.bin", self.revision,
            self.printer.config, "/usr/bin/pasm")

        self.printer.maxJerkXY = float(
            self.printer.config.get('Steppers', 'maxJerk_xy'))
        self.printer.maxJerkZ = float(
            self.printer.config.get('Steppers', 'maxJerk_z'))
        self.printer.maxJerkEH = float(
            self.printer.config.get('Steppers', 'maxJerk_eh'))

        self.printer.path_planner = PathPlanner(self.printer, pru_firmware)

        travel = {}
        offset = {}
        i = 0
        for axis in ['X', 'Y', 'Z', 'E', 'H']:
            travel[axis] = self.printer.config.getfloat(
                'Geometry', 'travel_' + axis.lower())
            offset[axis] = self.printer.config.getfloat(
                'Geometry', 'offset_' + axis.lower())
            self.printer.acceleration[i] = self.printer.config.getfloat(
                'Steppers', 'acceleration_' + axis.lower())
            i += 1

        self.printer.path_planner.travel_length = travel
        self.printer.path_planner.center_offset = offset
        self.printer.processor = GCodeProcessor(self.printer)

        # Set up communication channels
        self.printer.comms["USB"] = USB(self.printer)
        self.printer.comms["Eth"] = Ethernet(self.printer)
        self.printer.comms["octoprint"] = Pipe(
            self.printer, "octoprint")  # Pipe for Octoprint
        self.printer.comms["toggle"] = Pipe(self.printer,
                                            "toggle")  # Pipe for Toggle
        self.printer.comms["testing"] = Pipe(self.printer,
                                             "testing")  # Pipe for testing
        self.printer.comms["testing_noret"] = Pipe(
            self.printer, "testing_noret")  # Pipe for testing
        self.printer.comms["testing_noret"].send_response = False

        self.running = True

        # Start the two processes
        p0 = Thread(target=self.loop, args=(self.printer.commands, "buffered"))
        p1 = Thread(target=self.loop,
                    args=(self.printer.unbuffered_commands, "unbuffered"))
        p0.daemon = True
        p1.daemon = True

        p0.start()
        p1.start()

        # Signal everything ready
        logging.info("Redeem ready")

        # Wait for exit signal
        p0.join()
        p1.join()
Exemplo n.º 15
0
def adjustThermostat(temp=None, test=False):
    if temp == None:
        si = si7021()
        temp = si.getTempC()
    fan = Fan()
    fan.adjust(temp, test)
Exemplo n.º 16
0
def main():
    f = Fan(FAST)
    #	f1 = Fan(FAST, 10, "yellow", True)

    print(f.getState())
Exemplo n.º 17
0
def main():
	
	fan1 = Fan(3, 10,"yellow", True)
	fan2 = Fan(2, 5, "blue", False)
	
	print("Fan1................")
	print("Speed: ", fan1.getSpeed())
	print("Power On/Off: ", fan1.getOn())
	print("Fan Radius: ", fan1.getRadius())
	print("Fan Color: ", fan1.getColor())
	
	print("Fan2................")
	print("Speed: ", fan2.getSpeed())
	print("Power On/Off: ", fan2.getOn())
	print("Fan Radius: ", fan2.getRadius())
	print("Fan Color: ", fan2.getColor())
Exemplo n.º 18
0
from Fan import Fan

blue_fan = Fan()
ask_color = input("Please select a color for your fan\n"
                  "1 - blue\n2 - red\n3 - black\n")
if ask_color == 1:
    Fan.set_color(blue_fan, 'blue')
elif ask_color == 2:
    Fan.set_color(blue_fan, 'red')
elif ask_color == 3:
    Fan.set_color(blue_fan, 'black')
else:
    print("Fail.")

ask_speed = input("Please select the speed of the fan\n"
                  "1 - Slow\n2 - Medium\n3 - Fast\n")

if ask_speed == 1:
    Fan.set_speed(blue_fan, 'slow')
elif ask_speed == 2:
    Fan.set_speed(blue_fan, 'medium')
elif ask_speed == 3:
    Fan.set_speed(blue_fan, 'fast')
else:
    print("You suck at life.")

ask_on_or_off = input("Is the fan on or off?\n" "1 - True\n2 - False\n")

if ask_on_or_off == 1:
    Fan.set_on(blue_fan, True)
elif ask_on_or_off == 2:
Exemplo n.º 19
0
    def __init__(self):
        # Init the IO library 
        io.bbio_init()

        # Make a list of steppers
        self.steppers = {}

        # Init the 5 Stepper motors
        self.steppers["X"]  = SMD(io.GPIO1_12, io.GPIO1_13, io.GPIO2_4,  5, "X")  # Fault_x should be PWM2A?
        self.steppers["Y"]  = SMD(io.GPIO1_31, io.GPIO1_30, io.GPIO1_15, 1, "Y")  
        self.steppers["Z"]  = SMD(io.GPIO1_1,  io.GPIO1_2,  io.GPIO0_27, 2, "Z")  
        self.steppers["E2"]  = SMD(io.GPIO3_21, io.GPIO1_7, io.GPIO2_1,  3, "Ext1")
        self.steppers["E"]  = SMD(io.GPIO1_14, io.GPIO1_6, io.GPIO2_3,  4, "Ext2")

        # Enable the steppers and set the current, steps pr mm and microstepping  
        self.steppers["X"].setCurrentValue(1.0) # 2A
        self.steppers["X"].setEnabled() 
        self.steppers["X"].set_steps_pr_mm(6.105)         
        self.steppers["X"].set_microstepping(2) 

        self.steppers["Y"].setCurrentValue(1.0) # 2A
        self.steppers["Y"].setEnabled() 
        self.steppers["Y"].set_steps_pr_mm(5.95)
        self.steppers["Y"].set_microstepping(2) 

        self.steppers["Z"].setCurrentValue(1.0) # 2A
        self.steppers["Z"].setEnabled() 
        self.steppers["Z"].set_steps_pr_mm(155)
        self.steppers["Z"].set_microstepping(2) 

        self.steppers["E"].setCurrentValue(1.0) # 2A        
        self.steppers["E"].setEnabled()
        self.steppers["E"].set_steps_pr_mm(5.0)
        self.steppers["E"].set_microstepping(2)

        # init the 3 thermistors
        self.therm_ext1 = Thermistor(io.AIN4, "Ext_1", chart_name="QU-BD")
        self.therm_hbp  = Thermistor(io.AIN6, "HBP", chart_name="B57560G104F")

        # init the 3 heaters
        self.mosfet_ext1 = Mosfet(io.PWM2B) # PWM2B on rev1
        self.mosfet_hbp  = Mosfet(io.PWM0C) # PWM0C on rev1 
        self.mosfet_ext2 = Mosfet(io.PWM2A) # 
        # Make extruder 1
        self.ext1 = Extruder(self.steppers["E"], self.therm_ext1, self.mosfet_ext1)
        self.ext1.setPvalue(0.5)
        self.ext1.setDvalue(0.1)     
        self.ext1.setIvalue(0.001)

        # Make Heated Build platform 
        self.hbp = HBP( self.therm_hbp, self.mosfet_hbp)       

        # Init the three fans
        self.fan_1 = Fan(1)
        self.fan_2 = Fan(2)
        self.fan_3 = Fan(3)
        self.fans = {0: self.fan_1, 1:self.fan_2, 2:self.fan_3 }

        # Make a queue of commands
        self.commands = Queue.Queue()

        # Set up USB, this receives messages and pushes them on the queue
        self.usb = USB(self.commands)		

        # Get all options 
        self.options = Options()

        # Init the path planner
        self.movement = "RELATIVE"
        self.feed_rate = 3000.0
        self.current_pos = {"X":0.0, "Y":0.0, "Z":0.0, "E":0.0}
        self.acceleration = 300.0/1000.0

        self.path_planner = Path_planner(self.steppers, self.current_pos)         
        self.path_planner.set_acceleration(self.acceleration) 
        logging.debug("Debug prints to console")
Exemplo n.º 20
0
class Replicape:
    ''' Init '''
    def __init__(self):
        # Init the IO library 
        io.bbio_init()

        # Make a list of steppers
        self.steppers = {}

        # Init the 5 Stepper motors
        self.steppers["X"]  = SMD(io.GPIO1_12, io.GPIO1_13, io.GPIO2_4,  5, "X")  # Fault_x should be PWM2A?
        self.steppers["Y"]  = SMD(io.GPIO1_31, io.GPIO1_30, io.GPIO1_15, 1, "Y")  
        self.steppers["Z"]  = SMD(io.GPIO1_1,  io.GPIO1_2,  io.GPIO0_27, 2, "Z")  
        self.steppers["E2"]  = SMD(io.GPIO3_21, io.GPIO1_7, io.GPIO2_1,  3, "Ext1")
        self.steppers["E"]  = SMD(io.GPIO1_14, io.GPIO1_6, io.GPIO2_3,  4, "Ext2")

        # Enable the steppers and set the current, steps pr mm and microstepping  
        self.steppers["X"].setCurrentValue(1.0) # 2A
        self.steppers["X"].setEnabled() 
        self.steppers["X"].set_steps_pr_mm(6.105)         
        self.steppers["X"].set_microstepping(2) 

        self.steppers["Y"].setCurrentValue(1.0) # 2A
        self.steppers["Y"].setEnabled() 
        self.steppers["Y"].set_steps_pr_mm(5.95)
        self.steppers["Y"].set_microstepping(2) 

        self.steppers["Z"].setCurrentValue(1.0) # 2A
        self.steppers["Z"].setEnabled() 
        self.steppers["Z"].set_steps_pr_mm(155)
        self.steppers["Z"].set_microstepping(2) 

        self.steppers["E"].setCurrentValue(1.0) # 2A        
        self.steppers["E"].setEnabled()
        self.steppers["E"].set_steps_pr_mm(5.0)
        self.steppers["E"].set_microstepping(2)

        # init the 3 thermistors
        self.therm_ext1 = Thermistor(io.AIN4, "Ext_1", chart_name="QU-BD")
        self.therm_hbp  = Thermistor(io.AIN6, "HBP", chart_name="B57560G104F")

        # init the 3 heaters
        self.mosfet_ext1 = Mosfet(io.PWM2B) # PWM2B on rev1
        self.mosfet_hbp  = Mosfet(io.PWM0C) # PWM0C on rev1 
        self.mosfet_ext2 = Mosfet(io.PWM2A) # 
        # Make extruder 1
        self.ext1 = Extruder(self.steppers["E"], self.therm_ext1, self.mosfet_ext1)
        self.ext1.setPvalue(0.5)
        self.ext1.setDvalue(0.1)     
        self.ext1.setIvalue(0.001)

        # Make Heated Build platform 
        self.hbp = HBP( self.therm_hbp, self.mosfet_hbp)       

        # Init the three fans
        self.fan_1 = Fan(1)
        self.fan_2 = Fan(2)
        self.fan_3 = Fan(3)
        self.fans = {0: self.fan_1, 1:self.fan_2, 2:self.fan_3 }

        # Make a queue of commands
        self.commands = Queue.Queue()

        # Set up USB, this receives messages and pushes them on the queue
        self.usb = USB(self.commands)		

        # Get all options 
        self.options = Options()

        # Init the path planner
        self.movement = "RELATIVE"
        self.feed_rate = 3000.0
        self.current_pos = {"X":0.0, "Y":0.0, "Z":0.0, "E":0.0}
        self.acceleration = 300.0/1000.0

        self.path_planner = Path_planner(self.steppers, self.current_pos)         
        self.path_planner.set_acceleration(self.acceleration) 
        logging.debug("Debug prints to console")
	
    ''' When a new gcode comes in, excute it '''
    def loop(self):
        try:
            while True:                
                gcode = Gcode(self.commands.get(), self)
                self._execute(gcode)
                self.usb.send_message(gcode.getAnswer())
                self.commands.task_done()
        except KeyboardInterrupt:
            print "Caught signal, exiting" 
            return
        finally:
            self.ext1.disable()
            self.hbp.disable()
            self.usb.close() 
            self.path_planner.exit()   
        logging.debug("Done")
		
    ''' Execute a G-code '''
    def _execute(self, g):
        if g.code() == "G1":                                        # Move (G1 X0.1 Y40.2 F3000)                        
            if g.hasLetter("F"):                                    # Get the feed rate                 
                feed_rate = float(g.getValueByLetter("F"))
                g.removeTokenByLetter("F")
            else:                                                   # If no feed rate is set in the command, use the default. 
                feed_rate = self.feed_rate                         
            smds = {}                                               # All steppers 
            for i in range(g.numTokens()):                          # Run through all tokens
                axis = g.tokenLetter(i)                             # Get the axis, X, Y, Z or E
                smds[axis] = float(g.tokenValue(i))                 # Get tha value, new position or vector             
            path = Path(smds, feed_rate, self.movement)             # Make a path segment from the axes            
            self.path_planner.add_path(path)                        # Add the path. This blocks until the path planner has capacity
        elif g.code() == "G21":                                     # Set units to mm
            self.factor = 1.0
        elif g.code() == "G28":                                     # Home the steppers
            if g.numTokens() == 0:                                  # If no token is given, home all
                g.setTokens(["X0", "Y0", "Z0"])                
            smds = {}                                               # All steppers 
            for i in range(g.numTokens()):                          # Run through all tokens
                axis = g.tokenLetter(i)                             # Get the axis, X, Y, Z or E
                smds[axis] = float(g.tokenValue(i))                 # Get tha value, new position or vector             
            path = Path(smds, self.feed_rate, "ABSOLUTE")           # Make a path segment from the axes
            self.path_planner.add_path(path)                        # Add the path. This blocks until the path planner has capacity
        elif g.code() == "G29": 
            print self.current_pos
        elif g.code() == "G90":                                     # Absolute positioning
            self.movement = "ABSOLUTE"
        elif g.code() == "G91":                                     # Relative positioning 
            self.movement = "RELATIVE"		
        elif g.code() == "G92":                                     # Set the current position of the following steppers
            if g.numTokens() == 0:
                 g.setTokens(["X0", "Y0", "Z0", "E0"])              # If no token is present, do this for all
            for i in range(g.numTokens()):
                axis = g.tokenLetter(i)
                val = float(g.tokenValue(i))
                self.path_planner.set_pos(axis, val)
        elif g.code() == "M17":                                     # Enable all steppers
            for name, stepper in self.steppers.iteritems():
                stepper.setEnabled()            
        elif g.code() == "M30":                                     # Set microstepping (Propietary to Replicape)
            for i in range(g.numTokens()):
                self.steppers[g.tokenLetter(i)].set_microstepping(int(g.tokenValue(i)))            
        elif g.code() == "M84":                                     # Disable all steppers
            self.path_planner.wait_until_done()
            for name, stepper in self.steppers.iteritems():
            	stepper.setDisabled()
        elif g.code() == "M101":									# Deprecated 
            pass 													
        elif g.code() == "M103":									# Deprecated
            pass 													
        elif g.code() == "M104":                                    # Set extruder temperature
            self.ext1.setTargetTemperature(float(g.tokenValue(0)))
        elif g.code() == "M105":                                    # Get Temperature
            answer = "ok T:"+str(self.ext1.getTemperature())
            answer += " B:"+str(int(self.hbp.getTemperature()))
            g.setAnswer(answer)
        elif g.code() == "M106":                                    # Fan on
            if g.hasLetter("P"):
                fan = self.fans[int(g.getValueByLetter("P"))]
                fan.setPWMFrequency(100)
                fan.setValue(float(g.getValueByLetter("S")))	                
            else:
                self.fan_1.setPWMFrequency(100)
                self.fan_1.setValue(float(g.tokenValue(0)))	
        elif g.code() == "M108":									# Deprecated
            pass 													
        elif g.code() == "M110":                                    # Reset the line number counter 
            Gcode.line_number = 0       
        elif g.code() == "M130":                                    # Set PID P-value, Format (M130 P0 S8.0)
            pass
            #if int(self.tokens[0][1]) == 0:
            #    self.ext1.setPvalue(float(self.tokens[1][1::]))
        elif g.code() == "M131":                                    # Set PID I-value, Format (M131 P0 S8.0) 
            pass
            #if int(self.tokens[0][1]) == 0:
            #    self.p.ext1.setPvalue(float(self.tokens[1][1::]))
        elif g.code() == "M132":                                    # Set PID D-value, Format (M132 P0 S8.0)
            pass
            #if int(self.tokens[0][1]) == 0:
            #    self.p.ext1.setPvalue(float(self.tokens[1][1::]))
        elif g.code() == "M140":                                    # Set bed temperature
            self.hbp.setTargetTemperature(float(g.tokenValue(0)))
        else:
            print "Unknown command: "+g.message	
Exemplo n.º 21
0
def main():
    fan1 = Fan(Fan.FAST, True, 10, "Yellow")
    fan2 = Fan(Fan.MEDIUM, False, 5, "Blue")

    print("Fan 1 speed:", fan1.getSpeed())
    print("Fan 1 radius:", fan1.getRadius())
    print("Fan 1 color:", fan1.getColor())
    print("Fan 1 on:", fan1.getOn())
    blankLine()
    print("Fan 2 speed:", fan2.getSpeed())
    print("Fan 2 radius:", fan2.getRadius())
    print("Fan 2 color:", fan2.getColor())
    print("Fan 2 on:", fan2.getOn())
Exemplo n.º 22
0
    def __init__(self):
        """ Init """
        logging.info("Redeem initializing " + version)

        self.printer = Printer()

        # Parse the config files. 
        self.printer.config = CascadingConfigParser(
            ['/etc/redeem/default.cfg', '/etc/redeem/printer.cfg',
             '/etc/redeem/local.cfg'])

        # Get the revision and loglevel from the Config file
        self.revision = self.printer.config.get('System', 'revision', "A4")
        level = self.printer.config.getint('System', 'loglevel')
        if level > 0:
            logging.getLogger().setLevel(level)
	    
        logging.info("Replicape revision " + self.revision)

        # Init the end stops
        EndStop.callback = self.end_stop_hit
        EndStop.inputdev = self.printer.config.get("Endstops", "inputdev");

        if self.revision == "A4" or self.revision == "A4A":
            self.printer.end_stops["X1"] = EndStop("GPIO3_21", 112, "X1",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_X1"))
            self.printer.end_stops["X2"] = EndStop("GPIO0_30", 113, "X2",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_X2"))
            self.printer.end_stops["Y1"] = EndStop("GPIO1_17", 114, "Y1",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_Y1"))
            self.printer.end_stops["Y2"] = EndStop("GPIO1_19", 115, "Y2",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_Y2"))
            self.printer.end_stops["Z1"] = EndStop("GPIO0_31", 123, "Z1",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_Z1"))
            self.printer.end_stops["Z2"] = EndStop("GPIO0_4", 117, "Z2",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_Z2"))
        else:
            self.printer.end_stops["X1"] = EndStop("GPIO0_14", 112, "X1",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_X1"))
            self.printer.end_stops["X2"] = EndStop("GPIO3_21", 113, "X2",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_X2"))
            self.printer.end_stops["Y1"] = EndStop("GPIO2_2", 114, "Y1",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_Y1"))
            self.printer.end_stops["Y2"] = EndStop("GPIO0_31", 115, "Y2",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_Y2"))
            self.printer.end_stops["Z1"] = EndStop("GPIO0_30", 123, "Z1",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_Z1"))
            self.printer.end_stops["Z2"] = EndStop("GPIO0_4", 117, "Z2",
                                                   self.printer.config.getboolean(
                                                       "Endstops",
                                                       "invert_Z2"))

        if self.revision == "A3":
            Stepper.revision = "A3"
            Stepper.ENABLED = 6
            Stepper.SLEEP = 5
            Stepper.RESET = 4
            Stepper.DECAY = 0

        # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
        self.printer.steppers["X"] = Stepper("GPIO0_27", "GPIO1_29", "GPIO2_4",
                                             0, "X",
                                             self.printer.end_stops["X1"], 0,
                                             0)
        self.printer.steppers["Y"] = Stepper("GPIO1_12", "GPIO0_22", "GPIO2_5",
                                             1, "Y",
                                             self.printer.end_stops["Y1"], 1,
                                             1)
        self.printer.steppers["Z"] = Stepper("GPIO0_23", "GPIO0_26",
                                             "GPIO0_15", 2, "Z",
                                             self.printer.end_stops["Z1"], 2,
                                             2)
        self.printer.steppers["E"] = Stepper("GPIO1_28", "GPIO1_15", "GPIO2_1",
                                             3, "E", None, 3, 3)
        self.printer.steppers["H"] = Stepper("GPIO1_13", "GPIO1_14", "GPIO2_3",
                                             4, "H", None, 4, 4)

        # Enable the steppers and set the current, steps pr mm and
        # microstepping
        for name, stepper in self.printer.steppers.iteritems():
            stepper.set_current_value(
                self.printer.config.getfloat('Steppers', 'current_' + name))
            stepper.in_use = self.printer.config.getboolean('Steppers',
                                                            'in_use_' + name)
            stepper.set_steps_pr_mm(self.printer.config.getfloat('Steppers',
                                                                 'steps_pr_mm_' + name))
            stepper.set_microstepping(self.printer.config.getint('Steppers',
                                                                 'microstepping_' + name))
            stepper.direction = self.printer.config.getint('Steppers',
                                                           'direction_' + name)
            stepper.set_decay(self.printer.config.getboolean("Steppers",
                                                             "slow_decay_" + name))
            stepper.has_endstop = self.printer.config.getboolean('Endstops',
                                                                 'has_' + name)

        # Commit changes for the Steppers
        Stepper.commit()

        # Find the path of the thermistors
        path = "/sys/bus/iio/devices/iio:device0/in_voltage"

        # init the 3 thermistors
        therm_ext1 = Thermistor(path + "4_raw", "MOSFET Ext 1",
                                self.printer.config.get('Heaters',
                                                        "ext1_temp_chart"))
        therm_hbp = Thermistor(path + "6_raw", "MOSFET HBP",
                               self.printer.config.get('Heaters',
                                                       "hbp_temp_chart"))
        therm_ext2 = Thermistor(path + "5_raw", "MOSFET Ext 2",
                                self.printer.config.get('Heaters',
                                                        "ext2_temp_chart"))

        path = self.printer.config.get('Cold-ends', 'path', 0)
        if os.path.exists(path):
            self.printer.cold_ends.append(ColdEnd(path, "Cold End 0"))
            logging.info("Found Cold end on " + path)
        else:
            logging.info("No cold end present in path: " + path)

        # Init the 3 heaters. Argument is channel number
        if self.revision == "A3":
            mosfet_ext1 = Mosfet(3)
            mosfet_ext2 = Mosfet(5)
            mosfet_hbp = Mosfet(4)
        else:
            mosfet_ext1 = Mosfet(5)
            mosfet_ext2 = Mosfet(3)
            mosfet_hbp = Mosfet(4)

        # Make extruder 1
        self.printer.heaters['E'] = Extruder(self.printer.steppers["E"],
                                             therm_ext1, mosfet_ext1, "Ext1",
                                             self.printer.config.getboolean(
                                                 'Heaters',
                                                 'ext1_onoff_control'))
        self.printer.heaters['E'].P = self.printer.config.getfloat('Heaters',
                                                                   "ext1_pid_p")
        self.printer.heaters['E'].I = self.printer.config.getfloat('Heaters',
                                                                   "ext1_pid_i")
        self.printer.heaters['E'].D = self.printer.config.getfloat('Heaters',
                                                                   "ext1_pid_d")
        self.printer.heaters['E'].ok_range = self.printer.config.getfloat(
            'Heaters', "ext1_ok_range")

        # Make Heated Build platform 
        self.printer.heaters['HBP'] = HBP(therm_hbp, mosfet_hbp,
                                          self.printer.config.getboolean(
                                              'Heaters', 'hbp_onoff_control'))
        self.printer.heaters['HBP'].P = self.printer.config.getfloat('Heaters',
                                                                     "hbp_pid_p")
        self.printer.heaters['HBP'].I = self.printer.config.getfloat('Heaters',
                                                                     "hbp_pid_i")
        self.printer.heaters['HBP'].D = self.printer.config.getfloat('Heaters',
                                                                     "hbp_pid_d")
        self.printer.heaters['HBP'].ok_range = self.printer.config.getfloat(
            'Heaters', "hbp_ok_range")

        # Make extruder 2.
        self.printer.heaters['H'] = Extruder(self.printer.steppers["H"],
                                             therm_ext2, mosfet_ext2, "Ext2",
                                             self.printer.config.getboolean(
                                                 'Heaters',
                                                 'ext2_onoff_control'))
        self.printer.heaters['H'].P = self.printer.config.getfloat('Heaters',
                                                                   "ext2_pid_p")
        self.printer.heaters['H'].I = self.printer.config.getfloat('Heaters',
                                                                   "ext2_pid_i")
        self.printer.heaters['H'].D = self.printer.config.getfloat('Heaters',
                                                                   "ext2_pid_d")
        self.printer.heaters['H'].ok_range = self.printer.config.getfloat(
            'Heaters', "ext2_ok_range")

        # Init the three fans. Argument is PWM channel number
        self.printer.fans = []
        if self.revision == "A3":
            self.printer.fans.append(Fan(0))
            self.printer.fans.append(Fan(1))
            self.printer.fans.append(Fan(2))
        else:
            self.printer.fans.append(Fan(8))
            self.printer.fans.append(Fan(9))
            self.printer.fans.append(Fan(10))

        Fan.set_PWM_frequency(100)

        for f in self.printer.fans:
            f.set_value(0)

        # Connect the cold end 0 to fan 2
        # This is very "Thing" specific, should be configurable somehow. 
        if len(self.printer.cold_ends):
            self.printer.coolers.append(
                Cooler(self.printer.cold_ends[0], self.printer.fans[2],
                       "Cooler0", False))
            self.printer.coolers[0].ok_range = 4
            self.printer.coolers[0].set_target_temperature(60)
            self.printer.coolers[0].enable()

            # Make a queue of commands
        self.printer.commands = JoinableQueue(10)

        # Make a queue of commands that should not be buffered
        self.printer.unbuffered_commands = JoinableQueue(10)

        # Init the path planner
        Path.axis_config = int(
            self.printer.config.get('Geometry', 'axis_config'))
        Path.max_speeds[0] = float(
            self.printer.config.get('Steppers', 'max_speed_x'))
        Path.max_speeds[1] = float(
            self.printer.config.get('Steppers', 'max_speed_y'))
        Path.max_speeds[2] = float(
            self.printer.config.get('Steppers', 'max_speed_z'))
        Path.max_speeds[3] = float(
            self.printer.config.get('Steppers', 'max_speed_e'))
        Path.max_speeds[4] = float(
            self.printer.config.get('Steppers', 'max_speed_h'))

        Path.home_speed[0] = float(
            self.printer.config.get('Steppers', 'home_speed_x'))
        Path.home_speed[1] = float(
            self.printer.config.get('Steppers', 'home_speed_y'))
        Path.home_speed[2] = float(
            self.printer.config.get('Steppers', 'home_speed_z'))
        Path.home_speed[3] = float(
            self.printer.config.get('Steppers', 'home_speed_e'))
        Path.home_speed[4] = float(
            self.printer.config.get('Steppers', 'home_speed_h'))

        Path.steps_pr_meter[0] = self.printer.steppers[
            "X"].get_steps_pr_meter()
        Path.steps_pr_meter[1] = self.printer.steppers[
            "Y"].get_steps_pr_meter()
        Path.steps_pr_meter[2] = self.printer.steppers[
            "Z"].get_steps_pr_meter()
        Path.steps_pr_meter[3] = self.printer.steppers[
            "E"].get_steps_pr_meter()
        Path.steps_pr_meter[4] = self.printer.steppers[
            "H"].get_steps_pr_meter()

        dirname = os.path.dirname(os.path.realpath(__file__))

        # Create the firmware compiler
        pru_firmware = PruFirmware(
            dirname + "/../firmware/firmware_runtime.p",
            dirname + "/../firmware/firmware_runtime.bin",
            dirname + "/../firmware/firmware_endstops.p",
            dirname + "/../firmware/firmware_endstops.bin",
            self.revision, self.printer.config, "/usr/bin/pasm")

	self.printer.maxJerkXY = float(
            self.printer.config.get('Steppers', 'maxJerk_xy'));
	self.printer.maxJerkZ = float(
            self.printer.config.get('Steppers', 'maxJerk_z'));
	self.printer.maxJerkEH = float(
            self.printer.config.get('Steppers', 'maxJerk_eh'));


        self.printer.path_planner = PathPlanner(self.printer, pru_firmware)

        travel = {}
        offset = {}
	i = 0
        for axis in ['X', 'Y', 'Z', 'E', 'H']:
            travel[axis] = self.printer.config.getfloat('Geometry',
                                                        'travel_' + axis.lower())
            offset[axis] = self.printer.config.getfloat('Geometry',
                                                        'offset_' + axis.lower())
	    self.printer.acceleration[i] = self.printer.config.getfloat('Steppers', 'acceleration_' + axis.lower())
	    i += 1



        self.printer.path_planner.travel_length = travel
        self.printer.path_planner.center_offset = offset
        self.printer.processor = GCodeProcessor(self.printer)

        # Set up communication channels
        self.printer.comms["USB"] = USB(self.printer)
        self.printer.comms["Eth"] = Ethernet(self.printer)
        self.printer.comms["octoprint"] = Pipe(self.printer,
                                               "octoprint")   # Pipe for Octoprint
        self.printer.comms["toggle"] = Pipe(self.printer,
                                            "toggle")      # Pipe for Toggle
        self.printer.comms["testing"] = Pipe(self.printer,
                                             "testing")     # Pipe for testing
        self.printer.comms["testing_noret"] = Pipe(self.printer,
                                                   "testing_noret")     # Pipe for testing
        self.printer.comms["testing_noret"].send_response = False

        self.running = True

        # Start the two processes
        p0 = Thread(target=self.loop,
                    args=(self.printer.commands, "buffered"))
        p1 = Thread(target=self.loop,
                    args=(self.printer.unbuffered_commands, "unbuffered"))
        p0.daemon = True
        p1.daemon = True

        p0.start()
        p1.start()

        # Signal everything ready
        logging.info("Redeem ready")

        # Wait for exit signal
        p0.join()
        p1.join()
Exemplo n.º 23
0
    def __init__(self):
        logging.info("Replicape initializing " + version)
        self.config = ConfigParser.ConfigParser()
        self.config.readfp(open('config/default.cfg'))

        # Make a list of steppers
        self.steppers = {}

        # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
        self.steppers["X"] = SMD("GPIO0_27", "GPIO1_29", "GPIO2_4", 0, "X")
        self.steppers["Y"] = SMD("GPIO1_12", "GPIO0_22", "GPIO2_5", 1, "Y")
        self.steppers["Z"] = SMD("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, "Z")
        self.steppers["H"] = SMD("GPIO1_28", "GPIO1_15", "GPIO2_1", 3, "Ext1")
        self.steppers["E"] = SMD("GPIO1_13", "GPIO1_14", "GPIO2_3", 4, "Ext2")

        # Enable the steppers and set the current, steps pr mm and microstepping
        for name, stepper in self.steppers.iteritems():
            stepper.setCurrentValue(
                self.config.getfloat('Steppers', 'current_' + name))
            stepper.setEnabled(
                self.config.getboolean('Steppers', 'enabled_' + name))
            stepper.set_steps_pr_mm(
                self.config.getfloat('Steppers', 'steps_pr_mm_' + name))
            stepper.set_microstepping(
                self.config.getint('Steppers', 'microstepping_' + name))
            stepper.set_decay(0)

# Commit changes for the Steppers
        SMD.commit()

        # Find the path of the thermostors
        path = "/sys/bus/iio/devices/iio:device0/in_voltage"

        # init the 3 thermistors
        self.therm_ext1 = Thermistor(path + "4_raw", "MOSFET Ext 1",
                                     "B57561G0103F000")  # Epcos 10K
        self.therm_hbp = Thermistor(path + "6_raw", "MOSFET HBP",
                                    "B57560G104F")  # Epcos 100K
        self.therm_ext2 = Thermistor(path + "5_raw", "MOSFET Ext 2",
                                     "B57561G0103F000")  # Epcos 10K

        if os.path.exists("/sys/bus/w1/devices/28-000002e34b73/w1_slave"):
            self.cold_end_1 = W1(
                "/sys/bus/w1/devices/28-000002e34b73/w1_slave", "Cold End 1")

        # init the 3 heaters
        self.mosfet_ext1 = Mosfet(3)
        self.mosfet_ext2 = Mosfet(4)
        self.mosfet_hbp = Mosfet(5)

        # Make extruder 1
        self.ext1 = Extruder(self.steppers["E"], self.therm_ext1,
                             self.mosfet_ext1, "Ext1")
        self.ext1.setPvalue(0.1)
        self.ext1.setDvalue(0.3)
        self.ext1.setIvalue(0.0)

        # Make Heated Build platform
        self.hbp = HBP(self.therm_hbp, self.mosfet_hbp)

        # Make extruder 2.
        self.ext2 = Extruder(self.steppers["H"], self.therm_ext2,
                             self.mosfet_ext2, "Ext2")
        self.ext1.setPvalue(0.1)
        self.ext1.setDvalue(0.3)
        self.ext1.setIvalue(0.0)

        self.current_tool = "E"

        # Init the three fans
        self.fan_1 = Fan(1)
        self.fan_2 = Fan(2)
        self.fan_3 = Fan(0)
        self.fans = {0: self.fan_1, 1: self.fan_2, 2: self.fan_3}

        self.fan_1.setPWMFrequency(100)

        # Init the end stops
        self.end_stops = {}
        self.end_stops["Y1"] = EndStop("GPIO2_2", self.steppers, 1, "Y1")
        self.end_stops["X1"] = EndStop("GPIO0_14", self.steppers, 2, "X1")
        self.end_stops["Z1"] = EndStop("GPIO0_30", self.steppers, 3, "Z1")
        self.end_stops["Y2"] = EndStop("GPIO3_21", self.steppers, 4, "Y2")
        self.end_stops["X2"] = EndStop("GPIO0_31", self.steppers, 5, "X2")
        self.end_stops["Z2"] = EndStop("GPIO0_4", self.steppers, 6, "Z2")

        # Make a queue of commands
        self.commands = Queue.Queue(10)

        # Set up USB, this receives messages and pushes them on the queue
        #self.usb = USB(self.commands)
        self.pipe = Pipe(self.commands)
        self.ethernet = Ethernet(self.commands)

        # Init the path planner
        self.movement = "RELATIVE"
        self.feed_rate = 3000.0
        self.current_pos = {"X": 0.0, "Y": 0.0, "Z": 0.0, "E": 0.0, "H": 0.0}
        self.acceleration = 0.3
        Path.axis_config = int(self.config.get('Geometry', 'axis_config'))
        Path.max_speed_x = float(self.config.get('Steppers', 'max_speed_x'))
        Path.max_speed_y = float(self.config.get('Steppers', 'max_speed_y'))
        Path.max_speed_z = float(self.config.get('Steppers', 'max_speed_z'))
        Path.max_speed_e = float(self.config.get('Steppers', 'max_speed_e'))
        Path.max_speed_h = float(self.config.get('Steppers', 'max_speed_h'))

        self.path_planner = Path_planner(self.steppers, self.current_pos)
        self.path_planner.set_acceleration(self.acceleration)

        # Signal everything ready
        logging.info("Replicape ready")
        print "Replicape ready"
Exemplo n.º 24
0
from Fan import Fan

#create two Fan objects
f1 = Fan(3, 10, "yellow", True)
f2 = Fan(2)
print(f1)
print(f2)
Exemplo n.º 25
0
    def __init__(self):
        logging.info("Redeem initializing " + version)

        self.printer = Printer()

        # Parse the config
        self.printer.config = CascadingConfigParser(
            ['/etc/redeem/default.cfg', '/etc/redeem/local.cfg'])

        # Get the revision from the Config file
        self.revision = self.printer.config.get('System', 'revision', "A4")
        logging.info("Replicape revision " + self.revision)

        # Init the end stops
        EndStop.callback = self.end_stop_hit
        EndStop.inputdev = self.printer.config.get("Endstops", "inputdev")

        if self.revision == "A4":
            self.printer.end_stops["X1"] = EndStop(
                "GPIO3_21", 112, "X1",
                self.printer.config.getboolean("Endstops", "invert_X1"))
            self.printer.end_stops["X2"] = EndStop(
                "GPIO0_30", 113, "X2",
                self.printer.config.getboolean("Endstops", "invert_X2"))
            self.printer.end_stops["Y1"] = EndStop(
                "GPIO1_17", 114, "Y1",
                self.printer.config.getboolean("Endstops", "invert_Y1"))
            self.printer.end_stops["Y2"] = EndStop(
                "GPIO1_19", 115, "Y2",
                self.printer.config.getboolean("Endstops", "invert_Y2"))
            self.printer.end_stops["Z1"] = EndStop(
                "GPIO0_31", 116, "Z1",
                self.printer.config.getboolean("Endstops", "invert_Z1"))
            self.printer.end_stops["Z2"] = EndStop(
                "GPIO0_4", 117, "Z2",
                self.printer.config.getboolean("Endstops", "invert_Z2"))
        else:
            self.printer.end_stops["X1"] = EndStop(
                "GPIO0_14", 112, "X1",
                self.printer.config.getboolean("Endstops", "invert_X1"))
            self.printer.end_stops["X2"] = EndStop(
                "GPIO3_21", 113, "X2",
                self.printer.config.getboolean("Endstops", "invert_X2"))
            self.printer.end_stops["Y1"] = EndStop(
                "GPIO2_2", 114, "Y1",
                self.printer.config.getboolean("Endstops", "invert_Y1"))
            self.printer.end_stops["Y2"] = EndStop(
                "GPIO0_31", 115, "Y2",
                self.printer.config.getboolean("Endstops", "invert_Y2"))
            self.printer.end_stops["Z1"] = EndStop(
                "GPIO0_30", 116, "Z1",
                self.printer.config.getboolean("Endstops", "invert_Z1"))
            self.printer.end_stops["Z2"] = EndStop(
                "GPIO0_4", 117, "Z2",
                self.printer.config.getboolean("Endstops", "invert_Z2"))

        if self.revision == "A3":
            Stepper.revision = "A3"
            Stepper.ENABLED = 6
            Stepper.SLEEP = 5
            Stepper.RESET = 4
            Stepper.DECAY = 0

        # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
        self.printer.steppers["X"] = Stepper("GPIO0_27", "GPIO1_29", "GPIO2_4",
                                             0, "X",
                                             self.printer.end_stops["X1"], 0,
                                             0)
        self.printer.steppers["Y"] = Stepper("GPIO1_12", "GPIO0_22", "GPIO2_5",
                                             1, "Y",
                                             self.printer.end_stops["Y1"], 1,
                                             1)
        self.printer.steppers["Z"] = Stepper("GPIO0_23", "GPIO0_26",
                                             "GPIO0_15", 2, "Z",
                                             self.printer.end_stops["Z1"], 2,
                                             2)
        self.printer.steppers["E"] = Stepper("GPIO1_28", "GPIO1_15", "GPIO2_1",
                                             3, "Ext1", None, 3, 3)
        self.printer.steppers["H"] = Stepper("GPIO1_13", "GPIO1_14", "GPIO2_3",
                                             4, "Ext2", None, 4, 4)

        # Enable the steppers and set the current, steps pr mm and microstepping
        for name, stepper in self.printer.steppers.iteritems():
            stepper.set_current_value(
                self.printer.config.getfloat('Steppers', 'current_' + name))
            if self.printer.config.getboolean('Steppers', 'enabled_' + name):
                stepper.set_enabled()
            else:
                stepper.set_disabled()
            stepper.set_steps_pr_mm(
                self.printer.config.getfloat('Steppers',
                                             'steps_pr_mm_' + name))
            stepper.set_microstepping(
                self.printer.config.getint('Steppers',
                                           'microstepping_' + name))
            stepper.direction = self.printer.config.getint(
                'Steppers', 'direction_' + name)
            stepper.set_decay(
                self.printer.config.getboolean("Steppers",
                                               "slow_decay_" + name))

# Commit changes for the Steppers
        Stepper.commit()

        # Find the path of the thermistors
        path = "/sys/bus/iio/devices/iio:device0/in_voltage"

        # init the 3 thermistors
        therm_ext1 = Thermistor(
            path + "4_raw", "MOSFET Ext 1",
            self.printer.config.get('Heaters', "ext1_temp_chart"))
        therm_hbp = Thermistor(
            path + "6_raw", "MOSFET HBP",
            self.printer.config.get('Heaters', "hbp_temp_chart"))
        therm_ext2 = Thermistor(
            path + "5_raw", "MOSFET Ext 2",
            self.printer.config.get('Heaters', "ext2_temp_chart"))

        path = self.printer.config.get('Cold-ends', 'path', 0)
        if os.path.exists(path):
            self.printer.cold_ends.append(ColdEnd(path, "Cold End 1"))
            logging.info("Found Cold end on " + path)
        else:
            logging.info("No cold end present in path: " + path)

        # Init the 3 heaters. Argument is channel number
        if self.revision == "A3":
            mosfet_ext1 = Mosfet(3)
            mosfet_ext2 = Mosfet(4)
            mosfet_hbp = Mosfet(5)
        else:
            mosfet_ext1 = Mosfet(5)
            mosfet_ext2 = Mosfet(3)
            mosfet_hbp = Mosfet(4)

        # Make extruder 1
        self.printer.heaters['E'] = Extruder(
            self.printer.steppers["E"], therm_ext1, mosfet_ext1, "Ext1",
            self.printer.config.getboolean('Heaters', 'ext1_onoff_control'))
        self.printer.heaters['E'].set_p_value(
            self.printer.config.getfloat('Heaters', "ext1_pid_p"))
        self.printer.heaters['E'].set_d_value(
            self.printer.config.getfloat('Heaters', "ext1_pid_d"))
        self.printer.heaters['E'].set_i_value(
            self.printer.config.getfloat('Heaters', "ext1_pid_i"))
        self.printer.heaters['E'].ok_range = self.printer.config.getfloat(
            'Heaters', "ext1_ok_range")

        # Make Heated Build platform
        self.printer.heaters['HBP'] = HBP(
            therm_hbp, mosfet_hbp,
            self.printer.config.getboolean('Heaters', 'hbp_onoff_control'))
        self.printer.heaters['HBP'].set_p_value(
            self.printer.config.getfloat('Heaters', "hbp_pid_p"))
        self.printer.heaters['HBP'].set_d_value(
            self.printer.config.getfloat('Heaters', "hbp_pid_i"))
        self.printer.heaters['HBP'].set_i_value(
            self.printer.config.getfloat('Heaters', "hbp_pid_d"))
        self.printer.heaters['HBP'].ok_range = self.printer.config.getfloat(
            'Heaters', "hbp_ok_range")

        # Make extruder 2.
        self.printer.heaters['H'] = Extruder(
            self.printer.steppers["H"], therm_ext2, mosfet_ext2, "Ext2",
            self.printer.config.getboolean('Heaters', 'ext2_onoff_control'))
        self.printer.heaters['H'].set_p_value(
            self.printer.config.getfloat('Heaters', "ext2_pid_p"))
        self.printer.heaters['H'].set_d_value(
            self.printer.config.getfloat('Heaters', "ext2_pid_i"))
        self.printer.heaters['H'].set_i_value(
            self.printer.config.getfloat('Heaters', "ext2_pid_d"))
        self.printer.heaters['H'].ok_range = self.printer.config.getfloat(
            'Heaters', "ext2_ok_range")

        # Init the three fans. Argument is PWM channel number
        self.printer.fans = []
        if self.revision == "A3":
            self.printer.fans.append(Fan(1))
            self.printer.fans.append(Fan(2))
            self.printer.fans.append(Fan(0))
        else:
            self.printer.fans.append(Fan(8))
            self.printer.fans.append(Fan(9))
            self.printer.fans.append(Fan(10))

        Fan.set_PWM_frequency(100)

        for f in self.printer.fans:
            f.set_value(0)

        # Make a queue of commands
        self.commands = Queue.Queue(10)

        # Set up USB, this receives messages and pushes them on the queue
        self.usb = USB(self.commands)
        # Virtual TTY
        self.pipe = Pipe(self.commands)
        #self.pipe.set_send_reponse(False)
        self.ethernet = Ethernet(self.commands)

        # Init the path planner
        Path.axis_config = int(
            self.printer.config.get('Geometry', 'axis_config'))
        Path.max_speed_x = float(
            self.printer.config.get('Steppers', 'max_speed_x'))
        Path.max_speed_y = float(
            self.printer.config.get('Steppers', 'max_speed_y'))
        Path.max_speed_z = float(
            self.printer.config.get('Steppers', 'max_speed_z'))
        Path.max_speed_e = float(
            self.printer.config.get('Steppers', 'max_speed_e'))
        Path.max_speed_h = float(
            self.printer.config.get('Steppers', 'max_speed_h'))

        Path.home_speed_x = float(
            self.printer.config.get('Steppers', 'home_speed_x'))
        Path.home_speed_y = float(
            self.printer.config.get('Steppers', 'home_speed_y'))
        Path.home_speed_z = float(
            self.printer.config.get('Steppers', 'home_speed_z'))
        Path.home_speed_e = float(
            self.printer.config.get('Steppers', 'home_speed_e'))
        Path.home_speed_h = float(
            self.printer.config.get('Steppers', 'home_speed_h'))

        dirname = os.path.dirname(os.path.realpath(__file__))

        # Create the firmware compiler
        pru_firmware = PruFirmware(
            dirname + "/../firmware/firmware_runtime.p",
            dirname + "/../firmware/firmware_runtime.bin",
            dirname + "/../firmware/firmware_endstops.p",
            dirname + "/../firmware/firmware_endstops.bin", self.revision,
            self.printer.config, "/usr/bin/pasm")

        self.printer.path_planner = PathPlanner(self.printer.steppers,
                                                pru_firmware)
        self.printer.path_planner.set_acceleration(
            float(self.printer.config.get('Steppers', 'acceleration')))

        travel = {}
        offset = {}
        for axis in ['X', 'Y', 'Z']:
            travel[axis] = self.printer.config.getfloat(
                'Geometry', 'travel_' + axis.lower())
            offset[axis] = self.printer.config.getfloat(
                'Geometry', 'offset_' + axis.lower())

        self.printer.path_planner.set_travel_length(travel)
        self.printer.path_planner.set_center_offset(offset)

        self.printer.processor = GCodeProcessor(self.printer)

        # After the firmwares are loaded, the endstop states can be updated.
        for k, endstop in self.printer.end_stops.iteritems():
            logging.debug("Endstop " + endstop.name + " hit? : " +
                          str(endstop.read_value()))

        self.running = True

        # Signal everything ready
        logging.info("Redeem ready")
Exemplo n.º 26
0
screen_size = (1280, 665)
screen = pygame.display.set_mode(screen_size)

background_image = pygame.image.load("soccer2.jpg")
#player_image = pygame.image.load("soccer_player.png")
# soccer_ball = pygame.image.load("soccer_ball.png")
pygame.display.set_caption("Soccer Game!")
pygame.mixer.music.load("music.wav")
pygame.mixer.music.play(-1)
FPS = 60

player = Player(screen)
defense = Defense(screen)
ball = Ball(screen)
fan = Fan(screen)

players = Group()
players.add(player)
balls = Group()
balls.add(ball)
defenses = Group()
defenses.add(defense)
cups = Group()

ball_place = True
score = 2

black = (0, 0, 0)

#ball_rect = pygame.Rect(ball.x, ball.y, ball.width, ball.height)
Exemplo n.º 27
0
 def __init__(self):
     self.logger = Logger("CO2_stat")
     self.logger.debug("initialize CO2 controller object")
     self._co2 = SCD30(self.logger)
     self._fan = Fan(self.logger)
Exemplo n.º 28
0
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
filehandle.setFormatter(formatter)
logger.addHandler(filehandle)

logger.info("Sample log")

if fan_upper_bound < no_fan or subsystem_upper_bound<no_subsystem:
    logger.error("Server startup fail: Limit exceeds the upper bound")
    print("System can not start: Check log file")
    exit()
for i in range(no_subsystem):
    subsystem=Subsystem(monitor, i)
    subsystems.append(subsystem)

for i in range(no_fan):
    fan=Fan(monitor, i, 130)
    fans.append(fan)

app=Flask(__name__)


@app.route('/fan',methods=['GET','POST','PUT'])
def fan_operations():
    content=request.json 
    if request.method == 'PUT':
        index = content['index']
        max_speed = content['max_speed']
        fans[index].set_max_rpm(max_speed)
        return 'Fan Speed Updated'

    if request.method == 'GET':
Exemplo n.º 29
0
class Interface(object):
    def __init__(self):
        self.i2cbus = SMBus(1)
        self.oled = ssd1306(self.i2cbus)
        self.font = ImageFont.truetype('/home/pi/Code/FreeSans.ttf', 10)
        self.font2 = ImageFont.truetype('/home/pi/Code/FreeSans.ttf', 11)
        self.font3 = ImageFont.truetype('/home/pi/Code/FreeSans.ttf', 18)
        self.font4 = ImageFont.truetype('/home/pi/Code/FreeSans.ttf', 36)
        self.disp = self.oled.canvas
        self.padding = 1
        self.top = self.padding
        self.bottom = self.oled.height - self.padding
        self.left = self.padding
        self.right = self.oled.width - self.padding
        self.line1 = 17
        self.line2 = 29
        self.line3 = 41
        self.line4 = 53
        self.lines = [self.line1, self.line2, self.line3, self.line4]
        self.column1 = self.left + 2
        self.column2 = self.left + 64
        self.column3 = self.right - 44
        self.selector = 0
        self.interfaces = []
        self.currentMenu = None
        self.b = None
        self.busy = False
        self.exit = False
        self.lock = Lock()
        self.stepsPerDeg = 1
        self.stepsPerUnit = 1
        self.motorStepTime = 0.01
        self.sequenceStartTime = 0
        self.timeStamp = 0
        self.lastRun = 0
        self.xEvent = threading.Event()
        self.rEvent = threading.Event()
        return

    #Define pin inputs and outputs
    def setControls(self, enter, go, LED, up, down):
        self.enterButt = enter
        self.goButt = go
        self.buttLED = LED
        #Button Indicator Settings
        self.buttLEDfreq = 1
        self.buttDuty = 25

        #Pin assignments
        GPIO.setup(self.buttLED, GPIO.OUT)
        GPIO.setup(self.goButt, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.enterButt, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        GPIO.add_event_detect(self.goButt,
                              GPIO.FALLING,
                              callback=self.goSTART,
                              bouncetime=500)
        GPIO.add_event_detect(self.enterButt,
                              GPIO.FALLING,
                              callback=self.selectButt,
                              bouncetime=500)
        self.encoder = RotaryEncoder(up, down, self.decode)
        self.buttON(True)
        time.sleep(0.125)
        self.buttON(False)
        time.sleep(0.125)
        self.buttON(True)
        time.sleep(0.125)
        self.buttON(False)
        return

    #Calibrate the Motors
    def homeMotors(self):
        self.fan(True)
        self.xMotor.calibrate()
        #self.rMotor.calibrate()
        self.fan(True)
        return

    #Define the fan pins
    def setFan(self, pin):
        self.blower = Fan(pin, 100, 0.25, 120)
        return

    #Define Camera Trigger Pins
    def setCamTrigger(self, half, full):
        self.halfPress = half
        self.fullPress = full
        GPIO.setup(self.halfPress, GPIO.OUT)
        GPIO.setup(self.fullPress, GPIO.OUT)
        GPIO.output(self.halfPress, True)
        GPIO.output(self.fullPress, True)
        return

    #Turn the button LED on or off (Button)
    def buttON(self, val):
        GPIO.output(self.buttLED, val)
        return

    #Create menu items
    def populate(self):
        self.main = Menu('Main Menu')

        self.ready = Go('Capture')
        self.preview = Go('Preview')
        self.movement = Menu('Movement')
        self.displacement = Menu('Displacement')
        self.time = Menu('Time')
        self.drive = Menu('Drive')

        self.translation = Menu('Translation')
        self.rotation = Menu('Rotation')
        self.initPos = Menu('Initial Positions')
        self.travDir = Menu('Travel Directions')

        self.camera = Menu('Camera')

        self.calibrate = Menu('Calibrate')
        self.manualControl = Menu('Manual Control')

        self.freeMove = Action('User Control X')
        self.freeRotate = Action('User Control R')

        self.totalDisp = Option('Total Displace')
        self.incDisp = Option('Increment')

        self.totalRot = Option('Total Rotation')
        self.incRot = Option('Increment')

        self.initX = Option('Initial X-Position')
        self.initR = Option('Initial R-Position')

        self.travX = Option('Initial X-Direction')
        self.travR = Option('Initial R-Direction')

        self.tVal = Camera('Time Value')  # Shutter speed of camera
        self.nomages = Option('Images')  # Number of images to capture

        self.inter = Option('Interval')  # Interval between shots in seconds
        self.totalTime = Option(
            'Total Time')  # Total time of sequence in minutes

        self.calTrans = Action('Translation')
        self.calRot = Action('Rotation')

        self.hold = Option('Holding Power')

        self.main.setItems(self.ready, self.movement, self.time, self.drive)
        self.main.pageInfo = 'Today'

        self.movement.setItems(self.displacement, self.initPos, self.travDir,
                               self.main)
        self.displacement.setItems(self.translation, self.rotation,
                                   self.movement)
        self.drive.setItems(self.calibrate, self.manualControl, self.hold,
                            self.main)
        self.time.setItems(self.totalTime, self.inter, self.camera, self.main)
        self.manualControl.setItems(self.freeMove, self.freeRotate, self.drive)
        self.ready.setItems(self.preview, self.main)
        self.ready.setHardware(self.xMotor, self.rMotor)
        self.ready.setSubtitle('Shots')
        self.preview.setItems(self.ready, self.main)
        self.preview.setHardware(self.xMotor, self.rMotor)
        self.preview.setSubtitle('Preview')

        self.translation.setItems(self.totalDisp, self.incDisp, self.movement)
        self.initPos.setItems(self.initX, self.initR, self.movement)
        self.travDir.setItems(self.travX, self.travR, self.movement)
        self.rotation.setItems(self.totalRot, self.incRot, self.movement)
        self.camera.setItems(self.tVal, self.nomages, self.time)

        self.calibrate.setItems(self.calTrans, self.calRot, self.drive)
        self.freeMove.setItems(self.manualControl)
        self.freeMove.setHardware(self.xMotor)
        self.freeRotate.setItems(self.manualControl)
        self.freeRotate.setHardware(self.rMotor)
        self.hold.setItems(self.drive)
        self.hold.hasRange(True)
        self.hold.setRange(0, 2)
        self.hold.hasAlternate(True)
        self.hold.setAlternate('OFF', 'LOW', 'HIGH')
        self.hold.setVal(1)

        self.totalDisp.setItems(self.translation)
        self.totalDisp.canZero(True)
        self.totalDisp.setVal(10000)
        self.totalDisp.setMultiplier(100)
        self.incDisp.setItems(self.translation)
        self.incDisp.canZero(True)
        self.incDisp.setVal(1)

        self.totalRot.setItems(self.rotation)
        self.totalRot.canZero(True)
        self.totalRot.setVal(90)
        self.incRot.setItems(self.rotation)
        self.incRot.canZero(True)
        self.incRot.setVal(1)

        self.totalTime.setItems(self.time)
        self.totalTime.setVal(45)
        self.inter.setItems(self.time)
        self.inter.setVal(2)

        self.tVal.setItems(self.camera)
        self.tVal.setVal(0)
        self.nomages.setItems(self.camera)
        self.nomages.setVal(10)

        self.calTrans.setItems(self.calibrate)
        self.calTrans.setHardware(self.xMotor)
        self.calRot.setItems(self.calibrate)
        self.calRot.setHardware(self.rMotor)

        self.travX.setItems(self.travDir)
        self.travX.hasRange(True)
        self.travX.setRange(0, 1)
        self.travX.hasAlternate(True)
        self.travX.setAlternate('FWD', 'REV')
        self.travR.setItems(self.travDir)
        self.travR.hasRange(True)
        self.travR.setRange(0, 1)
        self.travR.hasAlternate(True)
        self.travR.setAlternate('FWD', 'REV')

        self.initX.setItems(self.initPos)
        self.initX.hasRange(True)
        self.initX.setRange(self.xMotor.Limits[0], self.xMotor.Limits[1])
        self.initX.setMultiplier(100)
        self.initR.setItems(self.initPos)
        self.initR.hasRange(True)
        self.initR.setRange(self.rMotor.Limits[0], self.rMotor.Limits[1])
        self.initR.setMultiplier(100)

        self.currentMenu = self.main
        return

    #Turn the fan on or off (Boolean)
    def fan(self, isOn):
        if self.hold.getVal() == 2:
            self.blower.on()
        elif isOn:
            self.blower.on()
        elif ~isOn:
            self.blower.off()
        return

    #Define pins and create translation motor object
    def setTransMotor(self, pinA1, pinA2, pinB1, pinB2, pinENa, pinENb,
                      endButt, steps):
        self.xMotor = Stepper(pinA1, pinA2, pinB1, pinB2, pinENa, pinENb,
                              endButt)
        self.xMotor.invert()
        self.xMotor.pwmHoldSet(1)
        self.stepsPerUnit = steps
        return

    #Define pins and create rotation motor object
    def setRotMotor(self, pinA1, pinA2, pinB1, pinB2, pinENa, pinENb, endButt,
                    steps):
        self.rMotor = Stepper(pinA1, pinA2, pinB1, pinB2, pinENa, pinENb,
                              endButt)
        self.stepsPerDeg = steps
        return

    #Set hard limits of displacement motor
    def setTransLimits(self, min, max):
        self.xMotor.setLimits(min, max)
        return

    #Set hard limits of rotational motor
    def setRotLimits(self, min, max):
        self.rMotor.setLimits(min, max)
        return

    #Update values of current menu
    def updateInfo(self, val):
        if type(self.currentMenu) is Option or type(
                self.currentMenu) is Camera:
            self.currentMenu.setVal(val)
            self.disp.text((self.column3, self.top),
                           str(self.currentMenu.toString()[2]),
                           font=self.font,
                           fill=0)
            self.disp.text((self.column3, self.top),
                           str(self.currentMenu.toString()[1]),
                           font=self.font,
                           fill=1)
        if type(self.currentMenu) is Action or type(self.currentMenu) is Go:
            self.currentMenu.setVal(val)
        return

    #Draw objects of the current menu
    def draw(self):
        self.disp.text((1, self.top),
                       self.currentMenu.title,
                       font=self.font,
                       fill=1)
        #Populate the interface list with the current menu's items
        try:
            self.interfaces = self.currentMenu.getItems()
        except:
            print('Menu population error')

        if type(self.currentMenu) is Menu:
            self.updateInfo(self.toString())
            for item in self.interfaces:
                if item != None:
                    self.disp.text(
                        (self.column1,
                         self.lines[self.interfaces.index(item)]),
                        self.interfaces[self.interfaces.index(item)].title,
                        font=self.font2,
                        fill=1)
                    if self.interfaces[self.interfaces.index(
                            item)].getVal() != None:
                        self.disp.text(
                            (self.column3,
                             self.lines[self.interfaces.index(item)]),
                            self.interfaces[self.interfaces.index(
                                item)].toString()[2],
                            font=self.font2,
                            fill=0)
                        self.disp.text(
                            (self.column3,
                             self.lines[self.interfaces.index(item)]),
                            self.interfaces[self.interfaces.index(
                                item)].toString()[1],
                            font=self.font2,
                            fill=1)
        #Display scheme for camera shutter speed selection menu
        if type(self.currentMenu) is Option or type(
                self.currentMenu) is Camera:
            #Erase the previous display and write the new display
            self.disp.text((self.column1, self.lines[1]),
                           self.currentMenu.toString()[2],
                           font=self.font4,
                           fill=0)
            self.disp.text((self.column1, self.lines[1]),
                           self.currentMenu.toString()[1],
                           font=self.font4,
                           fill=1)
        #Display scheme for Action menus
        if type(self.currentMenu) is Action:
            #Display info about the current menu functionality
            self.disp.text((self.column1, self.lines[0]),
                           self.currentMenu.getSubtitle(),
                           font=self.font2,
                           fill=1)
            #Erase the previous display and write the new display
            self.disp.text((self.column1, self.lines[2]),
                           self.currentMenu.toString()[2],
                           font=self.font3,
                           fill=0)
            self.disp.text((self.column1, self.lines[2]),
                           self.currentMenu.toString()[1],
                           font=self.font3,
                           fill=1)
            #Display the 'Position' heading
            self.disp.text((self.column2, self.lines[0]),
                           'Position',
                           font=self.font2,
                           fill=1)
            #Erase the previous display and write the new display
            self.disp.text((self.column2, self.lines[2]),
                           str(self.currentMenu.getPosition()[1]),
                           font=self.font3,
                           fill=0)
            self.disp.text((self.column2, self.lines[2]),
                           str(self.currentMenu.getPosition()[0]),
                           font=self.font3,
                           fill=1)
        #Display scheme for Capture menu
        if type(self.currentMenu) is Go:
            #self.updateInfo(self.currentMenu.getVal())
            self.currentMenu.updatePosition()
            #Display 'Shots Remaining' tag
            self.disp.text((self.column1, self.lines[0]),
                           self.currentMenu.getSubtitle(),
                           font=self.font2,
                           fill=1)
            #Display 'Time Remaining'
            self.disp.text((self.column2, self.top),
                           self.currentMenu.getTimeString()[1],
                           font=self.font2,
                           fill=0)
            self.disp.text((self.column2, self.top),
                           self.currentMenu.getTimeString()[0],
                           font=self.font2,
                           fill=1)
            #Erase the previous display and write the new display (Shots Remaining)
            self.disp.text((self.column1, self.lines[2]),
                           self.currentMenu.toString()[2],
                           font=self.font3,
                           fill=0)
            self.disp.text((self.column1, self.lines[2]),
                           self.currentMenu.toString()[1],
                           font=self.font3,
                           fill=1)
            #Display the 'Position' heading
            self.disp.text((self.column2, self.lines[0]),
                           'Position',
                           font=self.font2,
                           fill=1)
            #Erase the previous display and write the new display (xMotor)
            self.disp.text((self.column2, self.lines[1]),
                           'X: ' + str(self.currentMenu.getPosition(0)[1]),
                           font=self.font2,
                           fill=0)
            self.disp.text((self.column2, self.lines[1]),
                           'X: ' + str(self.currentMenu.getPosition(0)[0]),
                           font=self.font2,
                           fill=1)
            #Erase the previous display and write the new display (rMotor)
            self.disp.text((self.column2, self.lines[2]),
                           'R: ' + str(self.currentMenu.getPosition(1)[1]),
                           font=self.font2,
                           fill=0)
            self.disp.text((self.column2, self.lines[2]),
                           'R: ' + str(self.currentMenu.getPosition(1)[0]),
                           font=self.font2,
                           fill=1)
        return

    #Hightlight the menu option indicated by the selector
    def highlight(self):
        if type(self.currentMenu) is Menu:
            try:
                textDim = self.font.getsize(str(
                    self.interfaces[self.selector]))
                self.disp.rectangle(
                    (self.left, self.lines[self.selector] - 1,
                     self.left + textDim[0] + 5,
                     self.lines[self.selector] + textDim[1] + 2),
                    outline=0,
                    fill=1)
                self.disp.text((self.column1, self.lines[self.selector]),
                               self.interfaces[self.selector].toString()[0],
                               font=self.font2,
                               fill=0)
                if self.interfaces[self.selector].getVal() != None:
                    self.disp.text(
                        (self.column3, self.lines[self.selector]),
                        self.interfaces[self.selector].toString()[1],
                        font=self.font2,
                        fill=0)
            except:
                pass
        return

    #Redraw the current menu
    def update(self):
        self.oled.cls()
        self.draw()
        self.highlight()
        self.oled.display()
        return

    #Refresh the display without clearing previous values
    def refresh(self):
        self.draw()
        self.oled.display()
        return

    #Call the update method
    def getMenu(self):
        self.update()
        return

    #Black out the display
    def off(self):
        self.oled.cls()
        self.fan(False)
        self.buttON(False)
        self.xMotor.OFF()
        self.rMotor.OFF()
        return

    #Return object info
    def toString(self):
        return self.currentMenu.toString()

    #Set an object value
    def setVal(self, val):
        self.currentMenu.setVal(val)
        return

    #Get an object value
    def getVal(self):
        return self.currentMenu.getVal()

    #Save option values to file
    def saveDATA(self):
        data = [
            self.totalDisp.getVal(),
            self.incDisp.getVal(),
            self.totalRot.getVal(),
            self.incRot.getVal(),
            self.tVal.getVal(),
            self.nomages.getVal(),
            self.inter.getVal(),
            self.totalTime.getVal(),
            self.xMotor.getPosition(),
            self.rMotor.getPosition()
        ]
        file = open("//home//pi//Control//settings.txt", "w")

        for i in range(0, data.__len__()):
            file.write(str(data[i]))
            file.write(',')

        file.close()
        return

    #Load saved option values from file
    def loadDATA(self):
        try:
            file = open("//home//pi//Control//settings.txt", "r")
            data = file.readlines()
            file.close()

            for line in data:
                vals = line.split(',')
            print(data)

            self.totalDisp.setVal(vals[0])
            self.incDisp.setVal(vals[1])
            self.totalRot.setVal(vals[2])
            self.incRot.setVal(vals[3])
            self.tVal.setVal(vals[4])
            self.nomages.setVal(vals[5])
            self.inter.setVal(vals[6])
            self.totalTime.setVal(vals[7])
            self.xMotor.setPosition(vals[8])
            self.rMotor.setPosition(vals[9])

        except:
            print("Load failed")
        return

    #Select the menu represented by the selector value
    def selectButt(self, channel):
        self.buttON(False)
        self.fan(False)
        try:
            self.currentMenu.isRecent(True)
        except:
            pass
        self.currentMenu = self.interfaces[self.selector]
        if type(self.currentMenu) is Action or type(self.currentMenu) is Go:
            self.buttON(True)
        if type(self.currentMenu) is Action:
            self.fan(True)
        self.selector = 0
        self.calculate()
        self.update()
        self.saveDATA()
        return

    #Increase the menu selector one increment
    def nextButt(self, channel):
        if self.selector < self.interfaces.__len__() - 1:
            self.selector += 1
        else:
            self.selector = 0
        self.update()
        return

    #Decrease the menu selector one increment
    def prevButt(self, channel):
        if self.selector > 0:
            self.selector -= 1
        else:
            self.selector = self.interfaces.__len__() - 1
        self.update()
        return

    #Update all option values to agree with the most recent user setting
    def calculate(self):
        if self.incDisp.isMostRecent() or self.nomages.isMostRecent():
            self.totalDisp.setVal(self.incDisp.getVal() *
                                  self.nomages.getVal())
            self.incDisp.isRecent(False)
            self.nomages.isRecent(False)

        if self.totalDisp.isMostRecent() or self.nomages.isMostRecent():
            self.incDisp.setVal(self.totalDisp.getVal() /
                                self.nomages.getVal())
            self.totalDisp.isRecent(False)
            self.nomages.isRecent(False)

        if self.incRot.isMostRecent() or self.nomages.isMostRecent():
            self.totalRot.setVal(self.incRot.getVal() * self.nomages.getVal())
            self.incRot.isRecent(False)
            self.nomages.isRecent(False)

        if self.totalRot.isMostRecent() or self.nomages.isMostRecent():
            self.incRot.setVal(self.totalRot.getVal() / self.nomages.getVal())
            self.totalRot.isRecent(False)
            self.nomages.isRecent(False)

        if self.totalTime.isMostRecent() or self.inter.isMostRecent():
            self.nomages.setVal(
                (self.totalTime.getVal() * 60) / self.inter.getVal())
            self.totalDisp.setVal(self.nomages.getVal() *
                                  self.incDisp.getVal())
            self.totalRot.setVal(self.nomages.getVal() * self.incRot.getVal())
            self.inter.isRecent(False)
            self.totalTime.isRecent(False)

        if self.inter.isMostRecent() or self.nomages.isMostRecent():
            self.totalTime.setVal(
                (self.inter.getVal() * self.nomages.getVal()) / 60.0)
            self.totalDisp.setVal(self.nomages.getVal() *
                                  self.incDisp.getVal())
            self.totalRot.setVal(self.nomages.getVal() * self.incRot.getVal())
            self.inter.isRecent(False)
            self.nomages.isRecent(False)

        if self.totalTime.isMostRecent() or self.nomages.isMostRecent():
            self.inter.setVal(
                (self.totalTime.getVal() * 60) / self.nomages.getVal())
            self.totalTime.isRecent(False)
            self.nomages.isRecent(False)

        if (self.inter.getVal() - self.tVal.getShutter() - self.motorStepTime *
                self.stepsPerUnit * self.incDisp.getVal()) < -1:
            palm = self.inter.getVal() - self.tVal.getShutter(
            ) - self.motorStepTime * self.stepsPerUnit * self.incDisp.getVal()
            face = self.inter.getVal()
            self.inter.setVal(face - palm)
            self.inter.increment(1)
            print("Interval Updated")

        if (self.inter.getVal() - self.tVal.getShutter() - self.motorStepTime *
                self.stepsPerUnit * self.incDisp.getVal()) < 0:
            self.inter.increment(1)
            print("Interval Updated")

        self.xMotor.pwmHoldSet(self.hold.getVal())
        self.rMotor.pwmHoldSet(self.hold.getVal())
        return

    #Determine what value the encoder should increment
    def decode(self, event):
        with self.lock:
            if type(self.currentMenu) is Menu or type(self.currentMenu) is Go:
                if event == 1:
                    self.nextButt(1)
                elif event == 2:
                    self.prevButt(1)
            elif type(self.currentMenu) is Action or type(
                    self.currentMenu) is Option or type(
                        self.currentMenu) is Camera:
                if event == 1:
                    encoderQueue = 1
                    self.jog(0, encoderQueue)
                elif event == 2:
                    encoderQueue = -1
                    self.jog(0, encoderQueue)
        return

    #Increment some value with the encoder
    def jog(self, channel, val):
        if type(self.currentMenu) is Option or type(
                self.currentMenu) is Camera:
            self.currentMenu.increment(val)
            self.refresh()
        elif type(self.currentMenu) is Action:
            self.currentMenu.jog(val)
            self.refresh()
        return

    #Update the timestamp on the display
    def getTime(self):
        self.timeStamp = time.monotonic()
        hours = int((self.totalTime.getVal() -
                     (self.timeStamp - self.sequenceStartTime) / 60) / 60)
        minutes = int((self.totalTime.getVal() -
                       (self.timeStamp - self.sequenceStartTime) / 60))
        seconds = int((self.totalTime.getVal() * 60 -
                       (self.timeStamp - self.sequenceStartTime)) % 60)
        if hours < 10:
            hourString = '0' + str(hours)
        else:
            hourString = str(hours)
        if minutes < 10:
            minString = '0' + str(minutes)
        else:
            minString = str(minutes)
        if seconds < 10:
            secString = '0' + str(seconds)
        else:
            secString = str(seconds)
        timeString = hourString + ':' + minString + ':' + secString
        self.ready.setTimeString(timeString)
        self.refresh()
        return

    #Trigger what ever action is indicated by the current menu
    def goSTART(self, channel):
        if time.monotonic() - self.lastRun < 2:
            print('DoubleGo')
            return
        if ~self.busy:
            self.exit = False
            self.buttON(False)
            if self.currentMenu == self.preview:
                self.fan(True)
                self.busy = True
                self.xMotor.goTo(self.initX.getVal())
                self.rMotor.goTo(self.initR.getVal())
                self.refresh()
                sleep(1)
                if self.travX.getVal() == 0:
                    self.xThread = stepperThread(1, "Trans-Thread",
                                                 self.xEvent,
                                                 self.totalDisp.getVal(),
                                                 self.incDisp.getVal(),
                                                 self.xMotor, True)
                elif self.travX.getVal() == 1:
                    self.xThread = stepperThread(1, "Trans-Thread",
                                                 self.xEvent,
                                                 -self.totalDisp.getVal(),
                                                 self.incDisp.getVal(),
                                                 self.xMotor, True)
                if self.travR.getVal() == 0:
                    self.rThread = stepperThread(2, "Rot-Thread", self.rEvent,
                                                 self.totalRot.getVal(),
                                                 self.incRot.getVal(),
                                                 self.rMotor, True)
                elif self.travR.getVal() == 1:
                    self.rThread = stepperThread(2, "Rot-Thread", self.rEvent,
                                                 -self.totalRot.getVal(),
                                                 self.incRot.getVal(),
                                                 self.rMotor, True)
                self.xThread.start()
                self.rThread.start()
                while self.xThread.is_alive() or self.rThread.is_alive():
                    self.refresh()
                    sleep(0.01)
                self.buttON(True)
                self.fan(True)
                self.currentMenu.setVal(self.nomages.getVal())
                self.refresh()
                self.busy = False
                self.xMotor.goTo(self.initX.getVal())
                self.rMotor.goTo(self.initR.getVal())
                self.lastRun = time.monotonic()

            elif self.currentMenu == self.ready:
                self.fan(True)
                self.busy = True
                self.xMotor.goTo(self.initX.getVal())
                self.rMotor.goTo(self.initR.getVal())
                self.refresh()
                GPIO.output(self.halfPress, False)
                sleep(1)
                if self.travX.getVal() == 0:
                    self.xThread = stepperThread(1, "Trans-Thread",
                                                 self.xEvent,
                                                 self.totalDisp.getVal(),
                                                 self.incDisp.getVal(),
                                                 self.xMotor, False)
                elif self.travX.getVal() == 1:
                    self.xThread = stepperThread(1, "Trans-Thread",
                                                 self.xEvent,
                                                 -self.totalDisp.getVal(),
                                                 self.incDisp.getVal(),
                                                 self.xMotor, False)
                if self.travR.getVal() == 0:
                    self.rThread = stepperThread(2, "Rot-Thread", self.rEvent,
                                                 self.totalRot.getVal(),
                                                 self.incRot.getVal(),
                                                 self.rMotor, False)
                elif self.travR.getVal() == 1:
                    self.rThread = stepperThread(2, "Rot-Thread", self.rEvent,
                                                 -self.totalRot.getVal(),
                                                 self.incRot.getVal(),
                                                 self.rMotor, False)
                self.sequenceStartTime = time.monotonic()
                self.xThread.start()
                self.rThread.start()
                n = 0  #Shot counter for UI display
                while self.xThread.is_alive() or self.rThread.is_alive():
                    t1 = time.monotonic()
                    n += 1
                    self.captureSequence(n)
                    self.xEvent.set()
                    self.rEvent.set()
                    self.refresh()
                    self.timeStamp = time.monotonic()
                    self.monotomiTimer(t1, self.inter.getVal())
                self.buttON(True)
                self.fan(False)
                self.currentMenu.setVal(self.nomages.getVal())
                self.refresh()
                self.busy = False
                self.xMotor.goTo(self.initX.getVal())
                self.rMotor.goTo(self.initR.getVal())
                self.lastRun = time.monotonic()

            elif self.currentMenu == self.calTrans:
                self.fan(True)
                self.buttON(False)
                self.xMotor.calibrate()
                self.buttON(True)
                self.update()
                self.fan(False)

            elif self.currentMenu == self.calRot:
                self.fan(True)
                self.buttON(False)
                self.rMotor.calibrate()
                self.buttON(True)
                self.update()
                self.fan(False)

            elif self.currentMenu == self.freeMove:
                self.buttON(False)
                self.xMotor.goTo(self.currentMenu.getVal())
                self.buttON(True)
                self.update()

            elif self.currentMenu == self.freeRotate:
                self.buttON(False)
                self.rMotor.goTo(self.currentMenu.getVal())
                self.buttON(True)
                self.update()

            else:
                try:
                    self.currentMenu.isRecent(True)
                except:
                    pass
                self.currentMenu = self.ready
                self.buttON(True)
                self.fan(False)
                self.selector = 0
                self.calculate()
                self.update()
                self.saveDATA()
        else:
            self.exit = True
        return

    #Execute camera capture and update
    def captureSequence(self, shotNumber):
        self.buttON(True)
        self.capture(self.tVal.getShutter())
        self.buttON(False)
        self.updateInfo(self.nomages.getVal() - shotNumber)
        self.refresh()
        return

    #Trigger the camera
    def capture(self, time):
        GPIO.output(self.fullPress, False)
        sleep(time)
        GPIO.output(self.fullPress, True)
        GPIO.output(self.halfPress, True)
        return

    #Time for capture sequence
    def monotomiTimer(self, t1, delay):
        while time.monotonic() - t1 < delay:
            if time.monotonic() - t1 > self.inter.getVal() - 1:
                GPIO.output(self.halfPress, False)
            self.getTime()
            sleep(0.001)
        return
Exemplo n.º 30
0
class Replicape:
    ''' Init '''
    def __init__(self):
        logging.info("Replicape initializing " + version)
        self.config = ConfigParser.ConfigParser()
        self.config.readfp(open('config/default.cfg'))

        # Make a list of steppers
        self.steppers = {}

        # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
        self.steppers["X"] = SMD("GPIO0_27", "GPIO1_29", "GPIO2_4", 0, "X")
        self.steppers["Y"] = SMD("GPIO1_12", "GPIO0_22", "GPIO2_5", 1, "Y")
        self.steppers["Z"] = SMD("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, "Z")
        self.steppers["H"] = SMD("GPIO1_28", "GPIO1_15", "GPIO2_1", 3, "Ext1")
        self.steppers["E"] = SMD("GPIO1_13", "GPIO1_14", "GPIO2_3", 4, "Ext2")

        # Enable the steppers and set the current, steps pr mm and microstepping
        for name, stepper in self.steppers.iteritems():
            stepper.setCurrentValue(
                self.config.getfloat('Steppers', 'current_' + name))
            stepper.setEnabled(
                self.config.getboolean('Steppers', 'enabled_' + name))
            stepper.set_steps_pr_mm(
                self.config.getfloat('Steppers', 'steps_pr_mm_' + name))
            stepper.set_microstepping(
                self.config.getint('Steppers', 'microstepping_' + name))
            stepper.set_decay(0)

# Commit changes for the Steppers
        SMD.commit()

        # Find the path of the thermostors
        path = "/sys/bus/iio/devices/iio:device0/in_voltage"

        # init the 3 thermistors
        self.therm_ext1 = Thermistor(path + "4_raw", "MOSFET Ext 1",
                                     "B57561G0103F000")  # Epcos 10K
        self.therm_hbp = Thermistor(path + "6_raw", "MOSFET HBP",
                                    "B57560G104F")  # Epcos 100K
        self.therm_ext2 = Thermistor(path + "5_raw", "MOSFET Ext 2",
                                     "B57561G0103F000")  # Epcos 10K

        if os.path.exists("/sys/bus/w1/devices/28-000002e34b73/w1_slave"):
            self.cold_end_1 = W1(
                "/sys/bus/w1/devices/28-000002e34b73/w1_slave", "Cold End 1")

        # init the 3 heaters
        self.mosfet_ext1 = Mosfet(3)
        self.mosfet_ext2 = Mosfet(4)
        self.mosfet_hbp = Mosfet(5)

        # Make extruder 1
        self.ext1 = Extruder(self.steppers["E"], self.therm_ext1,
                             self.mosfet_ext1, "Ext1")
        self.ext1.setPvalue(0.1)
        self.ext1.setDvalue(0.3)
        self.ext1.setIvalue(0.0)

        # Make Heated Build platform
        self.hbp = HBP(self.therm_hbp, self.mosfet_hbp)

        # Make extruder 2.
        self.ext2 = Extruder(self.steppers["H"], self.therm_ext2,
                             self.mosfet_ext2, "Ext2")
        self.ext1.setPvalue(0.1)
        self.ext1.setDvalue(0.3)
        self.ext1.setIvalue(0.0)

        self.current_tool = "E"

        # Init the three fans
        self.fan_1 = Fan(1)
        self.fan_2 = Fan(2)
        self.fan_3 = Fan(0)
        self.fans = {0: self.fan_1, 1: self.fan_2, 2: self.fan_3}

        self.fan_1.setPWMFrequency(100)

        # Init the end stops
        self.end_stops = {}
        self.end_stops["Y1"] = EndStop("GPIO2_2", self.steppers, 1, "Y1")
        self.end_stops["X1"] = EndStop("GPIO0_14", self.steppers, 2, "X1")
        self.end_stops["Z1"] = EndStop("GPIO0_30", self.steppers, 3, "Z1")
        self.end_stops["Y2"] = EndStop("GPIO3_21", self.steppers, 4, "Y2")
        self.end_stops["X2"] = EndStop("GPIO0_31", self.steppers, 5, "X2")
        self.end_stops["Z2"] = EndStop("GPIO0_4", self.steppers, 6, "Z2")

        # Make a queue of commands
        self.commands = Queue.Queue(10)

        # Set up USB, this receives messages and pushes them on the queue
        #self.usb = USB(self.commands)
        self.pipe = Pipe(self.commands)
        self.ethernet = Ethernet(self.commands)

        # Init the path planner
        self.movement = "RELATIVE"
        self.feed_rate = 3000.0
        self.current_pos = {"X": 0.0, "Y": 0.0, "Z": 0.0, "E": 0.0, "H": 0.0}
        self.acceleration = 0.3
        Path.axis_config = int(self.config.get('Geometry', 'axis_config'))
        Path.max_speed_x = float(self.config.get('Steppers', 'max_speed_x'))
        Path.max_speed_y = float(self.config.get('Steppers', 'max_speed_y'))
        Path.max_speed_z = float(self.config.get('Steppers', 'max_speed_z'))
        Path.max_speed_e = float(self.config.get('Steppers', 'max_speed_e'))
        Path.max_speed_h = float(self.config.get('Steppers', 'max_speed_h'))

        self.path_planner = Path_planner(self.steppers, self.current_pos)
        self.path_planner.set_acceleration(self.acceleration)

        # Signal everything ready
        logging.info("Replicape ready")
        print "Replicape ready"

    ''' When a new gcode comes in, excute it '''
    def loop(self):
        print "Replicape starting main"
        try:
            while True:
                gcode = Gcode(self.commands.get(), self)
                self._execute(gcode)
                if gcode.prot == "USB":
                    self.usb.send_message(gcode.getAnswer())
                elif gcode.prot == "PIPE":
                    self.pipe.send_message(gcode.getAnswer())
                else:
                    self.ethernet.send_message(gcode.getAnswer())
                self.commands.task_done()
        except Exception as e:
            logging.exception("Ooops: ")

    ''' Execute a G-code '''

    def _execute(self, g):
        if g.code() == "G1":  # Move (G1 X0.1 Y40.2 F3000)
            if g.hasLetter("F"):  # Get the feed rate
                self.feed_rate = float(g.getValueByLetter(
                    "F")) / 60000.0  # Convert from mm/min to SI unit m/s
                g.removeTokenByLetter("F")
            smds = {}  # All steppers
            for i in range(g.numTokens()):  # Run through all tokens
                axis = g.tokenLetter(i)  # Get the axis, X, Y, Z or E
                smds[axis] = float(g.tokenValue(
                    i)) / 1000.0  # Get the value, new position or vector
            if g.hasLetter(
                    "E"
            ) and self.current_tool != "E":  # We are using a different tool, switch..
                smds[self.current_tool] = smds["E"]
                del smds["E"]
            path = Path(smds, self.feed_rate, self.movement,
                        g.is_crc())  # Make a path segment from the axes
            self.path_planner.add_path(
                path
            )  # Add the path. This blocks until the path planner has capacity
            #logging.debug("Moving to: "+' '.join('%s:%s' % i for i in smds.iteritems()))
        elif g.code() == "G21":  # Set units to mm
            self.factor = 1.0
        elif g.code() == "G28":  # Home the steppers
            if g.numTokens() == 0:  # If no token is given, home all
                g.setTokens(["X0", "Y0", "Z0"])
            smds = {}  # All steppers
            for i in range(g.numTokens()):  # Run through all tokens
                axis = g.tokenLetter(i)  # Get the axis, X, Y, Z or E
                smds[axis] = float(
                    g.tokenValue(i))  # Get tha value, new position or vector
            path = Path(smds, self.feed_rate, "ABSOLUTE",
                        False)  # Make a path segment from the axes
            #logging.debug("moving to "+str(smds))
            self.path_planner.add_path(
                path
            )  # Add the path. This blocks until the path planner has capacity
        elif g.code() == "G90":  # Absolute positioning
            self.movement = "ABSOLUTE"
        elif g.code() == "G91":  # Relative positioning
            self.movement = "RELATIVE"
        elif g.code(
        ) == "G92":  # Set the current position of the following steppers
            #self.path_planner.wait_until_done()
            if g.numTokens() == 0:
                logging.debug("Adding all to G92")
                g.setTokens(["X0", "Y0", "Z0", "E0",
                             "H0"])  # If no token is present, do this for all
            #for i in range(g.numTokens()):
            #    axis = g.tokenLetter(i)
            #    val = float(g.tokenValue(i))
            #    self.path_planner.set_pos(axis, val)
            pos = {}  # All steppers
            for i in range(g.numTokens()):  # Run through all tokens
                axis = g.tokenLetter(i)  # Get the axis, X, Y, Z or E
                pos[axis] = float(g.tokenValue(
                    i)) / 1000.0  # Get the value, new position or vector
            logging.debug(pos)
            path = Path(pos, self.feed_rate,
                        "G92")  # Make a path segment from the axes
            self.path_planner.add_path(path)
        elif g.code() == "M17":  # Enable all steppers
            self.path_planner.wait_until_done()
            for name, stepper in self.steppers.iteritems():
                stepper.setEnabled()
            SMD.commit()
        elif g.code() == "M19":  # Reset all steppers
            self.path_planner.wait_until_done()
            for name, stepper in self.steppers.iteritems():
                stepper.reset()
        elif g.code() == "M30":  # Set microstepping (Propietary to Replicape)
            for i in range(g.numTokens()):
                self.steppers[g.tokenLetter(i)].set_microstepping(
                    int(g.tokenValue(i)))
            SMD.commit()
        elif g.code(
        ) == "M31":  # Set stepper current limit (Propietery to Replicape)
            for i in range(g.numTokens()):
                self.steppers[g.tokenLetter(i)].setCurrentValue(
                    float(g.tokenValue(i)))
            SMD.commit()
        elif g.code() == "M84":  # Disable all steppers
            self.path_planner.wait_until_done()
            for name, stepper in self.steppers.iteritems():
                stepper.setDisabled()
            SMD.commit()
        elif g.code() == "M92":  # M92: Set axis_steps_per_unit
            for i in range(g.numTokens()):  # Run through all tokens
                axis = g.tokenLetter(i)  # Get the axis, X, Y, Z or E
                self.steppers[axis].set_steps_pr_mm(float(g.tokenValue(i)))
            SMD.commit()
        elif g.code() == "M101":  # Deprecated
            pass
        elif g.code() == "M103":  # Deprecated
            pass
        elif g.code() == "M104":  # Set extruder temperature
            if g.hasLetter("P"):
                if int(g.getValueByLetter("P")) == 0:
                    self.ext1.setTargetTemperature(
                        float(g.getValueByLetter("S")))
                elif int(g.getValueByLetter("P")) == 1:
                    logging.debug("setting ext 2 temp to " +
                                  str(g.getValueByLetter("S")))
                    self.ext2.setTargetTemperature(
                        float(g.getValueByLetter("S")))
            else:
                logging.debug("setting ext 1 temp to " + str(g.tokenValue(0)))
                self.ext1.setTargetTemperature(float(g.tokenValue(0)))
        elif g.code() == "M105":  # Get Temperature
            answer = "ok T:" + str(self.ext1.getTemperature())
            if hasattr(self, "hbp"):
                answer += " B:" + str(int(self.hbp.getTemperature()))
            if hasattr(self, "ext2"):
                answer += " T1:" + str(int(self.ext2.getTemperature()))
            if hasattr(self, "cold_end_1"):
                answer += " T2:" + str(int(self.cold_end_1.getTemperature()))
            g.setAnswer(answer)
        elif g.code() == "M106":  # Fan on
            if g.hasLetter("P"):
                fan = self.fans[int(g.getValueByLetter("P"))]
                fan.set_value(
                    float(g.getValueByLetter("S")) /
                    255.0)  # According to reprap wiki, the number is 0..255
            else:  # if there is no fan-number present, do it for the first fan
                self.fan_1.set_value(float(g.tokenValue(0)) / 255.0)
        elif g.code() == "M108":  # Deprecated
            pass
        elif g.code() == "M110":  # Reset the line number counter
            Gcode.line_number = 0
        elif g.code() == "M114":
            g.setAnswer("ok C: " +
                        ' '.join('%s:%s' % i
                                 for i in self.current_pos.iteritems()))
        elif g.code() == "M130":  # Set PID P-value, Format (M130 P0 S8.0)
            pass
            #if int(self.tokens[0][1]) == 0:
            #    self.ext1.setPvalue(float(self.tokens[1][1::]))
        elif g.code() == "M131":  # Set PID I-value, Format (M131 P0 S8.0)
            pass
            #if int(self.tokens[0][1]) == 0:
            #    self.p.ext1.setPvalue(float(self.tokens[1][1::]))
        elif g.code() == "M132":  # Set PID D-value, Format (M132 P0 S8.0)
            pass
            #if int(self.tokens[0][1]) == 0:
            #    self.p.ext1.setPvalue(float(self.tokens[1][1::]))
        elif g.code() == "M140":  # Set bed temperature
            self.hbp.setTargetTemperature(float(g.tokenValue(0)))
        elif g.code() == "M141":
            fan = self.fans[int(g.getValueByLetter("P"))]
            fan.setPWMFrequency(int(g.getValueByLetter("F")))
            fan.set_value(float(g.getValueByLetter("S")))
        elif g.code() == "M142":
            self.stat = True
        elif g.code() == "M143":
            self.stat = False
        elif g.code() == "T0":  # Select tool 0
            self.current_tool = "E"
        elif g.code() == "T1":  # select tool 1
            self.current_tool = "H"
        else:
            logging.warning("Unknown command: " + g.message)
Exemplo n.º 31
0
 def setFan(self, pin):
     self.blower = Fan(pin, 100, 0.25, 120)
     return
Exemplo n.º 32
0
class Replicape:
    ''' Init '''
    def __init__(self):
        logging.info("Replicape initializing "+version)
        self.config = ConfigParser.ConfigParser()
        self.config.readfp(open('config/default.cfg'))

        # Make a list of steppers
        self.steppers = {}

        # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
        self.steppers["X"] = SMD("GPIO0_27", "GPIO1_29", "GPIO2_4",  0, "X") 
        self.steppers["Y"] = SMD("GPIO1_12", "GPIO0_22", "GPIO2_5",  1, "Y")  
        self.steppers["Z"] = SMD("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, "Z")  
        self.steppers["H"] = SMD("GPIO1_28", "GPIO1_15", "GPIO2_1",  3, "Ext1")
        self.steppers["E"] = SMD("GPIO1_13", "GPIO1_14", "GPIO2_3",  4, "Ext2")

        # Enable the steppers and set the current, steps pr mm and microstepping  
        for name, stepper in self.steppers.iteritems():
            stepper.setCurrentValue(self.config.getfloat('Steppers', 'current_'+name)) 
            stepper.setEnabled(self.config.getboolean('Steppers', 'enabled_'+name)) 
            stepper.set_steps_pr_mm(self.config.getfloat('Steppers', 'steps_pr_mm_'+name))         
            stepper.set_microstepping(self.config.getint('Steppers', 'microstepping_'+name)) 
            stepper.set_decay(0) 

		# Commit changes for the Steppers
        SMD.commit()

        # Find the path of the thermostors
        path = "/sys/bus/iio/devices/iio:device0/in_voltage"

        # init the 3 thermistors
        self.therm_ext1 = Thermistor(path+"4_raw", "MOSFET Ext 1", "B57561G0103F000") # Epcos 10K
        self.therm_hbp  = Thermistor(path+"6_raw", "MOSFET HBP",   "B57560G104F")	  # Epcos 100K
        self.therm_ext2 = Thermistor(path+"5_raw", "MOSFET Ext 2", "B57561G0103F000") # Epcos 10K

        if os.path.exists("/sys/bus/w1/devices/28-000002e34b73/w1_slave"):
            self.cold_end_1 = W1("/sys/bus/w1/devices/28-000002e34b73/w1_slave", "Cold End 1")
		
        # init the 3 heaters
        self.mosfet_ext1 = Mosfet(3)
        self.mosfet_ext2 = Mosfet(4)
        self.mosfet_hbp  = Mosfet(5)

        # Make extruder 1
        self.ext1 = Extruder(self.steppers["E"], self.therm_ext1, self.mosfet_ext1, "Ext1")
        self.ext1.setPvalue(0.1)
        self.ext1.setDvalue(0.3)     
        self.ext1.setIvalue(0.0)

        # Make Heated Build platform 
        self.hbp = HBP( self.therm_hbp, self.mosfet_hbp)       

        # Make extruder 2.
        self.ext2 = Extruder(self.steppers["H"], self.therm_ext2, self.mosfet_ext2, "Ext2")
        self.ext1.setPvalue(0.1)
        self.ext1.setDvalue(0.3)     
        self.ext1.setIvalue(0.0)

        self.current_tool = "E"

        # Init the three fans
        self.fan_1 = Fan(1)
        self.fan_2 = Fan(2)
        self.fan_3 = Fan(0)
        self.fans = {0: self.fan_1, 1:self.fan_2, 2:self.fan_3 }

        self.fan_1.setPWMFrequency(100)

        # Init the end stops
        self.end_stops = {}
        self.end_stops["Y1"] = EndStop("GPIO2_2", self.steppers, 1, "Y1")
        self.end_stops["X1"] = EndStop("GPIO0_14", self.steppers, 2, "X1")
        self.end_stops["Z1"] = EndStop("GPIO0_30", self.steppers, 3, "Z1")
        self.end_stops["Y2"] = EndStop("GPIO3_21", self.steppers, 4, "Y2")
        self.end_stops["X2"] = EndStop("GPIO0_31", self.steppers, 5, "X2")
        self.end_stops["Z2"] = EndStop("GPIO0_4", self.steppers, 6, "Z2")
        
        # Make a queue of commands
        self.commands = Queue.Queue(10)

        # Set up USB, this receives messages and pushes them on the queue
        #self.usb = USB(self.commands)		
        self.pipe = Pipe(self.commands)
        self.ethernet = Ethernet(self.commands)
        
        # Init the path planner
        self.movement = "RELATIVE"
        self.feed_rate = 3000.0
        self.current_pos = {"X":0.0, "Y":0.0, "Z":0.0, "E":0.0,"H":0.0}
        self.acceleration = 0.3
        Path.axis_config = int(self.config.get('Geometry', 'axis_config'))
        Path.max_speed_x = float(self.config.get('Steppers', 'max_speed_x'))
        Path.max_speed_y = float(self.config.get('Steppers', 'max_speed_y'))
        Path.max_speed_z = float(self.config.get('Steppers', 'max_speed_z'))
        Path.max_speed_e = float(self.config.get('Steppers', 'max_speed_e'))
        Path.max_speed_h = float(self.config.get('Steppers', 'max_speed_h'))

        self.path_planner = Path_planner(self.steppers, self.current_pos)         
        self.path_planner.set_acceleration(self.acceleration) 

        

        # Signal everything ready
        logging.info("Replicape ready")
        print "Replicape ready" 
	
    ''' When a new gcode comes in, excute it '''
    def loop(self):
        print "Replicape starting main"
        try:
            while True:                
                gcode = Gcode(self.commands.get(), self)
                self._execute(gcode)
                if gcode.prot == "USB":
                    self.usb.send_message(gcode.getAnswer())
                elif gcode.prot == "PIPE":
                    self.pipe.send_message(gcode.getAnswer())
                else:
                    self.ethernet.send_message(gcode.getAnswer())
                self.commands.task_done()
        except Exception as e:
            logging.exception("Ooops: ")
		
    ''' Execute a G-code '''
    def _execute(self, g):
        if g.code() == "G1":                                        # Move (G1 X0.1 Y40.2 F3000)                        
            if g.hasLetter("F"):                                    # Get the feed rate                 
                self.feed_rate = float(g.getValueByLetter("F"))/60000.0 # Convert from mm/min to SI unit m/s
                g.removeTokenByLetter("F")
            smds = {}                                               # All steppers 
            for i in range(g.numTokens()):                          # Run through all tokens
                axis = g.tokenLetter(i)                             # Get the axis, X, Y, Z or E
                smds[axis] = float(g.tokenValue(i))/1000.0          # Get the value, new position or vector             
            if g.hasLetter("E") and self.current_tool != "E":       # We are using a different tool, switch..
                smds[self.current_tool] = smds["E"]
                del smds["E"]
            path = Path(smds, self.feed_rate, self.movement, g.is_crc())# Make a path segment from the axes  
            self.path_planner.add_path(path)                        # Add the path. This blocks until the path planner has capacity
            #logging.debug("Moving to: "+' '.join('%s:%s' % i for i in smds.iteritems()))
        elif g.code() == "G21":                                     # Set units to mm
            self.factor = 1.0
        elif g.code() == "G28":                                     # Home the steppers
            if g.numTokens() == 0:                                  # If no token is given, home all
                g.setTokens(["X0", "Y0", "Z0"])                
            smds = {}                                               # All steppers 
            for i in range(g.numTokens()):                          # Run through all tokens
                axis = g.tokenLetter(i)                             # Get the axis, X, Y, Z or E
                smds[axis] = float(g.tokenValue(i))                 # Get tha value, new position or vector             
            path = Path(smds, self.feed_rate, "ABSOLUTE", False)    # Make a path segment from the axes
            #logging.debug("moving to "+str(smds))
            self.path_planner.add_path(path)                        # Add the path. This blocks until the path planner has capacity
        elif g.code() == "G90":                                     # Absolute positioning
            self.movement = "ABSOLUTE"
        elif g.code() == "G91":                                     # Relative positioning 
            self.movement = "RELATIVE"		
        elif g.code() == "G92":                                     # Set the current position of the following steppers
            #self.path_planner.wait_until_done()
            if g.numTokens() == 0:
                logging.debug("Adding all to G92")
                g.setTokens(["X0", "Y0", "Z0", "E0", "H0"])         # If no token is present, do this for all
            #for i in range(g.numTokens()):
            #    axis = g.tokenLetter(i)
            #    val = float(g.tokenValue(i))
            #    self.path_planner.set_pos(axis, val)
            pos = {}                                               # All steppers 
            for i in range(g.numTokens()):                          # Run through all tokens
                axis = g.tokenLetter(i)                             # Get the axis, X, Y, Z or E
                pos[axis] = float(g.tokenValue(i))/1000.0          # Get the value, new position or vector             
            logging.debug(pos)
            path = Path(pos, self.feed_rate, "G92")               # Make a path segment from the axes
            self.path_planner.add_path(path)  
        elif g.code() == "M17":                                     # Enable all steppers
            self.path_planner.wait_until_done()
            for name, stepper in self.steppers.iteritems():
                stepper.setEnabled() 
            SMD.commit()           
        elif g.code() == "M19":                                     # Reset all steppers
            self.path_planner.wait_until_done()
            for name, stepper in self.steppers.iteritems():
                stepper.reset() 
        elif g.code() == "M30":                                     # Set microstepping (Propietary to Replicape)
            for i in range(g.numTokens()):
                self.steppers[g.tokenLetter(i)].set_microstepping(int(g.tokenValue(i)))            
            SMD.commit() 
        elif g.code() == "M31":                                     # Set stepper current limit (Propietery to Replicape)
            for i in range(g.numTokens()):                         
                self.steppers[g.tokenLetter(i)].setCurrentValue(float(g.tokenValue(i)))            
            SMD.commit() 
        elif g.code() == "M84":                                     # Disable all steppers           
            self.path_planner.wait_until_done()
            for name, stepper in self.steppers.iteritems():
            	stepper.setDisabled()
            SMD.commit()           
        elif g.code() == "M92":                                     # M92: Set axis_steps_per_unit
            for i in range(g.numTokens()):                          # Run through all tokens
                axis = g.tokenLetter(i)                             # Get the axis, X, Y, Z or E
                self.steppers[axis].set_steps_pr_mm(float(g.tokenValue(i)))        
            SMD.commit() 
        elif g.code() == "M101":									# Deprecated 
            pass 													
        elif g.code() == "M103":									# Deprecated
            pass 													
        elif g.code() == "M104":                                    # Set extruder temperature
            if g.hasLetter("P"):
                if int(g.getValueByLetter("P")) == 0:
                    self.ext1.setTargetTemperature(float(g.getValueByLetter("S")))
                elif int(g.getValueByLetter("P")) == 1:
                    logging.debug("setting ext 2 temp to "+str(g.getValueByLetter("S")))
                    self.ext2.setTargetTemperature(float(g.getValueByLetter("S")))
            else:
                logging.debug("setting ext 1 temp to "+str(g.tokenValue(0)))
                self.ext1.setTargetTemperature(float(g.tokenValue(0)))
        elif g.code() == "M105":                                    # Get Temperature
            answer = "ok T:"+str(self.ext1.getTemperature())
            if hasattr(self, "hbp"):
                answer += " B:"+str(int(self.hbp.getTemperature()))
            if hasattr(self, "ext2"):
                answer += " T1:"+str(int(self.ext2.getTemperature()))
            if hasattr(self, "cold_end_1"):
                answer += " T2:"+str(int(self.cold_end_1.getTemperature()))         
            g.setAnswer(answer)
        elif g.code() == "M106":                                    # Fan on
            if g.hasLetter("P"):
                fan = self.fans[int(g.getValueByLetter("P"))]
                fan.set_value(float(g.getValueByLetter("S"))/255.0)	# According to reprap wiki, the number is 0..255
            else: # if there is no fan-number present, do it for the first fan
                self.fan_1.set_value(float(g.tokenValue(0))/255.0)	
        elif g.code() == "M108":									# Deprecated
            pass 													
        elif g.code() == "M110":                                    # Reset the line number counter 
            Gcode.line_number = 0       
        elif g.code() == "M114": 
             g.setAnswer("ok C: "+' '.join('%s:%s' % i for i in self.current_pos.iteritems()))
        elif g.code() == "M130":                                    # Set PID P-value, Format (M130 P0 S8.0)
            pass
            #if int(self.tokens[0][1]) == 0:
            #    self.ext1.setPvalue(float(self.tokens[1][1::]))
        elif g.code() == "M131":                                    # Set PID I-value, Format (M131 P0 S8.0) 
            pass
            #if int(self.tokens[0][1]) == 0:
            #    self.p.ext1.setPvalue(float(self.tokens[1][1::]))
        elif g.code() == "M132":                                    # Set PID D-value, Format (M132 P0 S8.0)
            pass
            #if int(self.tokens[0][1]) == 0:
            #    self.p.ext1.setPvalue(float(self.tokens[1][1::]))
        elif g.code() == "M140":                                    # Set bed temperature
            self.hbp.setTargetTemperature(float(g.tokenValue(0)))
        elif g.code() == "M141":
            fan = self.fans[int(g.getValueByLetter("P"))]
            fan.setPWMFrequency(int(g.getValueByLetter("F")))
            fan.set_value(float(g.getValueByLetter("S")))	           
        elif g.code() == "M142":
            self.stat = True 
        elif g.code() == "M143":
            self.stat = False 
        elif g.code() == "T0":                                      # Select tool 0
            self.current_tool = "E"
        elif g.code() == "T1":                                      # select tool 1
            self.current_tool = "H"
        else:
            logging.warning("Unknown command: "+g.message)
Exemplo n.º 33
0
from Fan import Fan

fan1 = Fan("MAX", True, 10, "yellow")

fan2 = Fan("MEDIUM", False, 5, "blue")

print("Fan1")
fan1.print()

print("Fan2")
fan2.print()
Exemplo n.º 34
0
    def __init__(self):
        firmware_version = "1.1.8~Raw Deal"
        logging.info("Redeem initializing " + firmware_version)

        printer = Printer()
        self.printer = printer
        Path.printer = printer

        printer.firmware_version = firmware_version

        # check for config files
        if not os.path.exists("/etc/redeem/default.cfg"):
            logging.error(
                "/etc/redeem/default.cfg does not exist, this file is required for operation"
            )
            sys.exit()  # maybe use something more graceful?

        if not os.path.exists("/etc/redeem/local.cfg"):
            logging.info("/etc/redeem/local.cfg does not exist, Creating one")
            os.mknod("/etc/redeem/local.cfg")

        # Parse the config files.
        printer.config = CascadingConfigParser([
            '/etc/redeem/default.cfg', '/etc/redeem/printer.cfg',
            '/etc/redeem/local.cfg'
        ])

        # Get the revision and loglevel from the Config file
        level = self.printer.config.getint('System', 'loglevel')
        if level > 0:
            logging.getLogger().setLevel(level)

        # Set up additional logging, if present:
        if self.printer.config.getboolean('System', 'log_to_file'):
            logfile = self.printer.config.get('System', 'logfile')
            formatter = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
            printer.redeem_logging_handler = logging.handlers.RotatingFileHandler(
                logfile, maxBytes=2 * 1024 * 1024)
            printer.redeem_logging_handler.setFormatter(
                logging.Formatter(formatter))
            printer.redeem_logging_handler.setLevel(level)
            logging.getLogger().addHandler(printer.redeem_logging_handler)
            logging.info("-- Logfile configured --")

        # Find out which capes are connected
        self.printer.config.parse_capes()
        self.revision = self.printer.config.replicape_revision
        if self.revision:
            logging.info("Found Replicape rev. " + self.revision)
        else:
            logging.warning("Oh no! No Replicape present!")
            self.revision = "00B3"
        # We set it to 5 axis by default
        Path.NUM_AXES = 5
        if self.printer.config.reach_revision:
            logging.info("Found Reach rev. " +
                         self.printer.config.reach_revision)
        if self.printer.config.reach_revision == "00A0":
            Path.NUM_AXES = 8
        elif self.printer.config.reach_revision == "00B0":
            Path.NUM_AXES = 7

        if self.revision in ["00A4", "0A4A", "00A3"]:
            PWM.set_frequency(100)
        elif self.revision in ["00B1", "00B2", "00B3"]:
            PWM.set_frequency(1000)

        # Test the alarm framework
        Alarm.printer = self.printer
        Alarm.executor = AlarmExecutor()
        alarm = Alarm(Alarm.ALARM_TEST, "Alarm framework operational")

        # Init the Watchdog timer
        printer.watchdog = Watchdog()

        # Enable PWM and steppers
        printer.enable = Enable("P9_41")
        printer.enable.set_disabled()

        # Init the Paths
        Path.axis_config = printer.config.getint('Geometry', 'axis_config')

        # Init the end stops
        EndStop.inputdev = self.printer.config.get("Endstops", "inputdev")
        # Set up key listener
        Key_pin.listener = Key_pin_listener(EndStop.inputdev)

        for es in ["Z2", "Y2", "X2", "Z1", "Y1",
                   "X1"]:  # Order matches end stop inversion mask in Firmware
            pin = self.printer.config.get("Endstops", "pin_" + es)
            keycode = self.printer.config.getint("Endstops", "keycode_" + es)
            invert = self.printer.config.getboolean("Endstops", "invert_" + es)
            self.printer.end_stops[es] = EndStop(printer, pin, keycode, es,
                                                 invert)
            self.printer.end_stops[es].stops = self.printer.config.get(
                'Endstops', 'end_stop_' + es + '_stops')

        # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
        if self.revision == "00A3":
            printer.steppers["X"] = Stepper_00A3("GPIO0_27", "GPIO1_29",
                                                 "GPIO2_4", 0, "X")
            printer.steppers["Y"] = Stepper_00A3("GPIO1_12", "GPIO0_22",
                                                 "GPIO2_5", 1, "Y")
            printer.steppers["Z"] = Stepper_00A3("GPIO0_23", "GPIO0_26",
                                                 "GPIO0_15", 2, "Z")
            printer.steppers["E"] = Stepper_00A3("GPIO1_28", "GPIO1_15",
                                                 "GPIO2_1", 3, "E")
            printer.steppers["H"] = Stepper_00A3("GPIO1_13", "GPIO1_14",
                                                 "GPIO2_3", 4, "H")
        elif self.revision == "00B1":
            printer.steppers["X"] = Stepper_00B1("GPIO0_27", "GPIO1_29",
                                                 "GPIO2_4", 11, 0, "X")
            printer.steppers["Y"] = Stepper_00B1("GPIO1_12", "GPIO0_22",
                                                 "GPIO2_5", 12, 1, "Y")
            printer.steppers["Z"] = Stepper_00B1("GPIO0_23", "GPIO0_26",
                                                 "GPIO0_15", 13, 2, "Z")
            printer.steppers["E"] = Stepper_00B1("GPIO1_28", "GPIO1_15",
                                                 "GPIO2_1", 14, 3, "E")
            printer.steppers["H"] = Stepper_00B1("GPIO1_13", "GPIO1_14",
                                                 "GPIO2_3", 15, 4, "H")
        elif self.revision == "00B2":
            printer.steppers["X"] = Stepper_00B2("GPIO0_27", "GPIO1_29",
                                                 "GPIO2_4", 11, 0, "X")
            printer.steppers["Y"] = Stepper_00B2("GPIO1_12", "GPIO0_22",
                                                 "GPIO2_5", 12, 1, "Y")
            printer.steppers["Z"] = Stepper_00B2("GPIO0_23", "GPIO0_26",
                                                 "GPIO0_15", 13, 2, "Z")
            printer.steppers["E"] = Stepper_00B2("GPIO1_28", "GPIO1_15",
                                                 "GPIO2_1", 14, 3, "E")
            printer.steppers["H"] = Stepper_00B2("GPIO1_13", "GPIO1_14",
                                                 "GPIO2_3", 15, 4, "H")
        elif self.revision == "00B3":
            printer.steppers["X"] = Stepper_00B3("GPIO0_27", "GPIO1_29", 90,
                                                 11, 0, "X")
            printer.steppers["Y"] = Stepper_00B3("GPIO1_12", "GPIO0_22", 91,
                                                 12, 1, "Y")
            printer.steppers["Z"] = Stepper_00B3("GPIO0_23", "GPIO0_26", 92,
                                                 13, 2, "Z")
            printer.steppers["E"] = Stepper_00B3("GPIO1_28", "GPIO1_15", 93,
                                                 14, 3, "E")
            printer.steppers["H"] = Stepper_00B3("GPIO1_13", "GPIO1_14", 94,
                                                 15, 4, "H")
        elif self.revision in ["00A4", "0A4A"]:
            printer.steppers["X"] = Stepper_00A4("GPIO0_27", "GPIO1_29",
                                                 "GPIO2_4", 0, 0, "X")
            printer.steppers["Y"] = Stepper_00A4("GPIO1_12", "GPIO0_22",
                                                 "GPIO2_5", 1, 1, "Y")
            printer.steppers["Z"] = Stepper_00A4("GPIO0_23", "GPIO0_26",
                                                 "GPIO0_15", 2, 2, "Z")
            printer.steppers["E"] = Stepper_00A4("GPIO1_28", "GPIO1_15",
                                                 "GPIO2_1", 3, 3, "E")
            printer.steppers["H"] = Stepper_00A4("GPIO1_13", "GPIO1_14",
                                                 "GPIO2_3", 4, 4, "H")
        # Init Reach steppers, if present.
        if printer.config.reach_revision == "00A0":
            printer.steppers["A"] = Stepper_reach_00A4("GPIO2_2", "GPIO1_18",
                                                       "GPIO0_14", 5, 5, "A")
            printer.steppers["B"] = Stepper_reach_00A4("GPIO1_16", "GPIO0_5",
                                                       "GPIO0_14", 6, 6, "B")
            printer.steppers["C"] = Stepper_reach_00A4("GPIO0_3", "GPIO3_19",
                                                       "GPIO0_14", 7, 7, "C")
        elif printer.config.reach_revision == "00B0":
            printer.steppers["A"] = Stepper_reach_00B0("GPIO1_16", "GPIO0_5",
                                                       "GPIO0_3", 5, 5, "A")
            printer.steppers["B"] = Stepper_reach_00B0("GPIO2_2", "GPIO0_14",
                                                       "GPIO0_3", 6, 6, "B")

        # Enable the steppers and set the current, steps pr mm and
        # microstepping
        for name, stepper in self.printer.steppers.iteritems():
            stepper.in_use = printer.config.getboolean('Steppers',
                                                       'in_use_' + name)
            stepper.direction = printer.config.getint('Steppers',
                                                      'direction_' + name)
            stepper.has_endstop = printer.config.getboolean(
                'Endstops', 'has_' + name)
            stepper.set_current_value(
                printer.config.getfloat('Steppers', 'current_' + name))
            stepper.set_steps_pr_mm(
                printer.config.getfloat('Steppers', 'steps_pr_mm_' + name))
            stepper.set_microstepping(
                printer.config.getint('Steppers', 'microstepping_' + name))
            stepper.set_decay(
                printer.config.getint("Steppers", "slow_decay_" + name))
            # Add soft end stops
            Path.soft_min[Path.axis_to_index(name)] = printer.config.getfloat(
                'Endstops', 'soft_end_stop_min_' + name)
            Path.soft_max[Path.axis_to_index(name)] = printer.config.getfloat(
                'Endstops', 'soft_end_stop_max_' + name)
            slave = printer.config.get('Steppers', 'slave_' + name)
            if slave:
                Path.add_slave(name, slave)
                logging.debug("Axis " + name + " has slave " + slave)

        # Commit changes for the Steppers
        #Stepper.commit()

        Stepper.printer = printer

        # Delta printer setup
        if Path.axis_config == Path.AXIS_CONFIG_DELTA:
            opts = [
                "Hez", "L", "r", "Ae", "Be", "Ce", "A_radial", "B_radial",
                "C_radial", "A_tangential", "B_tangential", "C_tangential"
            ]
            for opt in opts:
                Delta.__dict__[opt] = printer.config.getfloat('Delta', opt)

            Delta.recalculate()

        # Discover and add all DS18B20 cold ends.
        import glob
        paths = glob.glob("/sys/bus/w1/devices/28-*/w1_slave")
        logging.debug("Found cold ends: " + str(paths))
        for i, path in enumerate(paths):
            self.printer.cold_ends.append(ColdEnd(path, "ds18b20-" + str(i)))
            logging.info("Found Cold end " + str(i) + " on " + path)

        # Make Mosfets, thermistors and extruders
        heaters = ["E", "H", "HBP"]
        if self.printer.config.reach_revision:
            heaters.extend(["A", "B", "C"])
        for e in heaters:
            # Mosfets
            channel = self.printer.config.getint("Heaters", "mosfet_" + e)
            self.printer.mosfets[e] = Mosfet(channel)
            # Thermistors
            adc = self.printer.config.get("Heaters", "path_adc_" + e)
            chart = self.printer.config.get("Heaters", "temp_chart_" + e)
            resistance = self.printer.config.getfloat("Heaters",
                                                      "resistance_" + e)
            self.printer.thermistors[e] = Thermistor(adc, "MOSFET " + e, chart,
                                                     resistance)
            self.printer.thermistors[e].printer = printer

            # Extruders
            onoff = self.printer.config.getboolean('Heaters', 'onoff_' + e)
            prefix = self.printer.config.get('Heaters', 'prefix_' + e)
            if e != "HBP":
                self.printer.heaters[e] = Extruder(self.printer.steppers[e],
                                                   self.printer.thermistors[e],
                                                   self.printer.mosfets[e], e,
                                                   onoff)
            else:
                self.printer.heaters[e] = HBP(self.printer.thermistors[e],
                                              self.printer.mosfets[e], onoff)
            self.printer.heaters[e].prefix = prefix
            self.printer.heaters[e].P = self.printer.config.getfloat(
                'Heaters', 'pid_p_' + e)
            self.printer.heaters[e].I = self.printer.config.getfloat(
                'Heaters', 'pid_i_' + e)
            self.printer.heaters[e].D = self.printer.config.getfloat(
                'Heaters', 'pid_d_' + e)

            # Min/max settings
            self.printer.heaters[e].min_temp = self.printer.config.getfloat(
                'Heaters', 'min_temp_' + e)
            self.printer.heaters[e].max_temp = self.printer.config.getfloat(
                'Heaters', 'max_temp_' + e)
            self.printer.heaters[
                e].max_temp_rise = self.printer.config.getfloat(
                    'Heaters', 'max_rise_temp_' + e)
            self.printer.heaters[
                e].max_temp_fall = self.printer.config.getfloat(
                    'Heaters', 'max_fall_temp_' + e)

        # Init the three fans. Argument is PWM channel number
        self.printer.fans = []
        if self.revision == "00A3":
            self.printer.fans.append(Fan(0))
            self.printer.fans.append(Fan(1))
            self.printer.fans.append(Fan(2))
        elif self.revision == "0A4A":
            self.printer.fans.append(Fan(8))
            self.printer.fans.append(Fan(9))
            self.printer.fans.append(Fan(10))
        elif self.revision in ["00B1", "00B2", "00B3"]:
            self.printer.fans.append(Fan(7))
            self.printer.fans.append(Fan(8))
            self.printer.fans.append(Fan(9))
            self.printer.fans.append(Fan(10))
        if printer.config.reach_revision == "00A0":
            self.printer.fans.append(Fan(14))
            self.printer.fans.append(Fan(15))
            self.printer.fans.append(Fan(7))

        # Disable all fans
        for f in self.printer.fans:
            f.set_value(0)

        # Init the servos
        printer.servos = []
        servo_nr = 0
        while (printer.config.has_option("Servos", "servo_" + str(servo_nr) +
                                         "_enable")):
            if printer.config.getboolean("Servos",
                                         "servo_" + str(servo_nr) + "_enable"):
                channel = printer.config.get(
                    "Servos", "servo_" + str(servo_nr) + "_channel")
                pulse_min = printer.config.getfloat(
                    "Servos", "servo_" + str(servo_nr) + "_pulse_min")
                pulse_max = printer.config.getfloat(
                    "Servos", "servo_" + str(servo_nr) + "_pulse_max")
                angle_min = printer.config.getfloat(
                    "Servos", "servo_" + str(servo_nr) + "_angle_min")
                angle_max = printer.config.getfloat(
                    "Servos", "servo_" + str(servo_nr) + "_angle_max")
                angle_init = printer.config.getfloat(
                    "Servos", "servo_" + str(servo_nr) + "_angle_init")
                s = Servo(channel, pulse_min, pulse_max, angle_min, angle_max,
                          angle_init)
                printer.servos.append(s)
                logging.info("Added servo " + str(servo_nr))
            servo_nr += 1

        # Connect thermitors to fans
        for t, therm in self.printer.heaters.iteritems():
            for f, fan in enumerate(self.printer.fans):
                if not self.printer.config.has_option(
                        'Cold-ends', "connect-therm-{}-fan-{}".format(t, f)):
                    continue
                if printer.config.getboolean(
                        'Cold-ends', "connect-therm-{}-fan-{}".format(t, f)):
                    c = Cooler(therm, fan, "Cooler-{}-{}".format(t, f),
                               True)  # Use ON/OFF on these.
                    c.ok_range = 4
                    opt_temp = "therm-{}-fan-{}-target_temp".format(t, f)
                    if printer.config.has_option('Cold-ends', opt_temp):
                        target_temp = printer.config.getfloat(
                            'Cold-ends', opt_temp)
                    else:
                        target_temp = 60
                    c.set_target_temperature(target_temp)
                    c.enable()
                    printer.coolers.append(c)
                    logging.info("Cooler connects therm {} with fan {}".format(
                        t, f))

        # Connect fans to M106
        printer.controlled_fans = []
        for i, fan in enumerate(self.printer.fans):
            if not self.printer.config.has_option(
                    'Cold-ends', "add-fan-{}-to-M106".format(i)):
                continue
            if self.printer.config.getboolean('Cold-ends',
                                              "add-fan-{}-to-M106".format(i)):
                printer.controlled_fans.append(self.printer.fans[i])
                logging.info("Added fan {} to M106/M107".format(i))

        # Connect the colds to fans
        for ce, cold_end in enumerate(self.printer.cold_ends):
            for f, fan in enumerate(self.printer.fans):
                option = "connect-ds18b20-{}-fan-{}".format(ce, f)
                if self.printer.config.has_option('Cold-ends', option):
                    if self.printer.config.getboolean('Cold-ends', option):
                        c = Cooler(cold_end, fan,
                                   "Cooler-ds18b20-{}-{}".format(ce, f), False)
                        c.ok_range = 4
                        opt_temp = "cooler_{}_target_temp".format(ce)
                        if printer.config.has_option('Cold-ends', opt_temp):
                            target_temp = printer.config.getfloat(
                                'Cold-ends', opt_temp)
                        else:
                            target_temp = 60
                        c.set_target_temperature(target_temp)
                        c.enable()
                        printer.coolers.append(c)
                        logging.info(
                            "Cooler connects temp sensor ds18b20 {} with fan {}"
                            .format(ce, f))

        # Init roatray encs.
        printer.filament_sensors = []

        # Init rotary encoders
        printer.rotary_encoders = []
        for ex in ["E", "H", "A", "B", "C"]:
            if not printer.config.has_option('Rotary-encoders',
                                             "enable-{}".format(ex)):
                continue
            if printer.config.getboolean("Rotary-encoders",
                                         "enable-{}".format(ex)):
                logging.debug("Rotary encoder {} enabled".format(ex))
                event = printer.config.get("Rotary-encoders",
                                           "event-{}".format(ex))
                cpr = printer.config.getint("Rotary-encoders",
                                            "cpr-{}".format(ex))
                diameter = printer.config.getfloat("Rotary-encoders",
                                                   "diameter-{}".format(ex))
                r = RotaryEncoder(event, cpr, diameter)
                printer.rotary_encoders.append(r)
                # Append as Filament Sensor
                ext_nr = Path.axis_to_index(ex) - 3
                sensor = FilamentSensor(ex, r, ext_nr, printer)
                alarm_level = printer.config.getfloat(
                    "Filament-sensors", "alarm-level-{}".format(ex))
                logging.debug("Alarm level" + str(alarm_level))
                sensor.alarm_level = alarm_level
                printer.filament_sensors.append(sensor)

        # Make a queue of commands
        self.printer.commands = JoinableQueue(10)

        # Make a queue of commands that should not be buffered
        self.printer.sync_commands = JoinableQueue()
        self.printer.unbuffered_commands = JoinableQueue(10)

        # Bed compensation matrix
        Path.matrix_bed_comp = printer.load_bed_compensation_matrix()
        Path.matrix_bed_comp_inv = np.linalg.inv(Path.matrix_bed_comp)
        logging.debug("Loaded bed compensation matrix: \n" +
                      str(Path.matrix_bed_comp))

        for axis in printer.steppers.keys():
            i = Path.axis_to_index(axis)
            Path.max_speeds[i] = printer.config.getfloat(
                'Planner', 'max_speed_' + axis.lower())
            Path.min_speeds[i] = printer.config.getfloat(
                'Planner', 'min_speed_' + axis.lower())
            Path.jerks[i] = printer.config.getfloat('Planner',
                                                    'max_jerk_' + axis.lower())
            Path.home_speed[i] = printer.config.getfloat(
                'Homing', 'home_speed_' + axis.lower())
            Path.home_backoff_speed[i] = printer.config.getfloat(
                'Homing', 'home_backoff_speed_' + axis.lower())
            Path.home_backoff_offset[i] = printer.config.getfloat(
                'Homing', 'home_backoff_offset_' + axis.lower())
            Path.steps_pr_meter[i] = printer.steppers[axis].get_steps_pr_meter(
            )
            Path.backlash_compensation[i] = printer.config.getfloat(
                'Steppers', 'backlash_' + axis.lower())

        dirname = os.path.dirname(os.path.realpath(__file__))

        # Create the firmware compiler
        pru_firmware = PruFirmware(dirname + "/firmware/firmware_runtime.p",
                                   dirname + "/firmware/firmware_runtime.bin",
                                   dirname + "/firmware/firmware_endstops.p",
                                   dirname + "/firmware/firmware_endstops.bin",
                                   self.printer, "/usr/bin/pasm")

        printer.move_cache_size = printer.config.getfloat(
            'Planner', 'move_cache_size')
        printer.print_move_buffer_wait = printer.config.getfloat(
            'Planner', 'print_move_buffer_wait')
        printer.min_buffered_move_time = printer.config.getfloat(
            'Planner', 'min_buffered_move_time')
        printer.max_buffered_move_time = printer.config.getfloat(
            'Planner', 'max_buffered_move_time')

        self.printer.processor = GCodeProcessor(self.printer)
        self.printer.plugins = PluginsController(self.printer)

        # Path planner
        travel_default = False
        center_default = False
        home_default = False

        # Setting acceleration before PathPlanner init
        for axis in printer.steppers.keys():
            Path.acceleration[Path.axis_to_index(
                axis)] = printer.config.getfloat(
                    'Planner', 'acceleration_' + axis.lower())

        self.printer.path_planner = PathPlanner(self.printer, pru_firmware)
        for axis in printer.steppers.keys():
            i = Path.axis_to_index(axis)

            # Sometimes soft_end_stop aren't defined to be at the exact hardware boundary.
            # Adding 100mm for searching buffer.
            if printer.config.has_option('Geometry', 'travel_' + axis.lower()):
                printer.path_planner.travel_length[
                    axis] = printer.config.getfloat('Geometry',
                                                    'travel_' + axis.lower())
            else:
                printer.path_planner.travel_length[axis] = (
                    Path.soft_max[i] - Path.soft_min[i]) + .1
                if axis in ['X', 'Y', 'Z']:
                    travel_default = True

            if printer.config.has_option('Geometry', 'offset_' + axis.lower()):
                printer.path_planner.center_offset[
                    axis] = printer.config.getfloat('Geometry',
                                                    'offset_' + axis.lower())
            else:
                printer.path_planner.center_offset[axis] = (
                    Path.soft_min[i]
                    if Path.home_speed[i] > 0 else Path.soft_max[i])
                if axis in ['X', 'Y', 'Z']:
                    center_default = True

            if printer.config.has_option('Homing', 'home_' + axis.lower()):
                printer.path_planner.home_pos[axis] = printer.config.getfloat(
                    'Homing', 'home_' + axis.lower())
            else:
                printer.path_planner.home_pos[
                    axis] = printer.path_planner.center_offset[axis]
                if axis in ['X', 'Y', 'Z']:
                    home_default = True

        if Path.axis_config == Path.AXIS_CONFIG_DELTA:
            if travel_default:
                logging.warning(
                    "Axis travel (travel_*) set by soft limits, manual setup is recommended for a delta"
                )
            if center_default:
                logging.warning(
                    "Axis offsets (offset_*) set by soft limits, manual setup is recommended for a delta"
                )
            if home_default:
                logging.warning(
                    "Home position (home_*) set by soft limits or offset_*")
                logging.info("Home position will be recalculated...")

                # convert home_pos to effector space
                Az = printer.path_planner.home_pos['X']
                Bz = printer.path_planner.home_pos['Y']
                Cz = printer.path_planner.home_pos['Z']

                z_offset = Delta.vertical_offset(Az, Bz, Cz)  # vertical offset
                xyz = Delta.forward_kinematics2(Az, Bz,
                                                Cz)  # effector position

                # The default home_pos, provided above, is based on effector space
                # coordinates for carriage positions. We need to transform these to
                # get where the effector actually is.
                xyz[2] += z_offset
                for i, a in enumerate(['X', 'Y', 'Z']):
                    printer.path_planner.home_pos[a] = xyz[i]

                logging.info("Home position = %s" %
                             str(printer.path_planner.home_pos))

        # Enable Stepper timeout
        timeout = printer.config.getint('Steppers', 'timeout_seconds')
        printer.swd = StepperWatchdog(printer, timeout)
        if printer.config.getboolean('Steppers', 'use_timeout'):
            printer.swd.start()

        # Set up communication channels
        printer.comms["USB"] = USB(self.printer)
        printer.comms["Eth"] = Ethernet(self.printer)

        if Pipe.check_tty0tty() or Pipe.check_socat():
            printer.comms["octoprint"] = Pipe(printer, "octoprint")
            printer.comms["toggle"] = Pipe(printer, "toggle")
            printer.comms["testing"] = Pipe(printer, "testing")
            printer.comms["testing_noret"] = Pipe(printer, "testing_noret")
            # Does not send "ok"
            printer.comms["testing_noret"].send_response = False
        else:
            logging.warning(
                "Neither tty0tty or socat is installed! No virtual tty pipes enabled"
            )
Exemplo n.º 35
0
    def __init__(self):
        """ Init """
        logging.info("Redeem initializing " + version)

        printer = Printer()
        self.printer = printer

        # check for config files
        if not os.path.exists("/etc/redeem/default.cfg"):
            logging.error("/etc/redeem/default.cfg does not exist, this file is required for operation")
            sys.exit() # maybe use something more graceful?

        # Parse the config files.
        printer.config = CascadingConfigParser(
            ['/etc/redeem/default.cfg', '/etc/redeem/printer.cfg',
             '/etc/redeem/local.cfg'])

        # Find out which capes are connected
        self.printer.config.parse_capes()
        self.revision = self.printer.config.replicape_revision
        if self.revision:
            logging.info("Found Replicape rev. " + self.revision)
            Path.set_axes(5)
        else:
            logging.warning("Oh no! No Replicape present!")
            self.revision = "0A4A"
            # We set it to 5 axis by default
            Path.set_axes(5)
        if self.printer.config.reach_revision:
            Path.set_axes(8)
            logging.info("Found Reach rev. "+self.printer.config.reach_revision)

        # Get the revision and loglevel from the Config file
        level = self.printer.config.getint('System', 'loglevel')
        if level > 0:
            logging.getLogger().setLevel(level)

        if self.revision in ["00A4", "0A4A", "00A3"]:
            PWM.set_frequency(100)
        elif self.revision in ["00B1", "00B2"]:
            PWM.set_frequency(1000)

        # Init the Paths
        Path.axis_config = printer.config.getint('Geometry', 'axis_config')

        # Init the end stops
        EndStop.callback = self.end_stop_hit
        EndStop.inputdev = self.printer.config.get("Endstops", "inputdev")
        for es in ["X1", "X2", "Y1", "Y2", "Z1", "Z2"]:
            pin = self.printer.config.get("Endstops", "pin_"+es)
            keycode = self.printer.config.getint("Endstops", "keycode_"+es)
            invert = self.printer.config.getboolean("Endstops", "invert_"+es)
            self.printer.end_stops[es] = EndStop(pin, keycode, es, invert)

        # Backwards compatibility with A3
        if self.revision == "00A3":
            # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
            printer.steppers["X"] = Stepper_00A3("GPIO0_27", "GPIO1_29", "GPIO2_4" , 0, "X", 0, 0)
            printer.steppers["Y"] = Stepper_00A3("GPIO1_12", "GPIO0_22", "GPIO2_5" , 1, "Y", 1, 1)
            printer.steppers["Z"] = Stepper_00A3("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, "Z", 2, 2)
            printer.steppers["E"] = Stepper_00A3("GPIO1_28", "GPIO1_15", "GPIO2_1" , 3, "E", 3, 3)
            printer.steppers["H"] = Stepper_00A3("GPIO1_13", "GPIO1_14", "GPIO2_3" , 4, "H", 4, 4)
        elif self.revision == "00B1":
            # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
            printer.steppers["X"] = Stepper_00B1("GPIO0_27", "GPIO1_29", "GPIO2_4" , 11, 0, "X", 0, 0)
            printer.steppers["Y"] = Stepper_00B1("GPIO1_12", "GPIO0_22", "GPIO2_5" , 12, 1, "Y", 1, 1)
            printer.steppers["Z"] = Stepper_00B1("GPIO0_23", "GPIO0_26", "GPIO0_15", 13, 2, "Z", 2, 2)
            printer.steppers["E"] = Stepper_00B1("GPIO1_28", "GPIO1_15", "GPIO2_1" , 14, 3, "E", 3, 3)
            printer.steppers["H"] = Stepper_00B1("GPIO1_13", "GPIO1_14", "GPIO2_3" , 15, 4, "H", 4, 4)
        elif self.revision == "00B2":
            # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
            printer.steppers["X"] = Stepper_00B2("GPIO0_27", "GPIO1_29", "GPIO2_4" , 11, 0, "X", 0, 0)
            printer.steppers["Y"] = Stepper_00B2("GPIO1_12", "GPIO0_22", "GPIO2_5" , 12, 1, "Y", 1, 1)
            printer.steppers["Z"] = Stepper_00B2("GPIO0_23", "GPIO0_26", "GPIO0_15", 13, 2, "Z", 2, 2)
            printer.steppers["E"] = Stepper_00B2("GPIO1_28", "GPIO1_15", "GPIO2_1" , 14, 3, "E", 3, 3)
            printer.steppers["H"] = Stepper_00B2("GPIO1_13", "GPIO1_14", "GPIO2_3" , 15, 4, "H", 4, 4)
        else:
            # Init the 5 Stepper motors (step, dir, fault, DAC channel, name)
            printer.steppers["X"] = Stepper_00A4("GPIO0_27", "GPIO1_29", "GPIO2_4" , 0, 0, "X", 0, 0)
            printer.steppers["Y"] = Stepper_00A4("GPIO1_12", "GPIO0_22", "GPIO2_5" , 1, 1, "Y", 1, 1)
            printer.steppers["Z"] = Stepper_00A4("GPIO0_23", "GPIO0_26", "GPIO0_15", 2, 2, "Z", 2, 2)
            printer.steppers["E"] = Stepper_00A4("GPIO1_28", "GPIO1_15", "GPIO2_1" , 3, 3, "E", 3, 3)
            printer.steppers["H"] = Stepper_00A4("GPIO1_13", "GPIO1_14", "GPIO2_3" , 4, 4, "H", 4, 4)

            if printer.config.reach_revision:
                printer.steppers["A"] = Stepper_00A4("GPIO2_2" , "GPIO1_18", "GPIO0_14", 5, 5, "A", 5, 5)
                printer.steppers["B"] = Stepper_00A4("GPIO1_14", "GPIO0_5" , "GPIO0_14", 6, 6, "B", 6, 6)
                printer.steppers["C"] = Stepper_00A4("GPIO0_3" , "GPIO3_19", "GPIO0_14", 7, 7, "C", 7, 7)


        # Enable the steppers and set the current, steps pr mm and
        # microstepping
        for name, stepper in self.printer.steppers.iteritems():
            stepper.in_use = printer.config.getboolean('Steppers', 'in_use_' + name)
            stepper.direction = printer.config.getint('Steppers', 'direction_' + name)
            stepper.has_endstop = printer.config.getboolean('Endstops', 'has_' + name)
            stepper.set_current_value(printer.config.getfloat('Steppers', 'current_' + name))
            stepper.set_steps_pr_mm(printer.config.getfloat('Steppers', 'steps_pr_mm_' + name))
            stepper.set_microstepping(printer.config.getint('Steppers', 'microstepping_' + name))
            stepper.set_decay(printer.config.getboolean("Steppers", "slow_decay_" + name))
            # Add soft end stops
            Path.soft_min[Path.axis_to_index(name)] = printer.config.getfloat('Endstops', 'soft_end_stop_min_' + name)
            Path.soft_max[Path.axis_to_index(name)] = printer.config.getfloat('Endstops', 'soft_end_stop_max_' + name)

        # Commit changes for the Steppers
        #Stepper.commit()
        Stepper.printer = printer

        # Delta printer setup
        if Path.axis_config == Path.AXIS_CONFIG_DELTA:
            opts = ["Hez", "L", "r", "Ae", "Be", "Ce", "A_radial", "B_radial", "C_radial", "A_tangential", "B_tangential", "C_tangential" ]
            for opt in opts:
                Delta.__dict__[opt] = printer.config.getfloat('Delta', opt)

            Delta.recalculate()

        # Discover and add all DS18B20 cold ends.
        import glob
        paths = glob.glob("/sys/bus/w1/devices/28-*/w1_slave")
        logging.debug("Found cold ends: "+str(paths))
        for i, path in enumerate(paths):
            self.printer.cold_ends.append(ColdEnd(path, "ds18b20-"+str(i)))
            logging.info("Found Cold end "+str(i)+" on " + path)

        # Make Mosfets, thermistors and extruders
        heaters = ["E", "H", "HBP"]
        if self.printer.config.reach_revision:
            heaters.extend(["A", "B", "C"])
        for e in heaters:
            # Mosfets
            channel = self.printer.config.getint("Heaters", "mosfet_"+e)
            self.printer.mosfets[e] = Mosfet(channel)
            # Thermistors
            adc = self.printer.config.get("Heaters", "path_adc_"+e)
            chart = self.printer.config.get("Heaters", "temp_chart_"+e)
            resistance = self.printer.config.getfloat("Heaters", "resistance_"+e)
            self.printer.thermistors[e] = Thermistor(adc, "MOSFET "+e, chart, resistance)
            self.printer.thermistors[e].printer = printer

            # Extruders
            onoff = self.printer.config.getboolean('Heaters', 'onoff_'+e)
            prefix =  self.printer.config.get('Heaters', 'prefix_'+e)
            if e != "HBP":
                self.printer.heaters[e] = Extruder(
                                        self.printer.steppers[e],
                                        self.printer.thermistors[e],
                                        self.printer.mosfets[e], e, onoff)
            else:
                self.printer.heaters[e] = HBP(
                                        self.printer.thermistors[e],
                                        self.printer.mosfets[e], onoff)
            self.printer.heaters[e].prefix = prefix
            self.printer.heaters[e].P = self.printer.config.getfloat('Heaters', 'pid_p_'+e)
            self.printer.heaters[e].I = self.printer.config.getfloat('Heaters', 'pid_i_'+e)
            self.printer.heaters[e].D = self.printer.config.getfloat('Heaters', 'pid_d_'+e)

        # Init the three fans. Argument is PWM channel number
        self.printer.fans = []
        if self.revision == "00A3":
            self.printer.fans.append(Fan(0))
            self.printer.fans.append(Fan(1))
            self.printer.fans.append(Fan(2))
        elif self.revision == "0A4A":
            self.printer.fans.append(Fan(8))
            self.printer.fans.append(Fan(9))
            self.printer.fans.append(Fan(10))
        elif self.revision in ["00B1", "00B2"]:
            self.printer.fans.append(Fan(7))
            self.printer.fans.append(Fan(8))
            self.printer.fans.append(Fan(9))
            self.printer.fans.append(Fan(10))


        # Disable all fans
        for f in self.printer.fans:
            f.set_value(0)

        # Init the servos
        printer.servos = []
        servo_nr = 0
        while(printer.config.has_option("Servos", "servo_"+str(servo_nr)+"_enable")):
            if printer.config.getboolean("Servos", "servo_"+str(servo_nr)+"_enable"):
                channel = printer.config.get("Servos", "servo_"+str(servo_nr)+"_channel")
                angle_init = printer.config.getint("Servos", "servo_"+str(servo_nr)+"_angle_init")
                s = Servo(channel, 0.1, 0.2, angle_init)
                printer.servos.append(s)
                logging.info("Added servo "+str(servo_nr))
            servo_nr += 1

        # Connect thermitors to fans
        for t, therm in self.printer.heaters.iteritems():
            for f, fan in enumerate(self.printer.fans):
                if self.printer.config.getboolean('Cold-ends', "connect-therm-{}-fan-{}".format(t, f)):
                    c = Cooler(therm, fan, "Cooler-{}-{}".format(t, f), False)
                    c.ok_range = 4
                    c.set_target_temperature(60)
                    c.enable()
                    self.printer.coolers.append(c)
                    logging.info("Cooler connects therm {} with fan {}".format(t, f))

        # Connect fans to M106
        printer.controlled_fans = []
        for i, fan in enumerate(self.printer.fans):
            if self.printer.config.getboolean('Cold-ends', "add-fan-{}-to-M106".format(i)):
                printer.controlled_fans.append(self.printer.fans[i])
                logging.info("Added fan {} to M106/M107".format(i))

        # Connect the colds to fans
        for ce, cold_end in enumerate(self.printer.cold_ends):
            for f, fan in enumerate(self.printer.fans):
                option = "connect-ds18b20-{}-fan-{}".format(ce, f)
                if self.printer.config.has_option('Cold-ends', option):
                    if self.printer.config.getboolean('Cold-ends', option):
                        c = Cooler(cold_end, fan, "Cooler-ds18b20-{}-{}".format(ce, f), False)
                        c.ok_range = 4
                        c.set_target_temperature(60)
                        c.enable()
                        self.printer.coolers.append(c)
                        logging.info("Cooler connects temp sensor ds18b20 {} with fan {}".format(ce, f))

        # Make a queue of commands
        self.printer.commands = JoinableQueue(10)

        # Make a queue of commands that should not be buffered
        self.printer.sync_commands = JoinableQueue()
        self.printer.unbuffered_commands = JoinableQueue(10)

        # Bed compensation matrix
        Path.matrix_bed_comp = printer.load_bed_compensation_matrix()
        Path.matrix_bed_comp_inv = np.linalg.inv(Path.matrix_bed_comp)
        logging.debug("Loaded bed compensation matrix: \n"+str(Path.matrix_bed_comp))

        for axis in printer.steppers.keys():
            i = Path.axis_to_index(axis)
            Path.max_speeds[i] = printer.config.getfloat('Planner', 'max_speed_'+axis.lower())
            Path.home_speed[i] = printer.config.getfloat('Homing', 'home_speed_'+axis.lower())
            Path.home_backoff_speed[i] = printer.config.getfloat('Homing', 'home_backoff_speed_'+axis.lower())
            Path.home_backoff_offset[i] = printer.config.getfloat('Homing', 'home_backoff_offset_'+axis.lower())
            Path.steps_pr_meter[i] = printer.steppers[axis].get_steps_pr_meter()
            Path.backlash_compensation[i] = printer.config.getfloat('Steppers', 'backlash_'+axis.lower())

        dirname = os.path.dirname(os.path.realpath(__file__))

        # Create the firmware compiler
        pru_firmware = PruFirmware(
            dirname + "/firmware/firmware_runtime.p",
            dirname + "/firmware/firmware_runtime.bin",
            dirname + "/firmware/firmware_endstops.p",
            dirname + "/firmware/firmware_endstops.bin",
            self.revision, self.printer.config, "/usr/bin/pasm")

        printer.maxJerkXY = printer.config.getfloat('Planner', 'maxJerk_xy')
        printer.maxJerkZ = printer.config.getfloat('Planner', 'maxJerk_z')
        printer.maxJerkEH = printer.config.getfloat('Planner', 'maxJerk_eh')

        printer.move_cache_size = printer.config.getfloat('Planner', 'move_cache_size')
        printer.print_move_buffer_wait = printer.config.getfloat('Planner', 'print_move_buffer_wait')
        printer.min_buffered_move_time = printer.config.getfloat('Planner', 'min_buffered_move_time')
        printer.max_buffered_move_time = printer.config.getfloat('Planner', 'max_buffered_move_time')

        self.printer.processor = GCodeProcessor(self.printer)
        self.printer.plugins = PluginsController(self.printer)

        # Path planner
        travel_default = False
        center_default = False
        home_default = False

        # Setting acceleration before PathPlanner init
        for axis in printer.steppers.keys():
            printer.acceleration[Path.axis_to_index(axis)] = printer.config.getfloat(
                                                        'Planner', 'acceleration_' + axis.lower())

        self.printer.path_planner = PathPlanner(self.printer, pru_firmware)
        for axis in printer.steppers.keys():
            i = Path.axis_to_index(axis)

            # Sometimes soft_end_stop aren't defined to be at the exact hardware boundary.
            # Adding 100mm for searching buffer.
            if printer.config.has_option('Geometry', 'travel_' + axis.lower()):
                printer.path_planner.travel_length[axis] = printer.config.getfloat('Geometry', 'travel_' + axis.lower())
            else:
                printer.path_planner.travel_length[axis] = (Path.soft_max[i] - Path.soft_min[i]) + .1
                if axis in ['X','Y','Z']:
                    travel_default = True

            if printer.config.has_option('Geometry', 'offset_' + axis.lower()):
                printer.path_planner.center_offset[axis] = printer.config.getfloat('Geometry', 'offset_' + axis.lower())
            else:
                printer.path_planner.center_offset[axis] =(Path.soft_min[i] if Path.home_speed[i] > 0 else Path.soft_max[i])
                if axis in ['X','Y','Z']:
                    center_default = True

            if printer.config.has_option('Homing', 'home_' + axis.lower()):
                printer.path_planner.home_pos[axis] = printer.config.getfloat('Homing', 'home_' + axis.lower())
            else:
                printer.path_planner.home_pos[axis] = printer.path_planner.center_offset[axis]
                if axis in ['X','Y','Z']:
                    home_default = True

        if Path.axis_config == Path.AXIS_CONFIG_DELTA:
            if travel_default:
                logging.warning("Axis travel (travel_*) set by soft limits, manual setup is recommended for a delta")
            if center_default:
                logging.warning("Axis offsets (offset_*) set by soft limits, manual setup is recommended for a delta")
            if home_default:
                logging.warning("Home position (home_*) set by soft limits or offset_*")
                logging.info("Home position will be recalculated...")

                # convert home_pos to effector space
                Az = printer.path_planner.home_pos['X']
                Bz = printer.path_planner.home_pos['Y']
                Cz = printer.path_planner.home_pos['Z']

                z_offset = Delta.vertical_offset(Az,Bz,Cz) # vertical offset
                xyz = Delta.forward_kinematics2(Az, Bz, Cz) # effector position

                # The default home_pos, provided above, is based on effector space
                # coordinates for carriage positions. We need to transform these to
                # get where the effector actually is.
                xyz[2] += z_offset
                for i, a in enumerate(['X','Y','Z']):
                    printer.path_planner.home_pos[a] = xyz[i]

                logging.info("Home position = %s"%str(printer.path_planner.home_pos))

        if Path.axis_config == Path.AXIS_CONFIG_SCARA:
            if travel_default:
                logging.warning("Axis travel (travel_*) set by soft limits, manual setup is recommended for a scara")
            if center_default:
                logging.warning("Axis offsets (offset_*) set by soft limits, manual setup is recommended for a scara")
            if home_default:
                logging.warning("Home position (home_*) set by soft limits or offset_*")
                logging.info("Home position will be recalculated...")

                # convert home_pos to effector space
                #A = printer.path_planner.home_pos['X']
                #B = printer.path_planner.home_pos['Y']
                #C = printer.path_planner.home_pos['Z']

                #z_offset = Delta.vertical_offset(Az,Bz,Cz) # vertical offset
                #xyz = Scara.forward_kinematics(A, B, C) # effector position

                # don't cpnvert home_pos to effector spac
                # home offset is defined in cartesian space

                xyz = np.array([printer.path_planner.home_pos['X'],printer.path_planner.home_pos['Y'],printer.path_planner.home_pos['Z']])

                # The default home_pos, provided above, is based on effector space
                # coordinates for carriage positions. We need to transform these to
                # get where the effector actually is.
                #xyz[2] += z_offset
                for i, a in enumerate(['X','Y','Z']):
                    printer.path_planner.home_pos[a] = xyz[i]

                logging.info("Home position = %s"%str(printer.path_planner.home_pos))

        # Enable PWM and steppers
        printer.enable = Enable("P9_41")
        printer.enable.set_enabled()

        # Set up communication channels
        printer.comms["USB"] = USB(self.printer)
        printer.comms["Eth"] = Ethernet(self.printer)

        if Pipe.check_tty0tty() or Pipe.check_socat():
            printer.comms["octoprint"] = Pipe(printer, "octoprint")
            printer.comms["toggle"] = Pipe(printer, "toggle")
            printer.comms["testing"] = Pipe(printer, "testing")
            printer.comms["testing_noret"] = Pipe(printer, "testing_noret")
            # Does not send "ok"
            printer.comms["testing_noret"].send_response = False
        else:
            logging.warning("Neither tty0tty or socat is installed! No virtual tty pipes enabled")