def move_robot(request): data = dict() if LaboremGroupInputPermission.objects.count() > 0: for group in request.user.groups.iterator(): if LaboremGroupInputPermission.objects.get(hmi_group=group).move_robot: try: variable = Variable.objects.get(name="LABOREM") except Variable.DoesNotExist: return HttpResponse(status=200) vp = VariableProperty.objects.get_property(variable=variable, name="ROBOT_PUT_ON") if vp is None: return HttpResponse(status=200) key = vp.id for base in LaboremRobotBase.objects.all(): if base.element is not None and str(base.element.active) == '0': VariableProperty.objects.update_or_create_property(Variable.objects.get(name="LABOREM"), "message_laborem", "Le robot place les éléments...", value_class='string', timestamp=now()) data['message_laborem'] = {} data['message_laborem']['message'] = "Le robot place les éléments..." data['message_laborem']['timestamp'] = int(format(now(), 'U')) * 1000 cwt = DeviceWriteTask(variable_property_id=key, value=1, start=time.time(), user=request.user) cwt.create_and_notificate(cwt) return HttpResponse(json.dumps(data), content_type='application/json') return HttpResponse(status=200)
def form_write_task(request): if not request.user.is_authenticated(): return redirect('/accounts/login/?next=%s' % request.path) if 'var_id' in request.POST and 'value' in request.POST: cwt = DeviceWriteTask(variable_id=request.POST['var_id'], value=request.POST['value'], start=time.time(), user=request.user) cwt.save() return HttpResponse(status=200) else: return HttpResponse(status=404)
def relay(self, value=True): io_config = self.MotherboardIOConfig if io_config.pin5 is not None and io_config.pin5.gpio_variable is not None: io_config.pin5.gpio_variable.refresh_from_db() last_element = RecordedData.objects.last_element( variable=io_config.pin5.gpio_variable, time_min=0) if last_element is not None and int( last_element.value()) != int(value): logger.debug("Switching relay to " + str(int(value))) cwt = DeviceWriteTask( variable_id=io_config.pin5.gpio_variable.pk, value=value, start=time.time(), user=None) cwt.create_and_notificate(cwt) return True elif last_element is None: logger.debug("No last relay config, switching relay to 1") cwt = DeviceWriteTask( variable_id=io_config.pin5.gpio_variable.pk, value=1, start=time.time(), user=None) cwt.create_and_notificate(cwt) return True else: return False else: logger.debug('Laborem relay pin not defined !') return False
def form_write_task(request): if not request.user.is_authenticated(): return redirect('/accounts/login/?next=%s' % request.path) if 'key' in request.POST and 'value' in request.POST: key = int(request.POST['key']) item_type = request.POST['item_type'] if item_type == 'variable': cwt = DeviceWriteTask(variable_id=key, value=request.POST['value'], start=time.time(), user=request.user) cwt.save() return HttpResponse(status=200) elif item_type == 'variable_property': cwt = DeviceWriteTask(variable_property_id=key, value=request.POST['value'], start=time.time(), user=request.user) cwt.save() return HttpResponse(status=200) return HttpResponse(status=404)
def write_value_to_device(self, variable_name, value, time_start=None, user=None, blocking=False, timeout=60): """ :param timeout: :param variable_name: :param value: :param time_start: :param user: instance of the writing user, default is None :param blocking: wait until write succeeded :return: """ if time_start is None: time_start = time() if variable_name in self.variables: variable = self.variables[variable_name] else: variable = Variable.objects.filter(name=variable_name).first() self.variables[variable_name] = variable if not variable: # todo throw exception return False if not variable.writeable: # todo throw exception return False dwt = DeviceWriteTask(variable=variable, value=value, start=time_start, user=user) dwt.save() if blocking: timeout = max(time(), time_start) + timeout while timeout < time(): dwt.refresh_from_db() if dwt.done(): return True return False else: return True
def form_write_task(request): if 'key' in request.POST and 'value' in request.POST: key = int(request.POST['key']) item_type = request.POST['item_type'] value = request.POST['value'] #logger.debug("key : %s - value %s - type %s" % (key, value, item_type)) # check if float as DeviceWriteTask doesn't support string values try: float(value) except ValueError: logger.debug("form_write_task input is not a float") return HttpResponse(status=403) if GroupDisplayPermission.objects.count() == 0: if item_type == 'variable': cwt = DeviceWriteTask(variable_id=key, value=value, start=time.time(), user=request.user) cwt.create_and_notificate(cwt) return HttpResponse(status=200) elif item_type == 'variable_property': cwt = DeviceWriteTask(variable_property_id=key, value=value, start=time.time(), user=request.user) cwt.create_and_notificate(cwt) return HttpResponse(status=200) else: if item_type == 'variable': if GroupDisplayPermission.objects.filter( hmi_group__in=request.user.groups.iterator(), control_items__type=0, control_items__variable__pk=key): cwt = DeviceWriteTask(variable_id=key, value=value, start=time.time(), user=request.user) cwt.create_and_notificate(cwt) return HttpResponse(status=200) else: logger.debug( "Missing group display permission for write task variable" ) elif item_type == 'variable_property': if GroupDisplayPermission.objects.filter( hmi_group__in=request.user.groups.iterator(), control_items__type=0, control_items__variable_property__pk=key): cwt = DeviceWriteTask(variable_property_id=key, value=value, start=time.time(), user=request.user) cwt.create_and_notificate(cwt) return HttpResponse(status=200) else: logger.debug( "Missing group display permission for write task VP") else: logger.debug("key or value missing in request : %s" % request.POST) return HttpResponse(status=404)
def form_write_task(request): if 'key' in request.POST and 'value' in request.POST: key = int(request.POST['key']) item_type = request.POST['item_type'] value = request.POST['value'] # check if float as DeviceWriteTask doesn't support string values try: float(value) except ValueError: logger.debug("form_write_task input is not a float") return HttpResponse(status=403) if GroupDisplayPermission.objects.count() == 0: if item_type == 'variable': cwt = DeviceWriteTask(variable_id=key, value=value, start=time.time(), user=request.user) cwt.save() return HttpResponse(status=200) elif item_type == 'variable_property': cwt = DeviceWriteTask(variable_property_id=key, value=value, start=time.time(), user=request.user) cwt.save() return HttpResponse(status=200) else: for group_user in request.user.groups.iterator(): if item_type == 'variable': for group in GroupDisplayPermission.objects.filter(hmi_group=group_user, control_items__type=5, control_items__variable__pk=key): cwt = DeviceWriteTask(variable_id=key, value=value, start=time.time(), user=request.user) cwt.save() return HttpResponse(status=200) elif item_type == 'variable_property': for group in GroupDisplayPermission.objects.filter(hmi_group=group_user, control_items__type=5, control_items__variable_property__pk=key): cwt = DeviceWriteTask(variable_property_id=key, value=value, start=time.time(), user=request.user) cwt.save() return HttpResponse(status=200) return HttpResponse(status=404)
def write_data(self, variable_id, value): """ write values to the device """ i = 0 j = 0 while i < 10: try: self.inst.query('*IDN?') logger.info("Visa-MDO3014-Write- variable_id : %s et value : %s" %(variable_id, value)) i = 12 j = 1 except: self.connect() time.sleep(1) i += 1 logger.error("MDO3014 connect error i : %s" % i) if j == 0: logger.error("MDO3014-Instrument not connected") return None if variable_id == 'init_BODE': self.inst.read_termination = '\n' # Reset and init Osc Vepp = RecordedData.objects.last_element(variable__name='BODE_Vpp') # self.inst.write('*CLS') self.inst.write('*RST;:SEL:CH1 1;:SEL:CH2 1;:HORIZONTAL:POSITION 0;:CH1:YUN "V";:CH1:SCALE ' + str(1.2*float(Vepp.value())/(2*4))+';:CH2:YUN "V";:CH2:BANdwidth 10000000;:' 'CH1:BANdwidth 10000000;:TRIG:A:TYP EDGE;' ':TRIG:A:EDGE:COUPLING DC;:TRIG:A:EDGE:SOU CH1;' ':TRIG:A:EDGE:SLO FALL;:TRIG:A:MODE NORM') return True elif variable_id == 'find_phase': # N = int(RecordedData.objects.last_element(variable__name='BODE_n').value()) # if N == 1: # time.sleep(1) i = 0 F = RecordedData.objects.last_element(variable__name='BODE_F') while F is None and i<10: F = RecordedData.objects.last_element(variable__name='BODE_F') i += 1 Vsff = value Vsmax = float(Vsff)*float(math.sqrt(2)) CMD = str(':HORIZONTAL:SCALE '+str(round(float(float(4)/(float(10)*float(F.value()))), 6))+';:CH2:SCALE ' + str(1.4*float(Vsmax)/4)+';:TRIG:A:LEV:CH1 '+str(0.8*float(Vsmax)) + ';:MEASUrement:IMMed:SOUrce1 CH1;:MEASUrement:IMMed:SOUrce2 CH2;:MEASUREMENT:IMMED:TYPE PHASE') self.inst.write(CMD) time.sleep(20/F.value()) CMD = str(':MEASUREMENT:IMMED:VALUE?') Phase = [] for k in range(1, 4): # TODO : put a try to prevent if the read is not a float Phase.append(float(self.inst.query(CMD))) time.sleep(0.1) MeanPhase = np.mean(Phase) StDevPhase = np.std(Phase) logger.info("Phase : %s - Mean : %s - StDev : %s" %(Phase, MeanPhase, StDevPhase)) i=0 while (float(MeanPhase) > 100000 or StDevPhase > 3) and i<10: logger.info("Calculate Phase again") Phase = [] for k in range(1,4): Phase.append(float(self.inst.query(CMD))) time.sleep(0.1) MeanPhase = np.mean(Phase) StDevPhase = np.std(Phase) logger.info("Phase : %s - Mean : %s - StDev : %s" %(Phase,MeanPhase,StDevPhase)) i += 1 time.sleep((1+i)/10) cwt = DeviceWriteTask(variable__name='Find_Gain_Osc', value=1, start=time.time()) cwt.save() # self.write_data("find_gain", 1) return self.parse_value(MeanPhase) elif variable_id == 'find_gain': CMD = str(':MEASUrement:IMMed:SOUrce1 CH1;:MEASUREMENT:IMMED:TYPE PK2PK;:MEASUREMENT:IMMED:VALUE?') P2P1 = self.inst.query(CMD) try: float(P2P1) i = 12 except: i = 0 logger.error("i : %s" % i) while i < 10: try: P2P1 = self.inst.query('MEASUREMENT:IMMED:VALUE?') logger.info("P2P1 : %s" % P2P2) float(P2P1) i =12 except: i += 1 logger.error("P2P1 - i : %s" % i) CMD = str(':MEASUrement:IMMed:SOUrce1 CH2;:MEASUREMENT:IMMED:TYPE PK2PK;:MEASUREMENT:IMMED:VALUE?') P2P2 = self.inst.query(CMD) try: float(P2P2) i = 12 except: i = 0 logger.error("i : %s" %(i)) while i < 10: try: P2P2 = self.inst.query('MEASUREMENT:IMMED:VALUE?') logger.info("P2P2 : %s" % P2P2) float(P2P2) i =12 except: i += 1 logger.error("P2P2 - i : %s" % i) try: float(P2P2) float(P2P1) except: return None G = 20*log10(float(P2P2)/float(P2P1)) # self.inst.write('SELect:CH1 0') # self.inst.write('SELect:CH2 0') N = RecordedData.objects.last_element(variable__name='BODE_n').id N_new = N.value() + 1 F = RecordedData.objects.last_element(variable__name='BODE_F').id Fmin = RecordedData.objects.last_element(variable__name='BODE_Fmin').id Fmax = RecordedData.objects.last_element(variable__name='BODE_Fmax').id nb_points = RecordedData.objects.last_element(variable__name='BODE_nb_points').id # Variation de F en log k=pow(Fmax.value()/Fmin.value(),(N_new-11)/(nb_points.value()-1)) F_new = Fmin.value()*pow(Fmax.value()/Fmin.value(),(N_new-1)/(nb_points.value()-1)) F_new = int(F_new) # logger.info("N_new : %s - k : %s - F : %s" %(N_new, k, F_new)) # Variation F linéaire # F_new = F.value() + (Fmax.value() - Fmin.value())/nb_points.value() if F_new > Fmax.value(): logger.info("BODE terminé") else: cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='BODE_F').id, value=F_new, start=time.time()) cwt.save() cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='BODE_n').id, value=N_new, start=time.time()) cwt.save() cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='Set_Freq_GBF').id, value=F_new, start=time.time()) cwt.save() return self.parse_value(G) return self.parse_value(self.inst.query(str(variable_id)+' '+str(value)))
def import_xml_config_file(filename): ''' read xml file content and write/update the model data ''' from xml.dom.minidom import parse with open(filename, "r") as file_: xml_doc = parse(file_) doc_node = xml_doc.documentElement doc_version = doc_node.getAttribute('version') objects = doc_node.getElementsByTagName('object') def _parse_field(): if field.hasAttribute('type'): _type = field.getAttribute('type') else: _type = 'string' field_name = field.getAttribute('name') values[field_name] = _cast(field.firstChild.nodeValue,_type) # read all objects _Devices = [] _Variables = [] _Units = [] _Colors = [] _DeviceWriteTask = [] for obj in objects: obj_name = obj.getAttribute('name') fields = obj.getElementsByTagName('field') values = {} if not obj.hasAttribute('id'): continue values['id'] = int(obj.getAttribute('id')) for field in fields: _parse_field() if obj_name.upper() in ['DEVICE']: _Devices.append(values) elif obj_name.upper() in ['VARIABLE']: _Variables.append(values) elif obj_name.upper() in ['UNIT']: _Units.append(values) elif obj_name.upper() in ['COLOR']: _Colors.append(values) elif obj_name.upper() in ['DEVICEWRITETASK']: _DeviceWriteTask.append(values) ## update/import Devices ################################################### for entry in _Devices: # Device (object) cc, created = Device.objects.get_or_create(pk = entry['id'],defaults={'id':entry['id'],'short_name':entry['name'],'description':entry['description'],'protocol':entry['protocol'],'active':entry['active']}) if created: log.info(("created device: %s") %(entry['name'])) else: cc.short_name = entry['name'] cc.description = entry['description'] cc.protocol = entry['protocol'] cc.active = entry['active'] cc.save() log.info(("updated device: %s (%d)") %(entry['name'],entry['id'])) # modbus config if entry.has_key('modbus.protocol') and entry.has_key('modbus.ip_address') and entry.has_key('modbus.port') and entry.has_key('modbus.unit_id'): # get protocol choice id protocol_choices = ModbusDevice._meta.get_field('protocol').choices for prtc in protocol_choices: if entry['modbus.protocol'] == prtc[1]: entry['modbus.protocol'] = prtc[0] if hasattr(cc,'modbusdevice'): cc.modbusdevice.ip_address = entry['modbus.ip_address'] cc.modbusdevice.port = entry['modbus.port'] cc.modbusdevice.unit_id = entry['modbus.unit_id'] cc.modbusdevice.protocol = entry['modbus.protocol'] cc.modbusdevice.save() else: mc = ModbusDevice(modbus_device=cc,ip_address=entry['modbus.ip_address'],port=entry['modbus.port'],protocol=entry['modbus.protocol'],unit_id=entry['modbus.unit_id']) mc.save() # Unit (object) for entry in _Units: # unit config uc, ucc = Unit.objects.get_or_create(pk = entry['id'],defaults={'id':entry['id'],'unit':entry['unit'],'description':entry['description'],'udunit':entry['udunit']}) if not created: uc.unit = entry['unit'] uc.description = entry['description'] uc.udunit = entry['udunit'] uc.save() # Color (object) for entry in _Colors: # unit config cc, ucc = Color.objects.get_or_create(pk = entry['id'],defaults={'id':entry['id'],'name':entry['name'],'R':entry['R'],'G':entry['G'],'B':entry['B']}) if not created: cc.name = entry['name'], cc.R = entry['R'] cc.G = entry['G'] cc.B = entry['B'] cc.save() # Variable (object) for entry in _Variables: vc, created = Variable.objects.get_or_create(pk=entry['id'], defaults={\ 'id':entry['id'],\ 'name':entry['name'],\ 'description': entry['description'],\ 'device_id':entry['device_id'],\ 'active':entry['active'],\ 'writeable':entry['writeable'],\ 'record':entry['record'],\ 'unit_id':entry['unit_id'],\ 'value_class':validate_value_class(entry["value_class"]) # TODO UNIXTIME ?? \ }) if created: log.info(("created variable: %s") %(entry['name'])) else: log.info(("updated variable: %s") %(entry['name'])) vc.name = entry['name'] vc.description = entry['description'] vc.device_id = entry['device_id'] vc.active =entry['active'] vc.writeable = entry['writeable'] vc.record = entry['record'] vc.unit_id = entry['unit_id'] vc.value_class = validate_value_class(entry["value_class"]) vc.save() if entry.has_key("hmi.chart_line_color_id"): vc.chart_line_color_id = entry["hmi.chart_line_color_id"] if entry.has_key("hmi.short_name"): vc.short_name = entry["hmi.short_name"] if entry.has_key("hmi.chart_line_thickness"): vc.chart_line_thickness = entry["hmi.chart_line_thickness"] vc.save() if hasattr(vc,'modbusvariable'): if entry.has_key("modbus.address"): vc.modbusvariable.address = entry["modbus.address"] if entry.has_key("modbus.function_code_read"): vc.modbusvariable.function_code_read = entry["modbus.function_code_read"] vc.modbusvariable.save() else: if entry.has_key("modbus.address") and entry.has_key("modbus.function_code_read"): ModbusVariable(modbus_variable=vc,address=entry["modbus.address"],function_code_read=entry["modbus.function_code_read"]).save() for entry in _DeviceWriteTask: # start if isinstance(entry['start'],basestring): # must be convertet from local datestr to datenum timestamp = time.mktime(datetime.datetime.strptime(entry['start'], "%d-%b-%Y %H:%M:%S").timetuple()) else: # is already datenum timestamp = entry['start'] # verify timestamp if timestamp < time.time(): continue # user user = User.objects.filter(username = entry['user']) if user: user = user.first() else: user = None # variable variable = Variable.objects.filter(name=entry['variable'],active=1,device__active=1) if variable: # check for duplicates dcwt = DeviceWriteTask.objects.filter(variable=variable.first(),value=entry['value'],user=user,start__range=(timestamp-2.5,timestamp+2.5)) if dcwt: continue # write to DB DeviceWriteTask(variable=variable.first(),value=entry['value'],user=user,start=timestamp).save()
def write_data(self, variable_id, value): """ write values to the device """ i = 0 j = 0 while i < 10: try: self.inst.query('*IDN?') # logger.info("Visa-AFG1022-Write-variable_id : %s et value : %s" %(variable_id, value)) i = 12 j = 1 except: self.connect() time.sleep(1) i += 1 logger.error("AFG1022 connect error i : %s" %i) if j == 0: logger.error("AFG1022-Instrument not connected") return None if variable_id == 'init_BODE': # N try: N = int(RecordedData.objects.last_element(variable_id=Variable.objects.get(name='BODE_n').id).value()) except: N = 0 logger.error('AFG1022 cannot load N') if N == 0: # Set N to 1 cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='BODE_n').id, value=1, start=time.time()) cwt.save() # ReCall init GBF cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='Init_BODE_GBF').id, value=1, start=time.time()) cwt.save() return None elif N == 1: self.inst.read_termination = '\n' # Récup de Ve Vepp = RecordedData.objects.last_element(variable_id=Variable.objects.get(name='BODE_Vpp').id).value() # Fmin Fmin = RecordedData.objects.last_element(variable_id=Variable.objects.get(name='BODE_Fmin').id).value() # Call Range MM cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='Set_AC_Range_and_Resolution_and_Measure_MM').id, value=Vepp, start=time.time()) cwt.save() # Call Init Osc cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='Init_BODE_Osc').id, value=1, start=time.time()) cwt.save() # Reset GBF CMD = str('*RST;OUTPut1:STATe ON;OUTP1:IMP MAX;SOUR1:AM:STAT OFF;SOUR1:FUNC:SHAP SIN;SOUR1:VOLT:LEV:IMM:AMPL '+str(Vepp)+'Vpp') self.inst.write(CMD) # self.inst.write('*CLS') # Set F value cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='BODE_F').id, value=Fmin, start=time.time()) cwt.save() # Call Set Freq GBF # cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='Set_Freq_GBF').id, value=Fmin, start=time.time()) # cwt.save() self.write_data("set_freq", Fmin) return True else: cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='Init_BODE_GBF').id, value=1, start=time.time()) cwt.save() logger.info("Init GBF - N : %s" %N) return False return None elif variable_id == 'set_freq': # Define Freq self.inst.write('SOUR1:FREQ:FIX '+str(value)) # Call Read MM cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='Read_MM_acual_value').id, value=1, start=time.time()) cwt.save() return self.parse_value(value) elif variable_id == 'set_tension': # Define tension self.inst.write('SOUR1:VOLT:LEV:IMM:AMPL '+str(value)+'Vpp') # F = Fmin F = RecordedData.objects.last_element(variable_id=Variable.objects.get(name='BODE_Fmin').id).value() # Set F value cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='BODE_F').id, value=F, start=time.time()) cwt.save() # Call Set Freq GBF cwt = DeviceWriteTask(variable_id=Variable.objects.get(name='Set_Freq_GBF').id, value=F, start=time.time()) cwt.save() return self.parse_value(value) elif variable_id == 'return_value': return self.parse_value(value) elif variable_id == 'reboot': import os os.system('sudo reboot') return 1 else: return self.parse_value(self.inst.query(str(variable_id)+' '+str(value))) return None
def change_selected_plug(self, plug, sub_plug=None, user=None): plug_device = self._get_selected_plug(str(plug)) if plug_device is None: #logger.debug("Plug device not found %s" % str(plug)) return False io_config = self.MotherboardIOConfig if sub_plug: plug_device.switch1_value = plug_device.laboremsubplugdevice_set.get( pk=sub_plug).switch1_value plug_device.switch2_value = plug_device.laboremsubplugdevice_set.get( pk=sub_plug).switch2_value plug_device.switch3_value = plug_device.laboremsubplugdevice_set.get( pk=sub_plug).switch3_value plug_device.switch4_value = plug_device.laboremsubplugdevice_set.get( pk=sub_plug).switch4_value else: io_config.switch1 = None io_config.switch2 = None io_config.switch3 = None io_config.switch4 = None cwts = [] if io_config.switch1 is not None: cwt = DeviceWriteTask( variable_id=io_config.switch1.gpio_variable.pk, value=plug_device.switch1_value, start=time.time(), user=user) cwts.append(cwt) if io_config.switch2 is not None: cwt = DeviceWriteTask( variable_id=io_config.switch2.gpio_variable.pk, value=plug_device.switch2_value, start=time.time(), user=user) cwts.append(cwt) if io_config.switch3 is not None: cwt = DeviceWriteTask( variable_id=io_config.switch3.gpio_variable.pk, value=plug_device.switch3_value, start=time.time(), user=user) cwts.append(cwt) if io_config.switch4 is not None: cwt = DeviceWriteTask( variable_id=io_config.switch4.gpio_variable.pk, value=plug_device.switch4_value, start=time.time(), user=user) cwts.append(cwt) if io_config.pin1 is not None: cwt = DeviceWriteTask(variable_id=io_config.pin1.gpio_variable.pk, value=int(bin(plug - 1)[2:].zfill(4)[3:4]), start=time.time(), user=user) cwts.append(cwt) if io_config.pin2 is not None: cwt = DeviceWriteTask(variable_id=io_config.pin2.gpio_variable.pk, value=int(bin(plug - 1)[2:].zfill(4)[2:3]), start=time.time(), user=user) cwts.append(cwt) if io_config.pin3 is not None: cwt = DeviceWriteTask(variable_id=io_config.pin3.gpio_variable.pk, value=int(bin(plug - 1)[2:].zfill(4)[1:2]), start=time.time(), user=user) cwts.append(cwt) if io_config.pin4 is not None: cwt = DeviceWriteTask(variable_id=io_config.pin4.gpio_variable.pk, value=int(bin(plug - 1)[2:].zfill(4)[0:1]), start=time.time(), user=user) cwts.append(cwt) if len(cwts): cwts[0].create_and_notificate(cwts) logger.debug("demandé " + str(plug)) count = 0 while plug is not None and count < 50: if self._get_selected_plug_key() is not None and int(plug) == int( self._get_selected_plug_key()): break #logger.debug("plug !=") count += 1 time.sleep(0.5) logger.debug("ok " + str(self._get_selected_plug_key())) count = 0 while sub_plug is not None and count < 50: if self._get_selected_sub_plug() is not None and int( sub_plug) == int(self._get_selected_sub_plug()): break #logger.debug("sub plug !=") count += 1 time.sleep(0.1) return True
def loop(self): # data from a write data = [] # process webservice task if len(self.ws_write_todo) > 0: for ws_id in self.ws_write_todo: WebServiceAction.objects.get(id=ws_id).write_data() cwt = DeviceWriteTask( variable_id=WebServiceAction.objects.get( id=ws_id).write_trigger.pk, value=0, start=time(), user=DeviceWriteTask.objects.filter( done=True, variable=WebServiceAction.objects.get( id=ws_id).write_trigger).latest('start').user) cwt.create_and_notificate(cwt) self.ws_write_todo = [] # process write tasks # Do all the write task for this device starting with the oldest for task in DeviceWriteTask.objects.filter( Q( done=False, start__lte=time(), failed=False, ) & (Q(variable__device_id=self.device_id) | Q(variable_property__variable__device_id=self.device_id)) ).order_by('start'): if task.variable.scaling is not None: task.value = task.variable.scaling.scale_output_value( task.value) tmp_data = self.device.write_data(task.variable.id, task.value, task) if isinstance(tmp_data, list): if len(tmp_data) > 0: if hasattr(task.variable, 'webservicevariable') and task.value: for ws in task.variable.ws_write_trigger.filter( active=1, webservice_RW=1, write_trigger=task.variable): self.ws_write_todo.append(ws.pk) task.done = True task.finished = time() task.save() data.append(tmp_data) else: task.failed = True task.finished = time() task.save() else: task.failed = True task.finished = time() task.save() if isinstance(data, list): if len(data) > 0: return 1, data device_read_tasks = DeviceReadTask.objects.filter( Q( done=False, start__lte=time(), failed=False, ) & (Q(device_id=self.device_id) | Q(variable__device_id=self.device_id) | Q(variable_property__variable__device_id=self.device_id))) if time() - self.last_query > self.dt_query_data or len( device_read_tasks): self.last_query = time() # Query data if self.device is not None: tmp_data = self.device.request_data() if isinstance(tmp_data, list): if len(tmp_data) > 0: device_read_tasks.update(done=True, finished=time()) return 1, [ tmp_data, ] device_read_tasks.update(failed=True, finished=time()) return 1, None