def create_rule_actions(eventDescriptors=[]): enough = False ruleActions = [] while not enough: print "\n========================================================" raw_input("-> Press \"enter\" to create rule actions! ") deviceId = devices.select_configured_device() if not deviceId: return None device = devices.get_device(deviceId) if not device: return None actionType = actions.select_actionType(device['deviceClassId']) if not actionType: continue params = read_ruleActionParams(actionType['paramTypes'], eventDescriptors) action = {} action['deviceId'] = deviceId action['actionTypeId'] = actionType['id'] if len(params) > 0: action['ruleActionParams'] = params ruleActions.append(action) input = raw_input("Do you want to add another action? (y/N): ") if not input == "y": enough = True return ruleActions
def main(): # User arguments args = parse_args() # Datasets and dataloaders img_data = setup_data(args.data_dir) # Build, train and save the model architecture = args.arch if args.arch else "vgg13" device = get_device("GPU" if args.gpu else "CPU") model, optimizer = setup_model( architecture, img_data['datasets'], img_data['dataloaders'], lr=args.learning_rate if args.learning_rate else 0.002, hidden_units=args.hidden_units) train_model(model, optimizer, img_data['dataloaders']['train'], img_data['dataloaders']['valid'], epochs=args.epochs if args.epochs else 1, device=device) if args.save_dir: save_model(args.save_dir, model, architecture, optimizer, img_data['datasets']['train'], device=device)
def getStateDescriptorString(stateDescriptor): global stateEvaluatorString stateDescriptorString = "" if not stateDescriptor: return None if not 'deviceId' in stateDescriptor: return stateDescriptorString if not 'operator' in stateDescriptor: return stateDescriptorString if not 'stateTypeId' in stateDescriptor: return stateDescriptorString if not 'value' in stateDescriptor: return stateDescriptorString device = devices.get_device(stateDescriptor['deviceId']) stateType = get_stateType(stateDescriptor['stateTypeId']) operator = nymea.get_valueOperator_string(stateDescriptor['operator']) return (" %s:%s %s %s " % (device['name'], stateType['displayName'], operator, stateDescriptor['value']))
def train_model(model, optimizer, train_loader, valid_loader, epochs=1, print_every=5, device=None): # Send model to GPU or CPU if not device: device = get_device('gpu') model.to(device) # Setup negative log probability for log softmax criterion = nn.NLLLoss() # Run through training epochs steps = 0 running_loss = 0 for epoch in range(epochs): for inputs, labels in train_loader: steps += 1 # Move input and label tensors to the default device inputs, labels = inputs.to(device), labels.to(device) optimizer.zero_grad() logps = model.forward(inputs) loss = criterion(logps, labels) loss.backward() optimizer.step() running_loss += loss.item() if steps % print_every == 0: valid_loss = 0 accuracy = 0 model.eval() with torch.no_grad(): for inputs, labels in valid_loader: inputs, labels = inputs.to(device), labels.to(device) logps = model.forward(inputs) batch_loss = criterion(logps, labels) valid_loss += batch_loss.item() # Calculate accuracy ps = torch.exp(logps) top_p, top_class = ps.topk(1, dim=1) equals = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equals.type( torch.FloatTensor)).item() # output the loss print(f""" Epoch {epoch + 1}/{epochs} Training loss: {running_loss / print_every:.3f} Validation loss: {valid_loss / len(valid_loader):.3f} Validation accuracy: {accuracy / len(valid_loader):.3f} """) running_loss = 0 model.train()
def print_stateEvaluator(stateEvaluator): if not stateEvaluator: return None if 'stateDescriptor' in stateEvaluator: stateType = get_stateType( stateEvaluator['stateDescriptor']['stateTypeId']) deviceName = devices.get_full_device_name( stateEvaluator['stateDescriptor']['deviceId']) print "%5s. -> %40s -> state: \"%s\"" % (0, deviceName, stateType['name']) print "%50s %s %s" % (stateType['name'], guh.get_valueOperator_string( stateEvaluator['stateDescriptor']['operator'] ), stateEvaluator['stateDescriptor']['value']) else: if not 'childEvaluators' in stateEvaluator: return None for i in range(len(stateEvaluator['childEvaluators'])): device = devices.get_device(stateEvaluator['childEvaluators'][i] ['stateDescriptor']['deviceId']) stateType = get_stateType(stateEvaluator['childEvaluators'][i] ['stateDescriptor']['stateTypeId']) print "(%s:%s" % (device['name'], stateType['name']), print guh.get_valueOperator_string( stateEvaluator['childEvaluators'][i]['stateDescriptor'] ['operator']), print stateEvaluator['childEvaluators'][i]['stateDescriptor'][ 'value'], ")", if i != (len(stateEvaluator['childEvaluators']) - 1): print "%s%s" % ( guh.get_stateEvaluator_string(stateEvaluator['operator']), guh.get_stateEvaluator_string(stateEvaluator['operator'])), print "\n"
def print_stateType(): deviceId = devices.select_configured_device() device = devices.get_device(deviceId) if device == None: return None stateType = select_stateType(device['deviceClassId']) if stateType == None: return None guh.print_json_format(stateType)
def print_eventType(): deviceId = devices.select_configured_device() device = devices.get_device(deviceId) if not device: return None eventType = select_eventType(device['deviceClassId']) if not eventType: print "\n This device has no events" return None nymea.print_json_format(eventType)
def print_actionList(actionList): for i in range(len(actionList)): action = actionList[i] device = devices.get_device(action['deviceId']) actionType = get_actionType(actionList[i]['actionTypeId']) actionParams = actionList[i]['params'] print "%5s. -> %40s -> action: \"%s\"" % (i, device['name'], actionType['displayName']) for i in range(len(actionParams)): print "%50s: %s" % (actionParams[i]['displayName'], actionParams[i]['value'])
def print_actionType(): deviceId = devices.select_configured_device() if deviceId == None: return None device = devices.get_device(deviceId) actionType = select_actionType(device['deviceClassId']) #print nymea.print_json_format(actionType) if actionType == None: print "\n This device has no actions" return None actionType = get_actionType(actionType['id']) nymea.print_json_format(actionType)
def get_device_name(entry): global deviceIdCache deviceName = None name = None if entry['deviceId'] in deviceIdCache: deviceName = deviceIdCache[entry['deviceId']] else: device = devices.get_device(entry['deviceId']) deviceName = device['name'] deviceIdCache[entry['deviceId']] = deviceName return deviceName
def hopper(self): interface = devices.get_device(self.mInterface) s = nl.nl_socket_alloc(timeout=1) # Repeat until program exits. while globalsx.gALIVE: start = time.time() try: if len(globalsx.gFILTERCHANNEL) != len(self.mTarget): channel = choice(self.mChannels) devices.set_channel(interface, channel) self.mChannel = channel # If target found. else: if globalsx.gFILTERCHANNEL: channel = choice(globalsx.gFILTERCHANNEL) else: channel = choice(self.mChannels) devices.set_channel(interface, channel, s) self.mChannel = channel if len(globalsx.gFILTERCHANNEL) == 1: break if self.mDiagnose: print("[CH]: Channel Set to: {0}".format(self.mChannel)) except AttributeError: print("Error on interpreter shutdown. Disregard.") sys.exit(0) except: print("Error") print(time.time() - start) time.sleep(2.75) nl.nl_socket_free(s) # Exit hopper. return
def create_eventDescriptor(): print " -> Creating EventDescriptor:\n" deviceId = devices.select_configured_device() device = devices.get_device(deviceId) if not device: return None eventType = select_eventType(device['deviceClassId']) if not eventType: print "\n This device has no events" return None params = parameters.read_paramDescriptors(eventType['paramTypes']) eventDescriptor = {} eventDescriptor['deviceId'] = deviceId eventDescriptor['eventTypeId'] = eventType['id'] if len(params) > 0: eventDescriptor['paramDescriptors'] = params return eventDescriptor
def load_checkpoint(file_path, device=None): """Rebuild a model from a saved checkpoint.""" if not device: device = get_device('gpu') model_data = torch.load(file_path) model = models.vgg16(pretrained = True) model.classifier = model_data.get('classifier', { ('fc1', nn.Linear(25088, 500)), ('relu', nn.ReLU()), ('fc2', nn.Linear(500, 102)), ('dropout', nn.Dropout(0.2)), ('output', nn.LogSoftmax(dim = 1)) }) model.class_to_idx = model_data.get('class_to_idx', model_data.get('idx_to_class')) model.load_state_dict(model_data['state_dict']) model.to(device) print("Model loaded.") return (model, model_data)
def uplink(alias, bytecode, loop, skip_layout, layout_root, tmpdir): """ .. _ztc-cmd-uplink: Uplink ====== Once a Zerynth program is compiled to bytecode it can be executed by transferring such bytecode to a running virtual machine on a device. This operation is called "uplinking" in the ZTC terminology. Indeed Zerynth virtual machines act as a bootloader waiting a small amount of time after device reset to check if new bytecode is incoming. If not, they go on executing a previously loaded bytecode or just wait forever. The command: :: ztc uplink alias bytecode will start the uplinking process for the device with alias :samp:`alias` using the compiled :samp:`.vbo` file given in the :samp:`bytecode` argument. As usual :samp:`alias` ca be partially specified. The uplinking process may require user interaction for manual resetting the device whan appropriate. The process consists of: * a discovery phase: the device with the given alias is searched and its attributes are checked * a probing phase: depending on the device target a manual reset can be asked to the user. It is needed to reset the virtual machine and put it in a receptive state. In this phase a "probe" is sent to the virtual machine, asking for runtime details * a handshake phase: once runtime details are known, additional info are exchanged between the linker and the virtual machine to ensure correct bytecode transfer * a relocation phase: the bytecode is not usually executable as is and some symbols must be resolved against runtime details * a flashing phase: the relocated bytecode is sent to the virtual machine Each of the previous phases may fail in different ways and the cause can be determined by inspecting error messages. The :command:`uplink` may the additional :option:`--loop times` option that specifies the number of retries during the discovery phase (each retry lasts one second). """ dev = get_device(alias, loop) if not skip_layout: _uplink_layout(dev, bytecode, dczpath=layout_root) if dev.preferred_uplink_with_jtag: # uplink code with jtag _link_uplink_jtag(dev, bytecode, tmpdir) else: _uplink_dev(dev, bytecode, loop, tmpdir)
def create_device_state_logfilter(): params = {} deviceIds = [] typeIds = [] loggingSources = [] loggingSources.append("LoggingSourceStates") params['loggingSources'] = loggingSources deviceId = devices.select_configured_device() if not deviceId: return None deviceIds.append(deviceId) params['deviceIds'] = deviceIds device = devices.get_device(deviceId) stateType = states.select_stateType(device['deviceClassId']) if not stateType: return None typeIds.append(stateType['id']) params['typeIds'] = typeIds return params
def list_rules_containig_deviceId(): deviceId = devices.select_configured_device() if not deviceId: return None device = devices.get_device(deviceId) params = {} params['deviceId'] = deviceId response = nymea.send_command("Rules.FindRules", params) if not response['params']['ruleIds']: print "\nThere is no rule containig this device." return None print "\nFollowing rules contain this device %s\n" % (deviceId) for i in range(len(response['params']['ruleIds'])): ruleDescription = get_rule_description( response['params']['ruleIds'][i]) print "%20s ( %s ) -> %s / %s" % ( ruleDescription['name'], ruleDescription['id'], print_rule_enabled_status(ruleDescription['enabled']), print_rule_active_status(ruleDescription['active']))
def execute_action(): deviceId = devices.select_configured_device() if deviceId == None: return None device = devices.get_device(deviceId) actionType = select_actionType(device['deviceClassId']) #print nymea.print_json_format(actionType) if actionType == None: print "\n This device has no actions" return None actionTypeId = actionType['id'] params = {} params['actionTypeId'] = actionTypeId params['deviceId'] = deviceId actionType = get_actionType(actionTypeId) actionParams = parameters.read_params(actionType['paramTypes']) params['params'] = actionParams response = nymea.send_command("Actions.ExecuteAction", params) if response: nymea.print_device_error_code(response['params']['deviceError'])
def perform(self): # TODO this needs to be refactored once a sensible system # for combining all the audio sources and effects for # all six lists is settled on. for b in self.lists: if not b[0]: continue for c in b: n = int(c[:2], 8) v = int(c[2:], 8) device = get_device(int(c[:2], 8)) dprint(device, c) if n == 62: # Interrupt timer self.clock = v if 0 < n < 4: # Osc dprint('OSC', n) if self.oscillators[n - 1]: self.oscillators[n - 1].change(v) else: self.oscillators[n - 1] = Oscillator(v) self.active = n - 1 if 23 < n < 27: # Envelopes n = n - 24 dprint('Envelope', n + 1) d = self.secs(v) if self.envelopes[n]: self.envelopes[n].addtime(d) else: self.envelopes[n] = Envelope(d) if n == 60: # Wait timer d = self.secs(v) dprint('WAIT:', d) self.oscillators[self.active].duration += d if self.envelopes[self.active]: self.envelopes[self.active].addtime(d) # write the generated audio sources = [o for o in self.oscillators if o] sources += [e for e in self.envelopes if e] dprint('SOURCES', sources) output = ' '.join(['(seq %s)' % ' '.join(s.out()) for s in sources]) return '(mult %s)' % output
def main(): # Read user arguments args = parse_args() # Load the model device = get_device("GPU" if args.gpu else "CPU") model, model_data = load_checkpoint(args.checkpoint, device = device) # Load map of labels and indices optionally passing in custom json cat_to_name = cat_labels(args.category_names) if args.category_names else cat_labels() # Get image name and label for image image_path = args.path_to_image image_class = image_path.split("/")[-2] image_label = cat_to_name.get(image_class, "Undefined") # Load image tensor and calculate top-k predictions image = process_image(args.path_to_image) unsqueezed_image = image.unsqueeze(0) #unsqueezed_image.requires_grad = False #unsqueezed_image.to(device) model.to('cpu') model.eval() # Get the class labels and prediction probabilities k = args.top_k if args.top_k else 5 predictions = predict(unsqueezed_image, model, k = k) # Top-k image labels and likelihoods k = args.top_k if args.top_k else 1 print(f"\nTop {k} predictions for {image_path}:") # Get the predicted classes and probabilities predictions = predict(unsqueezed_image, model, k = k) # Log out the top labels and probabilities for i in range(len(predictions[0])): print(f"{cat_to_name[predictions[0][i]]}: {float(predictions[1][i])}") # Log the real image label print(f"True classification: {image_label}\n")
def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs self.ipaddr = kwargs.pop('ipaddr', None) self.iface = kwargs.pop('iface', None) self.docker_network = kwargs.pop('docker_network', None) self.env = kwargs.pop('env', None) self.name = kwargs.pop('name') self.cname = self.name + '-${uniq_id}' if self.ipaddr is not None: # TOOO: we rely on correct username and key and standard port pexpect.spawn.__init(self, command="ssh", args=[ '%s' % (self.ipaddr), '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'ServerAliveInterval=60', '-o', 'ServerAliveCountMax=5' ]) else: pexpect.spawn.__init__(self, command='bash', env=self.env) self.ipaddr = 'localhost' if 'BFT_DEBUG' in os.environ: self.logfile_read = sys.stdout self.expect(pexpect.TIMEOUT, timeout=1) self.sendline('export PS1="docker_session>"') self.expect(self.prompt) self.sendline('echo FOO') self.expect_exact('echo FOO') self.expect(self.prompt) self.set_cli_size(200) # if these interfaces are getting created let's give them time to show up for i in range(10): self.sendline('ifconfig %s' % self.iface) self.expect(self.prompt) if 'error fetching interface information: Device not found' not in self.before: break # iface set, we need to create network if self.iface is not None: self.sendline( 'docker network create -d macvlan -o parent=%s -o macvlan_mode=bridge %s' % (self.iface, self.cname)) self.expect(self.prompt) self.sendline('docker network ls') self.expect(self.prompt) self.created_docker_network = True from devices import get_device for target in kwargs.pop('targets'): target_img = target['img'] target_type = target['type'] target_cname = target['name'] + '-${uniq_id}' # TODO: check for docker image and build if needed/can # TODO: move default command into Dockerfile # TODO: list of ports to forward, http proxy port for example and ssh self.sendline( 'docker run --rm --privileged --name=%s -d -p 22 %s /usr/sbin/sshd -D' % (target_cname, target_img)) self.expect(self.prompt) assert "Unable to find image" not in self.before, "Unable to find %s image!" % target_img self.expect(pexpect.TIMEOUT, timeout=1) self.sendline('docker network connect %s %s' % (self.cname, target_cname)) self.expect(self.prompt) assert 'Error response from daemon' not in self.before, "Failed to connect docker network" if self.created_docker_network == True: self.sendline('docker exec %s ip address flush dev eth1' % target_cname) self.expect(self.prompt) self.sendline("docker port %s | grep '22/tcp' | sed 's/.*://g'" % target_cname) self.expect_exact( "docker port %s | grep '22/tcp' | sed 's/.*://g'" % target_cname) self.expect(self.prompt) target['port'] = self.before.strip() int(self.before.strip()) self.created_docker = True target['ipaddr'] = self.ipaddr new_device = get_device(target_type, **target) self.extra_devices.append(new_device) self.target_cname.append(target_cname)
def retrieve_vm_uid(alias): dev = get_device(alias, 5) vm_uid, version, target, chipid = _vmuid_dev(dev) if target != dev.target: fatal("Target mismatch!", target, "vs", dev.target) return vm_uid, version, target, chipid, dev
def __init__(self, interface, channels, target, mac, unassociated, diagnose, open_network, Clients_, kill_time, deauth=None, packets=None, skip=None): self.mChannel = devices.get_channel(interface) self.mUnassociated = unassociated self.mInterface = interface self.mDiagnose = diagnose self.mChannels = channels self.mClients = Clients_ self.mTarget = target self.mOpen = open_network self.mMAC = mac conf.iface = interface if kill_time: globalsx.gKILLTIME = kill_time self.mDeauthPackets = packets self.mSkip = skip globalsx.gDEAUTH = deauth self.mTime = kill_time self.mPackets = 0 self.mHidden = [] self.mAPs = {} self.mCls = {} self.mUCls = {} if len(self.mChannels) == 1: self.mHop = False self.mChannel = channels[0] devices.set_channel(devices.get_device(interface), channels[0]) else: self.mHop = True hop_thread = Thread(target=self.hopper) hop_thread.daemon = True hop_thread.start() if globalsx.gDEAUTH: deauth_thread = Thread(target=self.deauther) deauth_thread.daemon = True deauth_thread.start() if not self.mDiagnose: printer_thread = Thread(target=self.printer) printer_thread.daemon = True printer_thread.start() return
# signal is used to drive the power supply (sending data while the # device is not powered could cause troubles). # self.link.detect_wires('?') cout(_("Tty wires: %d\n") % self.link.wires) # We can now send synchronization sequences # try: self.link.sync() except Exception, e: die(_("Synchronization failed.\n%s" % repr(e))) # Identify device # self.device = devices.get_device(self.link) cout(_("Connected to device (protocol %d):\n" % self.device.protocol)) cout( self.device.str(self.options.show_fuses, self.options.decode_fuses)) # Check target name # if self.options.mcu and self.device.name.lower( ) != self.options.mcu.lower(): die( _("Target mismatch: connected to %s, %s expected.\n" % (self.device.name, self.options.mcu))) # Compute the CRC of the firmware? #
#!/usr/bin/env python3 import colorsys import math import time import random import numpy as np from devices import get_device from effects import get_effect device = get_device("lifx_tile") effect = get_effect("spectrum") while True: device.set_effect(effect) time.sleep(1 / 60)
# signal is used to drive the power supply (sending data while the # device is not powered could cause troubles). # self.link.detect_wires('?') cout(_("Tty wires: %d\n") % self.link.wires) # We can now send synchronization sequences # try: self.link.sync() except Exception, e: die(_("Synchronization failed.\n%s" % repr(e))) # Identify device # self.device = devices.get_device(self.link) cout(_("Connected to device (protocol %d):\n" % self.device.protocol)) cout(self.device.str(self.options.show_fuses, self.options.decode_fuses)) # Check target name # if self.options.mcu and self.device.name.lower() != self.options.mcu.lower(): die(_("Target mismatch: connected to %s, %s expected.\n" % (self.device.name, self.options.mcu))) # Compute the CRC of the firmware? # if self.options.fwcrc: cout("\nReading firmware flash: ") data='' if self.device.protocol == 4:
def runTest(self): if not wan: msg = 'No WAN Device defined, skipping test_create_session.' lib.common.test_msg(msg) self.skipTest(msg) wan_ip = wan.get_interface_ipaddr("eth0") import devices # this should fail, as "DebianBoxNonExistent" is not (yet) a device try: kwargs ={ 'name':"wan_test_calls_fail", 'ipaddr':wan_ip, 'port':22, 'color': 'magenta' } self.session = devices.get_device("DebianBoxNonExistent", **kwargs) except: pass else: assert self.session is None,"Test Failed on wrong class name" print("Failed to create session on wrong class name (expected) PASS") # this must fail, as "169.254.12.18" is not a valid ip try: kwargs ={ 'name':"wan_test_ip_fail", 'ipaddr':"169.254.12.18", 'port':22, 'color': 'cyan' } self.session = devices.get_device("DebianBox", **kwargs) except: pass else: assert self.session is None,"Test Failed on wrong IP" print("Failed to create session on wrong IP (expected) PASS") # this must fail, as 50 is not a valid port try: kwargs ={ 'name':"wan_test_port_fail", 'ipaddr':wan_ip, 'port':50, 'color': 'red' } self.session = devices.get_device("DebianBox", **kwargs) except: pass else: assert self.session is None,"Test Failed on wrong port" print("Failed to create session on wrong port (expected) PASS") # this must fail, close but no cigar try: kwargs ={ 'name':"wan_test_type_fail", 'ipaddr':wan_ip, 'port':50, 'color': 'red' } self.session = devices.get_device("debina", **kwargs) except: pass else: assert self.session is None,"Test Failed on misspelled class name" print("Failed to create session on misspelled class name (expected) PASS") # this should pass try: kwargs ={ 'name':"correct_wan_parms", 'ipaddr':wan_ip, 'port':'22', 'color': 'yellow' } self.session = devices.get_device("debian", **kwargs) except: assert 0, "Failed to create session, Test FAILED!" else: assert self.session is not None,"Test Failed on correct paramters!!" print("Session created successfully") # is the session really logged onto the wan? wan.sendline() wan.expect(wan.prompt) wan.sendline("ip a") wan.expect_exact("ip a") wan.expect(wan.prompt) w = wan.before self.session.sendline() self.session.expect(self.session.prompt) self.session.sendline("ip a") self.session.expect_exact("ip a") self.session.expect(self.session.prompt) s = self.session.before assert w == s, "Interfaces differ!!! Test Failed" self.session.sendline("exit") print("Test passed")
def create_stateDescriptor(): print "-> Creating a new stateDescriptor:\n" deviceId = devices.select_configured_device() device = devices.get_device(deviceId) if device == None: return None stateType = select_stateType(device['deviceClassId']) if stateType == None: return None valueOperator = guh.select_valueOperator(stateType['name']) stateDescriptor = {} print "\nThe StateType looks like this:\n", guh.print_json_format( stateType) print "Please enter the value for state \"%s\" (type: %s): " % ( stateType['name'], stateType['type']) # make bool selectable to make shore they are "true" or "false" if any("possibleValues" in item for item in stateType): # has to be a string (for sorting list) possibleValues = [] for value in stateType['possibleValues']: possibleValues.append(str(value)) selection = guh.get_selection( "Please select one of following possible values:", possibleValues) if selection == None: return None stateValue = stateType['possibleValues'][selection] else: # make bool selectable to make shore they are "true" or "false" if stateType['type'] == "Bool": boolTypes = ["true", "false"] selectionString = "Please enter the value for state \"%s\" (type: %s): " % ( stateType['name'], stateType['type']) selection = guh.get_selection(selectionString, boolTypes) if selection == None: return None stateValue = boolTypes[selection] elif stateType['type'] == "Int": stateValue = int( raw_input("%s %s " % (stateType['name'], guh.get_valueOperator_string(valueOperator)))) elif stateType['type'] == "Double": stateValue = float( raw_input("%s %s " % (stateType['name'], guh.get_valueOperator_string(valueOperator)))) elif stateType['type'] == "Uint": stateValue = int( raw_input("%s %s " % (stateType['name'], guh.get_valueOperator_string(valueOperator)))) else: stateValue = raw_input( "%s %s " % (stateType['name'], guh.get_valueOperator_string(valueOperator))) stateDescriptor['deviceId'] = deviceId stateDescriptor['stateTypeId'] = stateType['id'] stateDescriptor['value'] = stateValue stateDescriptor['operator'] = valueOperator print guh.print_json_format(stateDescriptor) return stateDescriptor
def run(self): flash = None # Data to burn into flash start_time = timer() # Compute a CRC? # if self.options.stat or self.options.crc or self.options.size: if not self.options.filename: die(_("Input file is required for CRC computation.\n")) if not self.options.mcu: die(_("Target device is required for CRC computation.\n")) try: self.device = devices.devices[self.options.mcu.lower()]() except: die(_("\"%s\": no such device.\n" % self.options.mcu.lower())) data = self.read_file(self.options.filename) x, crc = self.device.appstat(data) if self.options.stat: # # Use sys.stdout.write instead of cout to bypass '--quiet' # sys.stdout.write( _("%s: %d /%d application bytes, CRC=0x%04X.\n" % (self.options.filename, x, self.device.flashsize, crc))) elif self.options.crc: sys.stdout.write("%04X\n" % crc) else: sys.stdout.write("%d\n" % x) return # Compute a CRC32? # if self.options.crc32: if not self.options.filename: die(_("Input file is required for CRC32 computation.\n")) import binascii s = open(self.options.filename, 'rb').read() crc32 = binascii.crc32(s) sys.stdout.write("%08x\n" % (crc32 & 0xFFFFFFFF)) return # List available ttys? # if self.options.tty == "list": ttys = link.list() cout(_("Available ttys:\n" + str(ttys))) return # Open the communication channel # try: self.link = link.get(self.options) except link.serial.SerialException as e: die(str(e)) # Reset the device connected to the serial interface # self.link.set_TXD(0) self.link.set_RESET(0) if self.options.reset_length: time.sleep(self.options.reset_length) self.link.set_RESET(1) # Just reset the device and quit? # if self.options.reset_and_exit: return if self.options.keep_txd_low == 0: cout( "WARNING: target will probably not remain in Diabolo if TXD is not " "maintained low long enough!\n") else: time.sleep(self.options.keep_txd_low) self.link.set_TXD(1) # This is the best moment for detecting how many wires are used for the # serial communication since the target device is supposed to be # waiting in Diabolo for the synchronization. # # It is safe to send data on the serial line now even if the RESET # signal is used to drive the power supply (sending data while the # device is not powered could cause troubles). # self.link.detect_wires(b'?') cout(_("Tty wires: %d\n") % self.link.wires) # We can now send synchronization sequences # if not self.link.sync(): die(_("Synchronization failed.\n")) # Identify device # self.device = devices.get_device(self.link) cout(_("Connected to device (protocol %d):\n" % self.device.protocol)) cout( self.device.str(self.options.show_fuses, self.options.decode_fuses)) # Check target name # if self.options.mcu and self.device.name.lower( ) != self.options.mcu.lower(): die( _("Target mismatch: connected to %s, %s expected.\n" % (self.device.name, self.options.mcu))) # Compute the CRC of the firmware? # if self.options.fwcrc: cout("\nReading firmware flash: ") data = bytearray() if self.device.protocol == 4: step = self.device.pagesize else: # protocol 5 step = 256 for a in range(self.device.bladdr, self.device.flashsize, step): page = self.device.read_flash_page(a) if page == None: cerr(_("\nRead page failed at 0x%04X.\n" % a)) return False cout('.') flushout() data.extend(page) # Compute the CRC # crc = CRC.init() i = len(data) - 1 while i >= 0 and data[i] == 0xFF: i -= 1 while i >= 0: crc = CRC.add(crc, data[i]) i -= 1 # x, crc = self.device.appstat(data) cout( _("\nRead %d bytes of firmware, CRC=0x%04X.\n" % (len(data), crc))) return # Read flash memory? # if self.options.read_flash: data = self.read_flash() if self.options.hexdump: cout(hexdump(0, data) + "\n") if self.options.cache: self.write_file(self.options.cache, data) #return # Read eeprom memory? # if self.options.read_eeprom: data = self.read_eeprom() if self.options.hexdump: cout(hexdump(0, data) + "\n") if self.options.cache: self.write_file(self.options.cache, data) #return # Erase flash memory? # if self.options.clear_flash: flash = bytearray.fromhex('FF' * self.device.flashsize) # Write flash memory? # if self.options.burn_flash: if not self.options.filename: die(_("Input file is required to program flash memory.\n")) cache = None if self.options.cache: if os.path.isfile(self.options.cache): cache = self.read_file(self.options.cache) if len(cache) < self.device.bladdr: cout(_("Wrong cache size. Dropping cache data.\n")) cache = None else: x, cache_crc = self.device.appstat(cache) if self.device.appcrc != cache_crc: cout(_("Cache CRC (%04X) does not match device CRC. "\ "Dropping cache data.\n" % cache_crc)) cache = None else: cout( _("Cache file does not exist yet, reading flash" " memory is required.\n")) if cache == None: cache = self.read_flash() if self.options.cache: self.write_file(self.options.cache, cache) x, cache_crc = self.device.appstat(cache) flash = self.read_file(self.options.filename) if len(flash) < self.device.bladdr: cout(_("Padding data with 0xFF bytes\n")) flash.extend( bytes.fromhex('FF' * (self.device.bladdr - len(flash)))) # Program flash memory # if flash: # # Override RESET vector for device without bootsection # RJMP opcode: 1111 aaaa aaaa aaaa = 0xC000 + Addr # if not self.device.bootsection: addr = int(self.device.bladdr / 2) - 1 if addr > 0x0FFF: die(_("Can not set RESET vector opcode.\n")) opcode = 0xC000 + addr byte0 = opcode & 0xFF byte1 = opcode >> 8 cout( _("Device without bootsection, " "setting RESET vector to computed opcode: %02x %02x\n") % (byte0, byte1)) #flash = opcode.to_bytes(2,byteorder="little")+flash[2:] flash[0] = byte0 flash[1] = byte1 x, flash_crc = self.device.appstat(flash) if flash_crc == cache_crc: cout( _("Cache and data CRC match, nothing to program in Flash memory.\n" )) if self.device.eeappcrc != flash_crc: self.device.write_eeprom_appcrc(flash_crc) check = self.device.read_eeprom_appcrc() if check == flash_crc: cout( _("Updated application CRC in EEPROM: 0x%04X\n" % flash_crc)) else: raise Exception(_("update of application CRC in EEPROM failed: %04X!=%04X" %\ (check, flash_crc)) ) x_restart = True else: self.write_flash(flash, cache) x_restart = False if self.device.flash_changed: # trace() self.device.pgmcount += 1 self.device.write_eeprom_pgmcount(self.device.pgmcount) check = self.device.read_eeprom_pgmcount() if check == self.device.pgmcount: cout(_("Set program count to %d\n" % self.device.pgmcount)) else: cout( _("Failed to set program count to %d (read %d)." % (self.device.pgmcount, check))) x_restart = True if self.device.eeappcrc != flash_crc: # trace() self.device.write_eeprom_appcrc(flash_crc) cout( _("Stored application CRC in EEPROM: 0x%04X\n" % flash_crc)) x_restart = True if x_restart: # trace() #cout(_("Reset device's Diabolo\n")) self.device.resume() self.link.tx( b'*') # Send a bad command to force CRC re-computation # # Wait up to 1 s for CRC computation (~50 cycles/byte) # t = timer() + 1.0 while timer() < t and not self.link.rx(1): pass if timer() >= t: raise Exception("timeout waiting CRC recomputation") if self.link.lastchar != ord('!'): raise Exception( "unexpected reply (0x%02X) to '*' command" % ord(c)) self.link.tx(b'\n') # Resume self.link.rx(1) self.device = self.device.identify() cout(" Application CRC:\n") cout(_(" computed: 0x%04X\n" % self.device.appcrc)) cout(_(" EEPROM: 0x%04X\n" % self.device.eeappcrc)) cout(_(" Programmings: %d\n" % self.device.pgmcount)) # Update flash cache # if self.options.cache: # trace() self.write_file(self.options.cache, flash) # Start application # if self.device.appcrc == self.device.eeappcrc \ and self.device.appcrc != 0xFFFF: if self.device.start_application(): cout("Target started its application.\n") else: cout("ERROR: target did not start its application.\n") self.link.close() if self.options.diag: cout( _("%d commands, %d fails, %d resumes, %d crc errors, total time: %.1f s.\n" % (self.device.ncmds, self.device.ncmdfails, self.device.nresumes, self.device.ncrcerrors, timer() - start_time + 0.05)))