Exemple #1
0
    def exampleHuissen(self):

        f = open("alarm_db/2018-06-24-04-13-11.xml", "rb")
        xmlContent = f.read()
        f.close()

        alarm = Alarm(self.config)

        try:
            alarm.fromXml(xmlContent, self.logger)
        except:
            self.logger.error('Failed to parse XML:', exc_info=True)
            return

        self.processAlarm(alarm)
	def __init__(self, **kwargs):
		super(Alarm_manager_widget, self).__init__(**kwargs)
		# self.Alarm_Body=Alarm_Body=FloatLayout(pos_hint={'center_x':0.5,'y':0})
		self.AM_bar=AM_bar=BoxLayout(orientation='vertical')
		self.scroller=scroller=ScrollView(size_hint=(1,.9),pos_hint={'center_x':0.5,'top':1})
		scroller.add_widget(AM_bar)
		self.add_widget(scroller)
		self.f=f=open("alarms.txt", "r")
		self.Alarm_one =Alarm_one= Alarm()

		# AM_bar.add_widget(Alarm_widget(size_hint=(1,None),height=100))
		


		

		for line in f:
			print (line)
			try:
				self.Create_Alarm(Alarm_one.ReadMinutes(line), Alarm_one.ReadSeconds(line) , Alarm_one.ReadAlarm(line))
			except IndexError:
				break

		f.close()
		self.AM_ToolBar=FloatLayout(size_hint=(1,.1),pos_hint={'center_x':0.5,'y':0})
		self.add_widget(self.AM_ToolBar)
		self.kuku=BooleanProperty(False)
Exemple #3
0
    def alarms(self, value):
        for alarm in self._alarms:
            alarm.cancel()
            self._alarms.remove(alarm)

        for alarmString in value:
            self._alarms.append(Alarm(alarmString, self, seconds=10 * 60))
 def load_alarms(self):
     foo = self.cursor.execute('SELECT * FROM INTEGRATION_ALARM;')
     self.alarms = [Alarm(x) for x in foo]
     alarms_stack = self.builder.get_object('alarmsStack')
     for x in self.alarms:
         alarms_stack.pack_start(x.get_button(), False, False, False)
         x.get_button().show()
Exemple #5
0
    def __init__(self, test=Constants.test, parent=None):
        # UI init
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.voltageTimer = QTimer()
        self.voltageTimer.start(
            Constants.updateRate)  # update every 0.15 second
        self.guiTimer = QTimer()
        self.guiTimer.start(0)
        self.cm = plt.get_cmap('cool')
        self.alarm = Alarm(Constants.alarmParams, parent=self)
        self.judge = Judge(Constants.DATA_DIR)
        self.warning = Warning(parent=self)
        self.recorder = None
        self.setting = Setting(self.alarm.getInitialState())
        self.time = None
        self.measure = None
        self.predict = {'predict': 1, 'cnt': 0, 'curr_predict': None}

        # check it is test mode or not (arduino don't need to connect)
        try:
            self.arduino = Arduino()
        except:
            print('using monk arduino')
            self.arduino = ArduinoTest()

        # Connection
        self.voltageTimer.timeout.connect(self.voltageUpdate)
        self.ui.actionRecord_Data.triggered.connect(self.recordData)
        self.ui.actionSetting.triggered.connect(self.showSetting)
        self.setting.finished.connect(self.settingClose)
        self.guiTimer.timeout.connect(self.guiUpdate)

        # ShortCut
        self.ui.actionRecord_Data.setShortcut("Ctrl+D")
        self.ui.actionSetting.setShortcut("Ctrl+S")

        # Check is there are the data valid or not
        self.judgeStatusCheck()

        # Show the main window
        self.show()

        # Show and locate the warning message manually
        self.warning.showWarning()
Exemple #6
0
 def execute_alarm(self):
     a = Alarm(
         Alarm.FILAMENT_JAM,
         "Filament deviation above limit ({0:.2f} mm) for extruder {1} ".
         format(self.error_pos * 1000,
                self.ext_nr), "Filament jam on ext. {}".format(self.ext_nr))
     logging.warning(
         "Extruder {0} has reported too large deviation: {1:.2f} mm".format(
             self.ext_nr, self.error_pos * 1000))
Exemple #7
0
    def response(self, data):
        """新线程要做的事"""

        addr = data['addr']
        tcp_client = data['tcp_client']
        buf_size = data['buf_size']

        # 接受客户端述数据
        data = tcp_client.recv(buf_size).decode()
        # 将客户端数据转换成列表
        data = simplejson.loads(data)
        # 对数据进行计算
        info = InfoCompute(data)

        # 获取所有结果
        data_precent = info.return_all_precent()

        # 策略类
        str = Strategies()
        # 获取check的结果
        total, message = str.check_all_data(data_precent,
                                            self.old_alarm_dict[addr])
        # 告警
        alarm = Alarm()
        # 对数据进行检测,如果超出阈值,则就开始告警
        # sign : 0则表示不进行报警,1则表示告警的级别
        sign = alarm.send_mail(total, message)
        print("%s's sign: %d " % (addr, sign))
        data_precent['level'] = sign
        data_precent['message'] = message
        # 将结果保存到列表里面
        per = Persistent()
        # 保存所有源数据
        per.save_all_data(data, addr)
        # 保存警告后的数据
        per.save_alarm_data(data_precent, addr)

        # 告警过后,将历史数据清空
        if sign >= 4:
            total = self.init_alarm
            print("------------------")
        self.old_alarm_dict[addr] = total
        # 退出后关闭连接
        tcp_client.close()
Exemple #8
0
    def execute(self, g):
        bed_diameter_mm = g.get_float_by_letter("D", 140.0)  # Bed diameter
        circles = g.get_int_by_letter("C", 2)  # Number of circles
        points_pr_circle = g.get_int_by_letter("P", 8)  # Points pr circle
        probe_start_height = g.get_float_by_letter(
            "S", 6.0)  # Probe starting point above bed
        add_zero = bool(g.get_int_by_letter("Z", 1))  # Add probe point in 0, 0
        probe_speed = g.get_float_by_letter("K", 3000)
        reverse = g.get_int_by_letter("R", 0)
        reverse = -1 if bool(reverse) else 1

        theta = np.linspace(0,
                            reverse * 2 * np.pi,
                            points_pr_circle,
                            endpoint=False)

        probes = []
        r = bed_diameter_mm / 2
        for a in np.linspace(r, 0, circles, endpoint=False):
            for t in theta:
                x, y = a * np.cos(t), a * np.sin(t)
                probes.append((x, y))
        if add_zero:
            probes.append((0, 0))

        gcodes = "M561; (RFS) Reset bed matrix\n"
        for i, p in enumerate(probes):
            gcodes += "M557 P{0} X{1:+02.2f} Y{2:+02.2f} Z{3}\n".format(
                i, p[0], p[1], probe_start_height)
        gcodes += "    G32 ; Undock probe\n"
        gcodes += "    G28 ; Home steppers\n"
        for i in range(len(probes)):
            gcodes += "    G30 P{} S F{}; Probe point {}\n".format(
                i, probe_speed, i)
        gcodes += "    G31 ; Dock probe\n"
        gcodes += "    M561 U; (RFS) Update the matrix based on probe data\n"
        gcodes += "    M561 S; Show the current matrix\n"
        gcodes += "    M500; (RFS) Save data\n"

        # REset probe points
        self.printer.probe_points = []
        self.printer.config.set("Macros", "G29", gcodes)
        Alarm.action_command("new_g29", json.dumps(gcodes))
Exemple #9
0
    def response(self, data):
        """新线程要做的事"""

        addr = data['addr']
        tcp_client = data['tcp_client']
        buf_size = data['buf_size']

        # 接受客户端述数据
        data = tcp_client.recv(buf_size).decode()
        # 将客户端数据转换成列表
        data = simplejson.loads(data)
        # 对数据进行计算
        info = InfoCompute(data)

        # 获取所有结果
        data_precent = info.return_all_precent()

        # 策略类
        str = Strategies()
        # 获取check的结果
        total, message = str.check_all_data(data_precent, self.old_alarm_dict[addr])
        # 告警
        alarm = Alarm()
        # 对数据进行检测,如果超出阈值,则就开始告警
        # sign : 0则表示不进行报警,1则表示告警的级别
        sign = alarm.send_mail(total, message)
        print("%s's sign: %d " % (addr, sign))
        data_precent['level'] = sign
        data_precent['message'] = message
        # 将结果保存到列表里面
        per = Persistent()
        # 保存所有源数据
        per.save_all_data(data, addr)
        # 保存警告后的数据
        per.save_alarm_data(data_precent, addr)

        # 告警过后,将历史数据清空
        if sign >= 4:
            total = self.init_alarm
            print("------------------")
        self.old_alarm_dict[addr] = total
        # 退出后关闭连接
        tcp_client.close()
Exemple #10
0
    def _loop(self):
        ''' Gather distance travelled from each of the sensors '''
        while self.running:
            self.current_pos = self.sensor.get_distance()
            if self.printer and self.printer.path_planner:
                self.ideal_pos = self.printer.path_planner.get_extruder_pos(self.ext_nr)

            # Find the error in position, removing any previously reported error
            self.error_pos = self.current_pos-self.ideal_pos-self.prev_alarm_pos

            # Sound the alarm, if above level. 
            if abs(self.error_pos) >= self.alarm_level: 
                self.execute_alarm()
                self.prev_alarm_pos = self.current_pos-self.ideal_pos

            # Send filament data, if enabled
            if self.send_action_command:
                Alarm.action_command("filament_sensor", self.get_error())
            time.sleep(1)
    def __init__(self, **kwargs):
        super(SetAlarm_widget, self).__init__(**kwargs)
        self.Alarm_Body = Alarm_Body = FloatLayout(pos_hint={
            'center_x': 0.5,
            'y': 0
        })
        self.SM_TM = SM_TM = ScreenManager(size_hint=[1, .8],
                                           pos_hint={
                                               'center_x': 0.5,
                                               'top': 1
                                           })
        self.frst = frst = Set_Time_Screen(name='STS', id='firstw')
        # self.scnd=scnd=Act_Time_Screen(name='ATS',id='scndw')
        # self.thd=thd=Call_Time_Screen(name='CTS',id='thdw')
        # thd.CallAgreeButt.img1.source='icons8-circled-play-filled-90.png'
        # thd.CallAgreeButt.btn1.bind(on_release=self.IDAgree)
        # thd.CallDAgreeButt.img1.source='icons8-no-96.png'
        # thd.CallDAgreeButt.btn1.bind(on_release=self.IAgree)
        self.SM_TM.add_widget(frst)
        # self.SM_TM.add_widget(scnd)
        # self.SM_TM.add_widget(thd)
        self.AlarmSession = AlarmSession = Alarm()

        # self.Button_Pause=Button_Pause= AlarmLables(size_hint=[1/5.5,1],pos_hint={'center_x': .5, 'y': 0})
        # Button_Pause.img1.source='icons8-pause-button-filled-96.png'
        # Button_Pause.btn1.bind(on_release=self.LetsGetPause)

        # self.Button_Stop=Button_Stop= AlarmLables(size_hint=[1/5.5,1],pos_hint={'right': 0.9, 'y': 0})
        # Button_Stop.img1.source='icons8-no-96.png'
        # Button_Stop.btn1.bind(on_release=self.LetsGetStop)
        self.valueseconds = None
        self.valueminutes = None

        self.Alarm_ToolBar = Alarm_ToolBar = FloatLayout(size_hint=(.9, .1),
                                                         pos_hint={
                                                             'center_x': 0.5,
                                                             'y': 0
                                                         })

        # Alarm_ToolBar.add_widget(Button_Pause)
        # Alarm_ToolBar.add_widget(Button_Stop)

        # self.touchedS=BooleanProperty(False)

        # self.touchedP=BooleanProperty(False)

        # self.audiobool=BooleanProperty(False)
        # self.sound_inst_loop=['Sound1.mp3','Sound2.mp3','Sound3.mp3','Sound4.mp3','Sound5.mp3']
        # self.sound_loop=['1','2','3','4','5']
        # for i in range(len(self.sound_inst_loop)):
        #     self.sound_loop[i] = SoundLoader.load(self.sound_inst_loop[i])

        Alarm_Body.add_widget(SM_TM)
        Alarm_Body.add_widget(Alarm_ToolBar)
        self.add_widget(Alarm_Body)
Exemple #12
0
    def _loop(self):
        ''' Gather distance travelled from each of the sensors '''
        while self.running:
            self.current_pos = self.sensor.get_distance()
            if self.printer and self.printer.path_planner:
                self.ideal_pos = self.printer.path_planner.get_extruder_pos(
                    self.ext_nr)

            # Find the error in position, removing any previously reported error
            self.error_pos = self.current_pos - self.ideal_pos - self.prev_alarm_pos

            # Sound the alarm, if above level.
            if abs(self.error_pos) >= self.alarm_level:
                self.execute_alarm()
                self.prev_alarm_pos = self.current_pos - self.ideal_pos

            # Send filament data, if enabled
            if self.send_action_command:
                Alarm.action_command("filament_sensor", self.get_error())
            time.sleep(1)
Exemple #13
0
def main():
    while True:
        #retrieve data

        Trigger(db)

        # The alarm class, basically it checks in the database if the alarm is true or false,
        # based on that it either turns on or off the leds/buzzing
        Alarm(db)

        # makes it so it runs every second
        time.sleep(1)
Exemple #14
0
 def check_temperature_error(self):
     """ Check the temperatures, make sure they are sane. 
     Sound the alarm if something is wrong """
     if len(self.temperatures) < 2:
         return
     temp_delta = self.temperatures[-1] - self.temperatures[-2]
     # Check that temperature is not rising too quickly
     if temp_delta > self.max_temp_rise:
         a = Alarm(
             Alarm.HEATER_RISING_FAST,
             "Temperature rising too quickly ({} degrees) for {}".format(
                 temp_delta, self.name))
     # Check that temperature is not falling too quickly
     if temp_delta < -self.max_temp_fall:
         a = Alarm(
             Alarm.HEATER_FALLING_FAST,
             "Temperature falling too quickly ({} degrees) for {}".format(
                 temp_delta, self.name))
     # Check that temperature has not fallen below a certain setpoint from target
     if self.min_temp_enabled and self.current_temp < (self.target_temp -
                                                       self.min_temp):
         a = Alarm(
             Alarm.HEATER_TOO_COLD,
             "Temperature below min set point ({} degrees) for {}".format(
                 self.min_temp,
                 self.name), "Alarm: Heater {}".format(self.name))
     # Check if the temperature has gone beyond the max value
     if self.current_temp > self.max_temp:
         a = Alarm(
             Alarm.HEATER_TOO_HOT,
             "Temperature beyond max ({} degrees) for {}".format(
                 self.max_temp, self.name))
     # Check the time diff, only warn if something is off.
     if self.time_diff > 2:
         logging.warning("Heater time update large: " + self.name +
                         " temp: " + str(self.current_temp) +
                         " time delta: " +
                         str(self.current_time - self.prev_time))
Exemple #15
0
def main():
    # define buttons for gpio input
    mode_button = 29
    increase_button = 31
    decrease_button = 33

    # define serial and device in order to interact with the LED matrix
    serial = spi(port=0, device=0, gpio=noop())
    device = max7219(serial, cascaded=4, block_orientation=-90, rotate=1)
    virtual = viewport(device, width=8, height=32)

    # create instance of Alarm
    alarm = Alarm(virtual, device)

    # setup buttons
    GPIO.setmode(GPIO.BOARD)  # Use physical pin numbering
    GPIO.setup(mode_button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(increase_button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(decrease_button, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    # bounce time for the buttons so that they work properly
    bounce_time = 300
    # setup callbacks for the buttons with pull down logic
    GPIO.add_event_detect(mode_button,
                          GPIO.RISING,
                          callback=alarm.state_callback,
                          bouncetime=bounce_time)
    GPIO.add_event_detect(increase_button,
                          GPIO.RISING,
                          callback=alarm.inc_callback,
                          bouncetime=bounce_time)
    GPIO.add_event_detect(decrease_button,
                          GPIO.RISING,
                          callback=alarm.dec_callback,
                          bouncetime=bounce_time)

    # start alarm loop
    alarm.alarm_loop()
Exemple #16
0
    def execute(self, g):
        heater_nr = g.get_int_by_letter("E", 0)
        heater_name = ["HBP", "E", "H", "A", "B", "C"][heater_nr+1] # Map to name
        if not heater_name in self.printer.heaters:
            logging.warning("M303: Heater does not exist")
            return
        heater = self.printer.heaters[heater_name]
        temp     = g.get_float_by_letter("S", 200.0)        
        cycles   = min(3, g.get_int_by_letter("C", 4))       
        pre_cal  = bool(g.get_int_by_letter("P", 0))
        tuning_algo_nr = g.get_int_by_letter("Q", 0)
        if tuning_algo_nr not in [0, 1]:
            logging.warning("Unknown uning algorithm '{}'. Use one of 0, 1. Choosing 0.".format(tuning_algo_nr))
            tuning_algo_nr = 0
        tuning_algo = ["TL","ZN"][tuning_algo_nr]

        tuner = Autotune(heater, temp, cycles, g, self.printer, pre_cal, tuning_algo)
        tuner.run()
        logging.info("Max temp: {}, Min temp: {}, Ku: {}, Pu: {}".format(tuner.max_temp, tuner.min_temp, tuner.Ku, tuner.Pu))
        logging.info("Kp: {}, Ti: {}, Td: {}".format(heater.Kp, heater.Ti, heater.Td))
        self.printer.send_message(g.prot,"Max temp: {}, Min temp: {}, Ku: {}, Pu: {}".format(tuner.max_temp, tuner.min_temp, tuner.Ku, tuner.Pu))
        self.printer.send_message(g.prot, "Kp: {}, Ti: {}, Td: {}".format(heater.Kp, heater.Ti, heater.Td))
        self.printer.send_message(g.prot, "Settings by G-code: \n")
        self.printer.send_message(g.prot, "M130 P{} S{:.4f}\n".format(heater_nr, heater.Kp))
        self.printer.send_message(g.prot, "M131 P{} S{:.4f}\n".format(heater_nr, heater.Ti))
        self.printer.send_message(g.prot, "M132 P{} S{:.4f}\n".format(heater_nr, heater.Td))
        self.printer.send_message(g.prot, "Settings in local.cfg: \n")
        self.printer.send_message(g.prot, "pid_{}_Kp = {:.4f}\n".format(heater_name.lower(), heater.Kp))
        self.printer.send_message(g.prot, "pid_{}_Ti = {:.4f}\n".format(heater_name.lower(), heater.Ti))
        self.printer.send_message(g.prot, "pid_{}_Td = {:.4f}".format(heater_name.lower(), heater.Td))

        tune_data = {
            "tune_data": tuner.plot_temps,
            "tune_gcode": g.message,
            "replicape_key": self.printer.replicape_key}

        Alarm.action_command("pid_tune_data", json.dumps(tune_data))
Exemple #17
0
    def run(self):
        Main.start_time = '{:.19}'.format(str(datetime.now()))

        ip_addresses = ["216.58.192.142", "aftonbladet.se", "mixer.com"]

        def internet_on(ip_list):
            success = False

            for ip in ip_list:
                try:
                    request.urlopen("http://" + ip, timeout=2)
                    success = True
                except error.URLError as err:
                    print("URL that generated the error code: ", ip)
                    print("Error description:", err.reason)
                except socket.timeout:
                    print("URL that generated the error code: ", ip)
                    print("Error description: No response.")
                except socket.error:
                    print("URL that generated the error code: ", ip)
                    print("Error description: Socket error.")

            if not success:
                Main.dc_list.append(ConError())
                history_file = open('history.txt', 'a+')
                history_file.write('{:.19}'.format(str(datetime.now())) + '\n')
                history_file.close()

            return success

        while True:
            Main.internet_status = internet_on(ip_addresses)
            Main.current_time = '{:.19}'.format(str(datetime.now()))
            Main.last_dc = '{:.19}'.format(str(ConError.last_dc))
            Main.total_dc = str(ConError.total_dc)

            if len(Main.dc_list) >= 4:
                Main.next_dc = Main.dc_list[-4].time + timedelta(
                    days=3) + timedelta(minutes=11)

            if not Main.internet_status:
                sleep(600)
            else:
                Alarm(self.dc_list)
                sleep(randint(7, 30))
Exemple #18
0
    def __init__(self, pin, sensorConfiguration, name):

        if len(sensorConfiguration) != 5:
            logging.error(
                "PT100 Sensor configuration for {0} is missing parameters. Expected: 5, received: {1}."
                .format(pin, len(sensorConfiguration)))
            Alarm(
                Alarm.THERMISTOR_ERROR,
                "PT100 Sensor configuration for {0} is missing parameters. Expected: 5, received: {1}."
                .format(pin, len(sensorConfiguration)))
        else:
            self.pin = pin
            self.name = name
            self.sensorIdentifier = sensorConfiguration[0]  # The identifier
            self.pullup = sensorConfiguration[1]
            self.R0 = sensorConfiguration[2]
            self.A = sensorConfiguration[3]
            self.B = sensorConfiguration[4]
Exemple #19
0
 def get_temperature(self):
     """ Return the temperature in degrees celsius """
     ret = -1.0
     Thermistor.mutex.acquire()
     try:
         with open(self.pin, "r") as file:
             voltage = (float(file.read().rstrip()) / 4095.0) * 1.8
             res_val = self.voltage_to_resistance(
                 voltage)  # Convert to resistance
             ret = self.resistance_to_degrees(res_val)  # Convert to degrees
     except IOError as e:
         Alarm(
             Alarm.THERMISTOR_ERROR,
             "Unable to get ADC value ({0}): {1}".format(
                 e.errno, e.strerror))
     finally:
         Thermistor.mutex.release()
     return ret
Exemple #20
0
    def read_adc(self):
        voltage = 0

        TemperatureSensor.mutex.acquire()
        try:
            with open(self.pin, "r") as file:
                signal = float(file.read().rstrip())
                if (signal > self.maxAdc or signal <= 0.0):
                    voltage = -1.0
                else:
                    voltage = signal / self.maxAdc * 1.8  #input range is 0 ... 1.8V
        except IOError as e:
            Alarm(
                Alarm.THERMISTOR_ERROR,
                "Unable to get ADC value ({0}): {1}".format(
                    e.errno, e.strerror))

        TemperatureSensor.mutex.release()
        return voltage
Exemple #21
0
 def __init__(self, pin, sensorConfiguration, name):
     """ Init """
     self.name = name
     if len(sensorConfiguration) != 5:
         Alarm(
             Alarm.THERMISTOR_ERROR,
             "Sensor configuration for {0} is missing parameters. Expected: 5, received: {1}."
             .format(pin, len(sensorConfiguration)))
     else:
         self.pin = pin
         self.sensorIdentifier = sensorConfiguration[0]  # The identifier
         self.r1 = sensorConfiguration[1]  #pullup resistance
         self.c1 = sensorConfiguration[2]  #Steinhart-Hart coefficient
         self.c2 = sensorConfiguration[3]  #Steinhart-Hart coefficient
         self.c3 = sensorConfiguration[4]  #Steinhart-Hart coefficient
         logging.debug(
             "Initialized temperature sensor at {0} (type: {1}). Pullup value = {2} Ohm. Steinhart-Hart coefficients: c1 = {3}, c2 = {4}, c3 = {5}."
             .format(pin, sensorConfiguration[0], sensorConfiguration[1],
                     sensorConfiguration[2], sensorConfiguration[3],
                     sensorConfiguration[4]))
Exemple #22
0
settings_data = config.SETTINGS

radio_channels = None

with open(radio_config) as data_file:
    radio_data = json.load(data_file)

if "channels" in radio_data:
    radio_channels = radio_data['channels']

p = Radio(radio_channels=radio_channels, mplayer_path=config.MPLAYER_PATH)
if "radio" in settings_data:
    _radio_settings = settings_data['radio']
    p.change_country(_radio_settings['country'])
    if "radio_stations" in _radio_settings and len(_radio_settings['radio_stations']) > 0:
        p.radio_channels.extend(_radio_settings['radio_stations'])

web_frontend.radio = p
alarm = Alarm("res/sounds/Argon_48k.wav", settings=settings_data)
alarm.create_alarms()

web_frontend.alarm = alarm

last_state = config.load_last_state()
if last_state is not None:
    p.set_channel(last_state["last_radio_station"])
    gui.current_page = last_state["last_page"]

tingbot.run(loop)
Exemple #23
0
 def execute(self, g):
     # This G-code can be used directly
     text = g.message.strip("M117 ")
     Alarm.action_command("display_message", text)
Exemple #24
0
 def fault_callback(self, key, event):
     Alarm(
         Alarm.STEPPER_FAULT,
         "Stepper {}<br>Most likely the stepper is over heated.".format(
             self.name))
Exemple #25
0
 def __init__(self, pin, ArduinoPort):
     Alarm.__init__(self, pin, ArduinoPort)
Exemple #26
0
    def execute(self, g):
        if g.has_letter("P"):  # Load point
            index = int(g.get_value_by_letter("P"))
            point = self.printer.probe_points[index]
        else:
            # If no probe point is specified, use current pos
            # this value is in metres
            # need to convert to millimetres as we are using
            #this value for a G0 call
            point = self.printer.path_planner.get_current_pos(mm=True,
                                                              ideal=True)
            logging.debug("G30: current position (mm) :  X{} Y{} Z{}".format(
                point["X"], point["Y"], point["Z"]))

        if g.has_letter("X"):  # Override X
            point["X"] = float(g.get_value_by_letter("X"))
        if g.has_letter("Y"):  # Override Y
            point["Y"] = float(g.get_value_by_letter("Y"))
        if g.has_letter("Z"):  # Override Z
            point["Z"] = float(g.get_value_by_letter("Z"))

        # Get probe length, if present, else use 1 cm.
        if g.has_letter("D"):
            probe_length = float(g.get_value_by_letter("D")) / 1000.
        else:
            probe_length = self.printer.config.getfloat('Probe', 'length')

        # Get probe speed. If not preset, use printers curent speed.
        if g.has_letter("F"):
            probe_speed = float(g.get_value_by_letter("F")) / 60000.0
        else:
            probe_speed = self.printer.config.getfloat('Probe', 'speed')

        # Get acceleration. If not present, use value from config.
        if g.has_letter("A"):
            probe_accel = float(g.get_value_by_letter("A"))
        else:
            probe_accel = self.printer.config.getfloat('Probe', 'accel')

        use_bed_matrix = bool(g.get_int_by_letter("B", 0))

        # Find the Probe offset
        # values in config file are in metres, need to convert to millimetres
        offset_x = self.printer.config.getfloat('Probe', 'offset_x') * 1000
        offset_y = self.printer.config.getfloat('Probe', 'offset_y') * 1000

        logging.debug("G30: probing from point (mm) : X{} Y{} Z{}".format(
            point["X"] + offset_x, point["Y"] + offset_y, point["Z"]))

        # Move to the position
        G0 = Gcode({
            "message":
            "G0 X{} Y{} Z{}".format(point["X"] + offset_x,
                                    point["Y"] + offset_y, point["Z"]),
            "prot":
            g.prot
        })
        self.printer.processor.execute(G0)
        self.printer.path_planner.wait_until_done()
        bed_dist = self.printer.path_planner.probe(
            probe_length, probe_speed, probe_accel) * 1000.0  # convert to mm
        logging.debug("Bed dist: " + str(bed_dist) + " mm")

        self.printer.send_message(
            g.prot,
            "Found Z probe distance {0:.2f} mm at (X, Y) = ({1:.2f}, {2:.2f})".
            format(bed_dist, point["X"], point["Y"]))

        Alarm.action_command("bed_probe_point",
                             json.dumps([point["X"], point["Y"], bed_dist]))

        # Must have S to save the probe bed distance
        # this is required for calculation of the bed compensation matrix
        # NOTE: the use of S in G30 is different to that in G29, here "S" means "save"
        if g.has_letter("S"):
            if not g.has_letter("P"):
                logging.warning(
                    "G30: S-parameter was set, but no index (P) was set.")
            else:
                self.printer.probe_heights[index] = bed_dist
Exemple #27
0
    def start(self):
        self.cycleTimer.stop()

        path = self.config.get("db", "path", fallback=None)
        if not path:
            return

        paths = [os.path.join(path, entry) for entry in os.listdir(path)]
        paths = [path for path in paths if \
                (path.endswith('.dme') or \
                path.endswith('.xml') or \
                path.endswith('.json')) and \
                os.path.isfile(path)]
        paths = sorted(paths, reverse=True)

        self.alarms = []
        index = 0
        while index < self.historySize and len(paths) > 0:
            path = paths[0]
            paths = paths[1:]

            alarm = Alarm(self.config)
            try:
                alarm.load(path)
            except Exception as e:
                self.logger.error('History failed to load %s: %s', path, e)
                continue

            if alarm.fallbackStr:
                # ignore incomplete or invalid alarms in history
                continue

            if len(self.alarms) and self.alarms[-1].matches(alarm):
                self.alarms[-1].merge(alarm)
            else:
                self.alarms.append(alarm)
                index += 1

        local_tz = get_localzone()
        now = local_tz.localize(datetime.datetime.now())

        index = 0
        for alarm in self.alarms:
            dateStr = alarm.datetime.strftime('%A, %d. %B, %H:%M')
            delta = alarm.datetime - now
            dateStr += ' (' + babel.dates.format_timedelta(
                delta, add_direction=True) + ')'
            image = alarm.imageBase()
            if image:
                image += '.svg'
                pixmap = pixmapFromSvg(os.path.join(self.imageDir, image), 40)
            else:
                pixmap = QPixmap()
            self.symbolLabels[index].setPixmap(pixmap)
            title = alarm.title()
            if not title:
                title = alarm.fallbackStr
            self.titleLabels[index].setText(title)
            desc = dateStr
            loc = alarm.location()
            if loc:
                desc += '\n' + loc
            self.descLabels[index].setText(desc)
            index += 1

        self.index = 0
        if len(self.alarms):
            alarm = self.alarms[self.index]
            self.targetMap.setTarget(alarm.lat, alarm.lon, ([], ))
            self.cycleTimer.start()
            self.updateStyles()
        else:
            self.finished.emit()
Exemple #28
0
 def fault_callback(self, key, event):
     Alarm(Alarm.STEPPER_FAULT, "Stepper {}".format(self.name))
Exemple #29
0
 def execute(self, g):
     # This G-code can be used directly
     text = g.message.strip("M117 ")
     Alarm.action_command("display_message", text)
def main():
    # We need the logger variable in the exception handler.
    # So we create it here.
    logger = logging.getLogger( 'DCacheAggregator' )

    # Ignore hangup signals. We shouldn't die just because our parent
    # shell logs out.
    signal.signal( signal.SIGHUP, signal.SIG_IGN )
    # Try to catch common signals and send email before we die
    signal.signal( signal.SIGINT,  warn_of_signal );
    signal.signal( signal.SIGQUIT, warn_of_signal );
    signal.signal( signal.SIGTERM, warn_of_signal );

    try:
        # Tell Gratia what versions we are using.
        # CHRIS: is there a way to automate the version extraction
        #        using the pkg_resource package?
        Gratia.RegisterReporterLibrary( "psycopg2", "2.0.6" )
        #Gratia.RegisterReporterLibrary( "SQLAlchemy", "0.4.1" )
        rev =  Gratia.ExtractCvsRevision("$Revision: 1.13 $")
        tag =  Gratia.ExtractCvsRevision("$Name:  $")
        Gratia.RegisterReporter( "dCacheBillingAggregator.py",
                                 str(rev) + " (tag " + str(tag) + ")")

        # BRIAN: attempt to pull the dCache version from RPM.
        version = "UNKNOWN"
        try:
            version = os.popen("rpm -q --qf '%{VERSION}-%{RELEASE}' " \
                               "dcache-server").read()
        except:
            pass
        Gratia.RegisterService( "dCache", version )


        # Initialize gratia before attempting to read its config file.
        Gratia.Initialize()
        # Extract the configuration information into local variables.
        myconf = dCacheProbeConfig()

        # Get the name of the directory where we are to store the log files.
        logDir = myconf.get_LogFolder()

        # Make sure that the logging directory is present
        if not os.path.isdir( logDir ):
            os.mkdir( logDir, 0755 )

        logFileName = os.path.join( logDir, "dcacheTransfer.log" )

        # Set up an alarm to send an email if the program terminates.
        termSubject = "dCache-transfer probe is going down"
        termMessage = "The dCache transfer probe for Gratia has " + \
                      "terminated.\nPlease check the logfile\n\n   " + \
                      logFileName + \
                      "\n\nfor the cause.\n"

        terminationAlarm = Alarm( myconf.get_EmailServerHost(),
                                  myconf.get_EmailFromAddress(),
                                  myconf.get_EmailToList(),
                                  termSubject, termMessage, 0, 0, False )

        # Set up the logger with a suitable format
        hdlr = RotatingFileHandler( logFileName, 'a', 512000, 10 )
        formatter = logging.Formatter( '%(asctime)s %(levelname)s %(message)s' )
        hdlr.setFormatter( formatter )
        logger.addHandler( hdlr )
        logger.setLevel( myconf.get_AggrLogLevel() )
        logger.info( "starting " + ProgramName )

        stopFileName = myconf.get_StopFileName()
        updateFreq = float(myconf.get_UpdateFrequency())
        logger.warn("update freq = %.2f" % updateFreq)

        # Create the aggregator instance that we will use.
        dataDir = myconf.get_DataFolder()
        aggregator = DCacheAggregator(myconf, dataDir)

        # If profiling was requested, turn it on.
        profiling = sys.argv.count('-profile') > 0
        if profiling:
            profiler = hotshot.Profile("profile.dat")
            logger.info( "Enabling Profiling" )

        # Now aggregate new records, then sleep, until somebody creates
        # the stop file...
        while 1:
            # Make sure we (still) have a connection to Gratia.
            if ( not TestContainer.isTest() ): # no need in that during self test
               Gratia.Maintenance()
          
            if profiling:
                profiler.run("aggregator.sendBillingInfoRecordsToGratia()")
            else:
                try:
                    aggregator.sendBillingInfoRecordsToGratia()
                except TestContainer.SimInterrupt:
                    logger.info("BillingRecSimulator.SimInterrupt caught, " \
                        "restarting")
                    aggregator = DCacheAggregator(myconf, dataDir)
                    continue
            # Are we are shutting down?
            if os.path.exists(stopFileName):
                break

            if TestContainer.isTest():
                break

            logger.warn("sleeping for = %.2f seconds" % updateFreq)
            sleep_check(updateFreq, stopFileName)

        # If we are profiling, print the results...
        if profiling:
            profiler.close()
            stats = hotshot.stats.load("profile.dat")
            stats.sort_stats('time', 'calls')
            stats.print_stats()

        logger.warn(ProgramName + " stop file detected.")
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        # format the traceback into a string
        tblist = traceback.format_exception( sys.exc_type,
                                             sys.exc_value,
                                             sys.exc_traceback )
        msg = ProgramName + " caught an exception:\n" + "".join(tblist)
        print msg
        logger.error(msg)

    TestContainer.dumpStatistics(logger)

    # shut down the logger to make sure nothing is lost.
    logger.critical(ProgramName + " shutting down.")
    logging.shutdown()
    # try to send an email warning of the shutdown.
    if terminationAlarm != None:
        terminationAlarm.event()

    sys.exit(1)
Exemple #31
0
def main():
    # We need the logger variable in the exception handler.
    # So we create it here.
    logger = logging.getLogger('DCacheAggregator')

    # Ignore hangup signals. We shouldn't die just because our parent
    # shell logs out.
    signal.signal(signal.SIGHUP, signal.SIG_IGN)
    # Try to catch common signals and send email before we die
    signal.signal(signal.SIGINT, warn_of_signal)
    signal.signal(signal.SIGQUIT, warn_of_signal)
    signal.signal(signal.SIGTERM, warn_of_signal)

    try:
        # Tell Gratia what versions we are using.
        # CHRIS: is there a way to automate the version extraction
        #        using the pkg_resource package?
        Gratia.RegisterReporterLibrary("psycopg2", "2.0.6")
        #Gratia.RegisterReporterLibrary( "SQLAlchemy", "0.4.1" )
        rev = Gratia.ExtractCvsRevision("$Revision: 1.13 $")
        tag = Gratia.ExtractCvsRevision("$Name:  $")
        Gratia.RegisterReporter("dCacheBillingAggregator.py",
                                str(rev) + " (tag " + str(tag) + ")")

        # BRIAN: attempt to pull the dCache version from RPM.
        version = "UNKNOWN"
        try:
            version = os.popen("rpm -q --qf '%{VERSION}-%{RELEASE}' " \
                               "dcache-server").read()
        except:
            pass
        Gratia.RegisterService("dCache", version)

        # Initialize gratia before attempting to read its config file.
        Gratia.Initialize()
        # Extract the configuration information into local variables.
        myconf = dCacheProbeConfig()

        # Get the name of the directory where we are to store the log files.
        logDir = myconf.get_LogFolder()

        # Make sure that the logging directory is present
        if not os.path.isdir(logDir):
            os.mkdir(logDir, 0755)

        logFileName = os.path.join(logDir, "dcacheTransfer.log")

        # Set up an alarm to send an email if the program terminates.
        termSubject = "dCache-transfer probe is going down"
        termMessage = "The dCache transfer probe for Gratia has " + \
                      "terminated.\nPlease check the logfile\n\n   " + \
                      logFileName + \
                      "\n\nfor the cause.\n"

        terminationAlarm = Alarm(myconf.get_EmailServerHost(),
                                 myconf.get_EmailFromAddress(),
                                 myconf.get_EmailToList(), termSubject,
                                 termMessage, 0, 0, False)

        # Set up the logger with a suitable format
        hdlr = RotatingFileHandler(logFileName, 'a', 512000, 10)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr)
        logger.setLevel(myconf.get_AggrLogLevel())
        logger.info("starting " + ProgramName)

        stopFileName = myconf.get_StopFileName()
        updateFreq = float(myconf.get_UpdateFrequency())
        logger.warn("update freq = %.2f" % updateFreq)

        # Create the aggregator instance that we will use.
        dataDir = myconf.get_DataFolder()
        aggregator = DCacheAggregator(myconf, dataDir)

        # If profiling was requested, turn it on.
        profiling = sys.argv.count('-profile') > 0
        if profiling:
            profiler = hotshot.Profile("profile.dat")
            logger.info("Enabling Profiling")

        # Now aggregate new records, then sleep, until somebody creates
        # the stop file...
        while 1:
            # Make sure we (still) have a connection to Gratia.
            if (not TestContainer.isTest()
                ):  # no need in that during self test
                Gratia.Maintenance()

            if profiling:
                profiler.run("aggregator.sendBillingInfoRecordsToGratia()")
            else:
                try:
                    aggregator.sendBillingInfoRecordsToGratia()
                except TestContainer.SimInterrupt:
                    logger.info("BillingRecSimulator.SimInterrupt caught, " \
                        "restarting")
                    aggregator = DCacheAggregator(myconf, dataDir)
                    continue
            # Are we are shutting down?
            if os.path.exists(stopFileName):
                break

            if TestContainer.isTest():
                break

            logger.warn("sleeping for = %.2f seconds" % updateFreq)
            sleep_check(updateFreq, stopFileName)

        # If we are profiling, print the results...
        if profiling:
            profiler.close()
            stats = hotshot.stats.load("profile.dat")
            stats.sort_stats('time', 'calls')
            stats.print_stats()

        logger.warn(ProgramName + " stop file detected.")
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        # format the traceback into a string
        tblist = traceback.format_exception(sys.exc_type, sys.exc_value,
                                            sys.exc_traceback)
        msg = ProgramName + " caught an exception:\n" + "".join(tblist)
        print msg
        logger.error(msg)

    TestContainer.dumpStatistics(logger)

    # shut down the logger to make sure nothing is lost.
    logger.critical(ProgramName + " shutting down.")
    logging.shutdown()
    # try to send an email warning of the shutdown.
    if terminationAlarm != None:
        terminationAlarm.event()

    sys.exit(1)
"""
Created on Tue Jul 31 18:42:53 2018

@author: Sander Oosterveld
"""

from MainScreen import MainScreen
from Alarm import Alarm, AlarmWidget
from queue import Queue
from Widget import TimeWidget, TextWidget, Position
from TimerObject import TimerObject

q = Queue()
screen = MainScreen(q)
screen.changeBackground('white')
alarm = Alarm("0700", "disturbed.ogg", True)
alarmWidget = AlarmWidget(screen, alarm)
timeWidget = TimeWidget(screen)
alarmWidget.make()
timeWidget.make()

timerObject = TimerObject(screen)
timerObject.addObject(screen.changeBackground, ("2300", -1), "black")
timerObject.addObject(screen.changeBackground, ("0630", -1), "white")
timerObject.addAlarm(alarm)
print(timerObject.getObjects())
alarm.setRepeat((1,2,3,4))
timerObject.updateAlarm(alarm)
print(timerObject.getObjects())
#timerObject.addObject(alarm.activate, ("0600", -1))
Exemple #33
0
from flask import Flask

from Alarm import Alarm
from CeilingLights import CeilingLights
from Scheduler import make_scheduler
from Woodlamp import Woodlamp

app = Flask(__name__)
make_scheduler(app)

woodlamp = Woodlamp(app, '192.168.178.26')
alarm = Alarm(app, woodlamp)
ceiling = CeilingLights(app)

controllers = [woodlamp, alarm, ceiling]


@app.route('/')
def main_page():
    return '<hr />'.join(
        [controller.produce_main_page_content() for controller in controllers])


if __name__ == '__main__':
    app.run(host='0.0.0.0')
Exemple #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"
            )
Exemple #35
0
    def __init__(self):

        logging.info("Initializing ALMA_Tripod class")

        self.ini = ConfigParser.ConfigParser()
        self.ini.read('/opt/spinitalia/service/config.ini')

        # Istanzio le classi
        self.canopen = Canopen(self)
        self.alarm = Alarm(self)
        self.kinematic = Kinematic(self)

        self.posTime = 0.01

        self.almaPositionProtocol = None
        self.almaPositionProtocolMulticast = None

        self.last_sim = ""
        self.last_sim_file = None
        self.last_sim_time = 0.0
        self.last_sim_timestamp = 0.0

        # All'avvio il sistema si trova nello stato 99, Non autenticato
        self.canStatus = 99
        self.oldStatus = 98    # Forzo il primo update
        self.simHash = ''

        self.userLoggedIn = False
        self.isAsyncError = False

        # Inizializza le strutture
        self.motorsAddress = []
        self.motorPos = {'120': 0L, '121': 0L, '122': 0L, '119': 0L}
        self.OpProgress = 0
        self.isCentered = False
        self.isImporting = False
        self.isReadyToStart = False
        self.currentLine = 0
        self.mex_counter = 0L
        self.almaControlProtocol = None
        self.isReading = False

        self.antenna_weight = 50

        # Per evitare che vengano eseguiti comandi errati prima che il canopen abbia comunicato lo stato tramite la
        # pipe ( si sblocca con CT0 )
        self.init_done = False

        # Annulla l'importazione
        self.stopAnalysis = False

        self.password = "******"

        # Indirizzi dei motori
        self.motor_address_list = ['119', '120', '121', '122']

        # Calcolo della velocità
        self.old_roll = 0.0
        self.old_pitch = 0.0
        self.old_yaw = 0.0

        # Compila i cercatori
        self.find_motor_position = re.compile(
            '@M([^ ]*) S([^ ]*) @M([^ ]*) S([^ ]*) @M([^ ]*) S([^ ]*) @M([^ ]*) S([^ ]*) AS([^ ]*) T([^ ]*) C([^ ]*)'
        )

        # Per prima cosa aggiorno lo stato
        self.update_output()
Exemple #36
0
class Tripod:
    """Classe principale per la gestione del tripode.

    Per la gestione del tripode, sono necessarie tre distinte attivita':

      - Abilitazione dei segnali visivi e acustici in base allo stato
      - Esecuzione del programma canopen_server per la comunicazione con i motori
      - Avvio del server TCP per la comunicazione con il programma di controllo remoto

    Il controllo dei segnali visivi ed acustici avviene tramite bus i2c, mentre il loro
    stato dipende da quanto comunicato tramite PIPE dal canopen_server.

    Il dialogo con il programma di controllo dei motori avviene tramite stdin, stdout e PIPE.

    """

    def __init__(self):

        logging.info("Initializing ALMA_Tripod class")

        self.ini = ConfigParser.ConfigParser()
        self.ini.read('/opt/spinitalia/service/config.ini')

        # Istanzio le classi
        self.canopen = Canopen(self)
        self.alarm = Alarm(self)
        self.kinematic = Kinematic(self)

        self.posTime = 0.01

        self.almaPositionProtocol = None
        self.almaPositionProtocolMulticast = None

        self.last_sim = ""
        self.last_sim_file = None
        self.last_sim_time = 0.0
        self.last_sim_timestamp = 0.0

        # All'avvio il sistema si trova nello stato 99, Non autenticato
        self.canStatus = 99
        self.oldStatus = 98    # Forzo il primo update
        self.simHash = ''

        self.userLoggedIn = False
        self.isAsyncError = False

        # Inizializza le strutture
        self.motorsAddress = []
        self.motorPos = {'120': 0L, '121': 0L, '122': 0L, '119': 0L}
        self.OpProgress = 0
        self.isCentered = False
        self.isImporting = False
        self.isReadyToStart = False
        self.currentLine = 0
        self.mex_counter = 0L
        self.almaControlProtocol = None
        self.isReading = False

        self.antenna_weight = 50

        # Per evitare che vengano eseguiti comandi errati prima che il canopen abbia comunicato lo stato tramite la
        # pipe ( si sblocca con CT0 )
        self.init_done = False

        # Annulla l'importazione
        self.stopAnalysis = False

        self.password = "******"

        # Indirizzi dei motori
        self.motor_address_list = ['119', '120', '121', '122']

        # Calcolo della velocità
        self.old_roll = 0.0
        self.old_pitch = 0.0
        self.old_yaw = 0.0

        # Compila i cercatori
        self.find_motor_position = re.compile(
            '@M([^ ]*) S([^ ]*) @M([^ ]*) S([^ ]*) @M([^ ]*) S([^ ]*) @M([^ ]*) S([^ ]*) AS([^ ]*) T([^ ]*) C([^ ]*)'
        )

        # Per prima cosa aggiorno lo stato
        self.update_output()

    def cleanup(self):

        logging.info("De-Initializing ALMA_Tripod class")

        # Invia CT6, spegnimento
        #reactor.callFromThread(self.canopen.sendCommand, 'CT6', 'local')

        # Chiude lo streamer
        if 'almaPositionProtocolMulticast' in vars():
            if self.almaPositionProtocolMulticast.posSender:
                self.almaPositionProtocolMulticast.posSender.stop()

        # Chiude lo stream_reader
        if 'receiver_thread' in vars():
            self.receiver_thread.stop()

        # Chiude il processo di comunicazione con i motori se attivo
        if self.canopen:
            self.canopen.transport.closeStdin()

        # Chiude il reattore se attivo
        if reactor.running:
            logging.info("Stopping reactor")
            reactor.stop()

        # Solo per rimuovere l'interrupt sul GPIO
        self.alarm.cleanup()

    def start_canopen(self):

        # Avvio il server CANOPEN
        # usePTY serve ad evitare l'ECHO
        # INFO: uso stdbuf per evitare il buffering dell'output se non in terminale
        if self.ini.getboolean("System", "canopen_fake"):
            reactor.spawnProcess(
                self.canopen,
                "/usr/bin/stdbuf",
                args=[
                    "stdbuf",
                    "--output=L",
                    "--input=0",
                    "{}alma3d_canopenshell".format(self.ini.get("Path", "base_path")),
                    "fake",
                    "load#libcanfestival_can_socket.so,0,1M,8"
                ],
                env=os.environ,
                usePTY=False
            )
        else:
            reactor.spawnProcess(
                self.canopen,
                "/usr/bin/stdbuf",
                args=[
                    "stdbuf",
                    "--output=L",
                    "--input=0",
                    "{}alma3d_canopenshell".format(self.ini.get("Path", "base_path")),
                    "load#libcanfestival_can_socket.so,0,1M,8"
                ],
                env=os.environ,
                usePTY=False
            )

    def update_import_progress(self, value, line_num):

        self.OpProgress = value
        self.currentLine = line_num

    def update_import_end(self, filename):

        if not self.stopAnalysis:
            self.isImporting = False
            self.last_sim = filename
            if filename != "":
                self.isReadyToStart = True

    def stream_reader(self):

        # TODO: Deve ripartire automaticamente in caso di errore ed in caso di assenza di pipe!
        logging.info("Position reader thread started!")

        is_pipe_open = False

        motor_pos = {'120': 0L, '121': 0L, '122': 0L, '119': 0L}
        is_async_error = False
        can_status = 3
        is_centered = False
        op_progress = 0
        mex_counter = 0L
        pos_time = 0.0

        while self.isReading:
            if is_pipe_open:
                try:
                    line = pipein.readline()[:-1]
                    # print 'Parent %d got "%s" at %s' % (os.getpid(), line, time.time( ))
                    # line: @M119 S0 @M120 S0 @M121 S0 @M122 S0 AS4 T9 C0
                    canopen_status = self.find_motor_position.search(line)
                    if canopen_status:
                        motor_pos[canopen_status.group(1)] = canopen_status.group(2)
                        motor_pos[canopen_status.group(3)] = canopen_status.group(4)
                        motor_pos[canopen_status.group(5)] = canopen_status.group(6)
                        motor_pos[canopen_status.group(7)] = canopen_status.group(8)
                        # Se lo stato e' zero, vuol dire che c'e' una segnalazione pendente
                        if canopen_status.group(9) == '0' and is_async_error is False:
                            is_async_error = True
                        elif canopen_status.group(9) != '0':
                            try:
                                can_status = int(canopen_status.group(9))
                            except ValueError:
                                can_status = 97
                                logging.error("Impossibile convertire lo stato {}".format(can_status))
                            if not is_centered:
                                if can_status == 6:
                                    is_centered = True
                        # pos_time = float(canopen_status.group(10))
                        pos_time = 0.01
                        op_progress = canopen_status.group(11)
                        mex_counter += 1

                    reactor.callFromThread(
                        self.update_var_from_canopen, motor_pos, is_async_error, can_status, is_centered,
                        pos_time, op_progress, mex_counter
                    )

                except Exception, e:

                    # Potrebbe essere semplicemente non disponibile un dato!
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    logging.error("Disabling Alarm, device not found! (%s)" % str(e))
                    traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)

                    is_pipe_open = False
                    logging.info("Pipe closed!")

            else:

                # Questa devo analizzarla meglio
                try:
                    if self.ini.get("System", "canopen_fake"):
                        if os.path.exists(self.ini.get("Path", "pipe_position_fake")):
                            mode = os.stat(self.ini.get("Path", "pipe_position_fake")).st_mode
                            if stat.S_ISFIFO(mode):
                                pipein = open(self.ini.get("Path", "pipe_position_fake"), 'r')
                                is_pipe_open = True
                                continue
                    else:
                        if os.path.exists(self.ini.get("Path", "pipe_position")):
                            mode = os.stat(self.ini.get("Path", "pipe_position")).st_mode
                            if stat.S_ISFIFO(mode):
                                pipein = open(self.ini.get("Path", "pipe_position"), 'r')
                                is_pipe_open = True
                                continue
                    sleep(0.5)

                except:

                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    logging.error("Impossibile inviare lo stato (%s)" % sys.exc_info()[0])
                    traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
Exemple #37
0
settings_data = config.SETTINGS

radio_channels = None

with open(radio_config) as data_file:
    radio_data = json.load(data_file)

if "channels" in radio_data:
    radio_channels = radio_data['channels']

p = Radio(radio_channels=radio_channels, mplayer_path=config.MPLAYER_PATH)
if "radio" in settings_data:
    _radio_settings = settings_data['radio']
    p.change_country(_radio_settings['country'])
    if "radio_stations" in _radio_settings and len(
            _radio_settings['radio_stations']) > 0:
        p.radio_channels.extend(_radio_settings['radio_stations'])

web_frontend.radio = p
alarm = Alarm("res/sounds/Argon_48k.wav", settings=settings_data)
alarm.create_alarms()

web_frontend.alarm = alarm

last_state = config.load_last_state()
if last_state is not None:
    p.set_channel(last_state["last_radio_station"])
    gui.current_page = last_state["last_page"]

tingbot.run(loop)