def openSnapCom(self): if self.com == None: try: self.com = snap.Snap("SNAP_license.dat", funcs=self.funcdir) if self.com: try: self.com.open_serial(snap.SERIAL_TYPE_SNAPSTICK100, 0, dll_path='.') except: try: self.com.open_serial(snap.SERIAL_TYPE_SNAPSTICK200, 0, dll_path='.') except: errStr = "Could not locate any USB bridge.\ \nPlease check the USB ports & verify they are not in use by another program." self.showMessage("Error", errStr) self.com = None else: CONN_TYPE = snap.SERIAL_TYPE_SNAPSTICK200 else: CONN_TYPE = snap.SERIAL_TYPE_SNAPSTICK100 except: errStr = "The system could not establish a Snap instance.\ \nPlease check that the license file is in the program directory." self.showMessage("Error", errStr) self.com = None
def __init__(self): # You can define what functions can be called remotely on your SNAPconnect instance # using the `funcs` argument funcs = { "get_random": self.get_random } # Create a SNAP instance self.comm = snap.Snap(funcs=funcs) # You can also define which functions can be called using `add_rpc_func` self.comm.add_rpc_func("log_response", self.log_response) # SNAPconnect also provides hooks for certain events, for example when the serial connection # is opened or closed self.comm.set_hook(snap.hooks.HOOK_SERIAL_OPEN, self.hook_open) self.comm.set_hook(snap.hooks.HOOK_SERIAL_CLOSE, self.hook_close) # Open a serial connection to your bridge self.comm.open_serial(SERIAL_TYPE, SERIAL_PORT) self.log = logging.getLogger("BridgeVersionClient") snapconnect_addr = self.comm.local_addr() self.log.info("SNAPconnect Address: %r" % binascii.hexlify(snapconnect_addr))
def __init__(self): self.snapRpcFuncs = {'status' : self.status, 'send_ws' : self.send_ws } # Create SNAP Connect instance. Note: we are using TornadoWeb's scheduler. self.snapconnect = snap.Snap(license_file = snap_license, addr = snap_addr, scheduler=ioloop_scheduler.IOLoopScheduler.instance(), funcs = self.snapRpcFuncs ) # Configure SNAP Connect params self.snapconnect.save_nv_param(snap.NV_FEATURE_BITS_ID, 0x100) # Send with RPC CRC # Connect to local SNAP wireless network self.snapconnect.open_serial(serial_conn, serial_port) #self.snapconnect.accept_tcp() self.snapconnect.set_hook(snap.hooks.HOOK_SNAPCOM_OPENED, self.on_connected) self.snapconnect.set_hook(snap.hooks.HOOK_SNAPCOM_CLOSED, self.on_disconnected) # Tell the Tornado scheduler to call SNAP Connect's internal poll function. tornado.ioloop.PeriodicCallback(asyncore.poll, self.SNAPCONNECT_POLL_INTERVAL).start() tornado.ioloop.PeriodicCallback(self.snapconnect.poll_internals, self.SNAPCONNECT_POLL_INTERVAL).start()
def __init__(self, node_addr, serial_type, serial_port): ''' :param node_addr: 6-byte hex string that is the target of the rpc calls. :param serial_type: Bridge type. See Snap Reference Manual for more info. :param serial_port: COM Port. 0 = COM 1, 1 = COM 2, dev/tty1 can be used for linux system. :return: ''' logging.info('Initializing SNAPconnect instance.') # You have to manually register your callbacks using traditional SNAPconnect methods. # It's possible to hide this behind-the-scenes and register them on the fly similar to how SNAPconnect Futures # handles it, but it would be more code than just registering the callbacks in this scenario. self.func = { 'simple_response' : self.simple_response, 'explicit_response' : self.explicit_response, 'the_wrong_response' : self.the_wrong_response, 'delay_response_one' : self.delay_response_one, 'delay_response_two' : self.delay_response_two, 'dropped_response' : self.dropped_response } self.serial_type = serial_type self.serial_port = serial_port self.response = None self.timeout_event = None self.attempt = 0 self.active_rpc = None self.queue = [] # Make your SNAP Instance. self.sc = snap.Snap(funcs = self.func) self.sc.open_serial(serial_type, serial_port)
def __init__(self): self.snapRpcFuncs = {'dist' : self.dist, 'send_ws' : self.send_ws } cur_dir = os.path.dirname(__file__) # Create SNAP Connect instance. Note: we are using TornadoWeb's scheduler. self.snapconnect = snap.Snap(license_file = os.path.join(cur_dir, 'SrvLicense.dat'), addr = snap_addr, scheduler=ioloop_scheduler.IOLoopScheduler.instance(), funcs = self.snapRpcFuncs ) # Connect to local SNAP wireless network self.snapconnect.open_serial(serial_conn, serial_port) #self.snapconnect.accept_tcp() self.snapconnect.set_hook(snap.hooks.HOOK_SNAPCOM_OPENED, self.on_connected) self.snapconnect.set_hook(snap.hooks.HOOK_SNAPCOM_CLOSED, self.on_disconnected) # Tell the Tornado scheduler to call SNAP Connect's internal poll function. tornado.ioloop.PeriodicCallback(asyncore.poll, self.SNAPCONNECT_POLL_INTERVAL).start() tornado.ioloop.PeriodicCallback(self.snapconnect.poll_internals, self.SNAPCONNECT_POLL_INTERVAL).start()
def __init__(self): """set up initial things for the class such as functions, rpc functions, hooks, and opening the serial port""" # You can define what functions can be called remotely on your SNAPconnect instance # using the `funcs` argument funcs = {"get_data": self.get_data} # Create a SNAP instance self.comm = snap.Snap(funcs=funcs) # You can also define which functions can be called using `add_rpc_func` self.comm.add_rpc_func("update_device", self.update_device) # SNAPconnect also provides hooks for certain events, for example when the serial connection # is opened or closed self.comm.set_hook(snap.hooks.HOOK_SERIAL_OPEN, self.hook_open) self.comm.set_hook(snap.hooks.HOOK_SERIAL_CLOSE, self.hook_close) # Open a serial connection to your bridge self.comm.open_serial(SERIAL_TYPE, SERIAL_PORT) # create logger to write to display screen self.log = logging.getLogger("BridgeVersionClient") snapconnect_addr = self.comm.local_addr() self.log.info("SNAPconnect Address: %r" % binascii.hexlify(snapconnect_addr))
def __init__(self): self.bridge_address = None # Set a default value for the bridge address self.bridge_version = "Unknown" # Set a default value for the bridge version # You can define what functions can be called remotely on your SNAPconnect instance # using the `funcs` argument funcs = { "major_callback": self.major_callback, "minor_callback": self.minor_callback } # Create a SNAP instance self.comm = snap.Snap(funcs=funcs) # You can also define which functions can be called using `add_rpc_func` self.comm.add_rpc_func("patch_callback", self.patch_callback) # SNAPconnect also provides hooks for certain events, for example when the serial connection # is opened or closed self.comm.set_hook(snap.hooks.HOOK_SERIAL_OPEN, self.hook_open) self.comm.set_hook(snap.hooks.HOOK_SERIAL_CLOSE, self.hook_close) # Open a serial connection to your bridge self.comm.open_serial(SERIAL_TYPE, SERIAL_PORT) self.log = logging.getLogger("BridgeVersionClient") snapconnect_addr = self.comm.local_addr() self.log.info("SNAPconnect Address: %r" % binascii.hexlify(snapconnect_addr))
def __init__(self,address,channel,log_name): # Create a SNAP instance self.channel = channel self.log_name = log_name self.snap = snap.Snap(funcs={'bridge_node_name':self.bridge_node_name,'reportIR': self.reportIR,'reportUS': self.reportUS,'reportPIR': self.reportPIR,'heartbeat':self.heartbeat},addr=address) self.snap.set_hook(snap.hooks.HOOK_SERIAL_CLOSE,self.connection_closed) self.snapconnect_addr = binascii.hexlify(self.snap.load_nv_param(2))
def __init__(self, publish, poll_interval=10): """Initializes an instance of SNAPToCloudExample. :param Callable[[str, dict], None] publish: A function for publishing to a cloud service :param int poll_interval: How often SNAPConnect should poll, in milliseconds """ self.publish = publish snap_rpc_funcs = {'status': self._on_status} # Create SNAP Connect instance. Note: we are using Tornado's scheduler. self.snapconnect = snap.Snap( license_file=snap_license, addr=snap_addr, scheduler=ioloop_scheduler.IOLoopScheduler(), funcs=snap_rpc_funcs) self.snapconnect.save_nv_param(snap.NV_FEATURE_BITS_ID, 0x0100) # RPC CRC Only self.snapconnect.open_serial(serial_conn, serial_port) # Tell tornado to call SNAP connect internals periodically tornado.ioloop.PeriodicCallback(self.snapconnect.poll_internals, poll_interval).start() # Start the IOLoop, nothing can happen after this point tornado.ioloop.IOLoop.instance().start()
def __init__(self): # Create a SNAP instance self.snap = snap.Snap(funcs={'setButtonCount': self.set_button_count}) # Open COM1 (port 0) connected to a serial SNAP bridge self.snap.open_serial(snap.SERIAL_TYPE_RS232, '/dev/cu.usbserial' ) #Accept connection from other SNAP connect instances and Portal self.snap.accept_tcp() # Create a logger self.log = logging.getLogger("McastCounterClient")
def main(): global comm print "Python version is " + sys.version comm = snap.Snap(funcs={}) print "SNAPconnect version number " + str(comm.get_info(5)) + "." + str( comm.get_info(6)) + "." + str(comm.get_info(7)) addr = comm.load_nv_param(2) print "My SNAP Address is " + "%02X.%02X.%02X" % (ord( addr[-3]), ord(addr[-2]), ord(addr[-1])) encryption_setting = comm.load_nv_param(snap.NV_AES128_ENABLE_ID) print "Encryption is set to " + str(encryption_setting)
def init_snap(self): """Create a SNAPconnect instance and add hooks for firmware upgrades""" self.comm = snap.Snap(funcs={}) self.comm.set_hook(snap.hooks.HOOK_OTA_UPGRADE_COMPLETE, self._upgrade_complete_hook) self.comm.set_hook(snap.hooks.HOOK_OTA_UPGRADE_STATUS, self._upgrade_status_hook) self.comm.set_hook(snap.hooks.HOOK_SERIAL_OPEN, self._serial_open_hook) # Start polling the SNAPconnect instance # While running this script, the wx application MainLoop() will drive the program # Here, we tie the polling of SNAPconnect into the application loop for the GUI # We could also choose to run the SNAPconnect loop() function inside of a separate thread self.poller = wx.Timer(self, wx.NewId()) self.Bind(wx.EVT_TIMER, self.poll_snap) self.poller.Start(self.poll_time, wx.TIMER_CONTINUOUS)
def __init__(self): self.snapRpcFuncs = {'updateLEDs' : self.updateLEDs, 'powerOn173' : self.powerOn173} cur_dir = os.path.dirname(__file__) # Create SNAP Connect instance. Note: we are using TornadoWeb's scheduler. self.snapconnect = snap.Snap(license_file = os.path.join(cur_dir, 'license.dat'), addr = snap_addr, scheduler=ioloop_scheduler.IOLoopScheduler(), funcs = self.snapRpcFuncs ) # Connect to local SNAP wireless network self.snapconnect.open_serial(serial_conn, serial_port) # Tell the Tornado scheduler to call SNAP Connect's internal poll function. Tornado already polls asyncore. tornado.ioloop.PeriodicCallback(self.snapconnect.poll_internals, self.SNAPCONNECT_POLL_INTERVAL).start()
def main(): """Simple benchmark. Create a SNAP Connect instance, and use it to send a batch of RPC calls""" global comm # Create a SNAP Connect object to do communications (comm) for us comm = snap.Snap(funcs={}) comm.add_rpc_func('response_handler', response_handler) # By tieing into HOOK_RPC_SENT events, we can avoid needlessly "piling up" RPC calls INSIDE THIS PC comm.set_hook(snap.hooks.HOOK_RPC_SENT, rpc_sent_handler) # By tieing into the HOOK_SERIAL_OPEN event, we can wait until we know we have a connected device to start the test comm.set_hook(snap.hooks.HOOK_SERIAL_OPEN, serial_open_handler) comm.open_serial(SERIAL_TYPE, SERIAL_PORT) # Wait for all the queries to be sent, and all the replies to be received (or timed out) while not test_complete: comm.poll() show_results()
def __init__(self, system_settings): """ Create instance of a Bridge Class :return: Bridge instance """ # Communication Nodes # self.gate = Node(system_settings=system_settings, input_dict={ 'name': 'Gate', 'presence': True, 'inactive': False, 'type': 'gate', }) self.base = Node(system_settings=system_settings, input_dict={ 'name': 'Base', 'presence': True, 'channel': None, 'inactive': False, 'type': 'base', }) # Internal Variables # self._bridge_init_info = None self._requests = list() self._base_node_reboot_flag = False self._vm_stat_callback = None self._serial_args = list() # Init Procedure # # Create SNAP Connect instance. Note: we are using Tornado scheduler. self._scheduler = ioloop_scheduler.IOLoopScheduler.instance() self.com = snap.Snap(scheduler=self._scheduler, funcs={}) # Set Tornado scheduler to call SNAP Connect's internal poll function. # Tornado already polls asyncore. # self._poll_timer = ioloop.PeriodicCallback(self._poll_snap, _SNAP_AWAKE_POLL) self._poll_timer = ioloop.PeriodicCallback(self._poll_snap, _SNAP_SLEEP_POLL)
def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title='GUI Template',size=(500,600)) panel = wx.Panel(self) self.poller = wx.Timer(self) self.Bind(wx.EVT_TIMER, lambda event : self.snap.poll()) self.poller.Start(20,wx.TIMER_CONTINUOUS) self.log = logging.getLogger("PumpFrame") sizer = wx.BoxSizer(wx.VERTICAL) btnSizer = wx.GridBagSizer(hgap=5,vgap=5) self.onUploadBtn = wx.Button(panel, -1, "Bulk Upload") self.Bind(wx.EVT_BUTTON, self.onBulkUpload, self.onUploadBtn) self.LEDonBtn = wx.Button(panel, -1, "LED on") self.Bind(wx.EVT_BUTTON, self.onLEDon, self.LEDonBtn) self.LEDoffBtn = wx.Button(panel, -1, "LED off") self.Bind(wx.EVT_BUTTON, self.onLEDoff, self.LEDoffBtn) btnSizer.Add(self.onUploadBtn, pos=(0,0)) btnSizer.Add(self.LEDonBtn, pos=(1,0)) btnSizer.Add(self.LEDoffBtn, pos=(2,0)) sizer.Add(btnSizer, flag=wx.CENTER|wx.ALL, border = 5) panel.SetSizer(sizer) panel.Fit() funcdir = {} self.snap = snap.Snap(funcs = funcdir) self.snap.open_serial(BRIDGE_NODE['type'],BRIDGE_NODE['port']) initial_mesh_seq_num = random.randint(1,255) self.snap.save_nv_param(snap.NV_MESH_SEQUENCE_NUMBER_ID, initial_mesh_seq_num) snaplib.MeshCodec.sequence_number=initial_mesh_seq_num
def main(): global comm # The functions required for this demo. Your program will likely add additional functions funcdir = { 'tellVmStat': tellVmStat, 'su_recvd_reboot': su_recvd_reboot } # Create a SNAPconnect object to do communications (comm) for us comm = snap.Snap(funcs=funcdir) # Note the hardcoded COM1 usage. See other examples for other connection possibilities. # Here the focus is on the script upload process, not all the different ways SNAPconnect # can communicate with other nodes. comm.open_serial(SERIAL_TYPE, SERIAL_PORT) # Make a SpyUploader object uploader = SpyUploader() # Tell it who to use for communications uploader.assign_SnapCom(comm) # Here we need to make a callback object. Your program may already have a GUI (etc.) # that implementes the required finishedSpyUpgrade() method callbackInstance = ExampleCallback() # Tell the SpyUploader who to report back to uploader.assign_Callback(callbackInstance) # Initiate an upload. Notice that the node and SPY file are defined at the top of this file uploader.beginUpload(BRIDGE_NODE, SPY_FILE) # For this example, only keep communications open until the transfer has been # completed, or the number of transfer attempts have been exhausted. # If we changed it to a "while True:" loop, then the SNAPconnect instance # would continue to run and route traffic even after the transfer was done. while uploader.progInProgress: comm.poll()
stCount = wx.StaticText(panel) stCount.SetMinSize((150, -1)) btInc = wx.Button(panel, label="Increment") box = wx.BoxSizer(wx.HORIZONTAL) box.Add(btInc, border=10, flag=wx.ALL) box.Add(stCount, border=10, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) panel.SetSizerAndFit(box) boxo = wx.BoxSizer(wx.VERTICAL) boxo.Add(panel) frame.SetSizerAndFit(boxo) setButtonCount(0) # initialize the button count to 0 frame.Bind(wx.EVT_BUTTON, guiButtonPressed) # register for button clicks # Create the SNAPconnect instance and expose the 'setButtonCount' function comm = snap.Snap(funcs={'setButtonCount': setButtonCount}) if BRIDGE_NODE['type'] == 'TCP': comm.connect_tcp(BRIDGE_NODE['host'], port=BRIDGE_NODE['port']) else: comm.open_serial(BRIDGE_NODE['type'], BRIDGE_NODE['port']) # Start a timer that fires every 20ms and gives the SNAPconnect # instance some attention poller = wx.Timer(frame) frame.Bind(wx.EVT_TIMER, lambda event: comm.poll()) poller.Start(20, wx.TIMER_CONTINUOUS) # Show the frame and start the wx event loop frame.Show() app.MainLoop()
def __init__(self): self.macs = [] bridge_mac = None parser = optparse.OptionParser() parser.add_option("-e", "--encryption", dest="encrypt", help="Enable encryption", default=0) parser.add_option("-k", "--encryptionKey", dest="encryption_key", help="Key for encryption", default='') parser.add_option("-m", "--macfile", dest="macfile", help="Mac list (def MacList.txt)", default='MacList.txt') parser.add_option("-s", "--spyfile", dest="spyfile", help="SPY file", default='') parser.add_option("-b", "--bridge", dest="comport", help="COM port 'COM4', 'USB100', or 'USB200'", default='DEFAULT') parser.add_option("-c", "--column", dest="column", help="CSV column (def 1)", default=1) parser.add_option("-f", "--find", dest="find", help="Find nodes on any channel/NID", action="store_true") parser.add_option("-n", "--network", dest="network", help="Change network (ch,0xNeId)(ex 1,0xD110)", default='') parser.add_option("-x", "--nofwd", dest="nofwd", help="Kill repeaters (no forwarding)", action="store_true") parser.add_option("-r", "--retry", dest="retry", help="Retry RPCs (def 3x)", default=3) parser.add_option("-t", "--timeout", dest="timeout", help="Timeout RPCs (def 3s)", default=3) parser.add_option("-z", "--remoteConn", dest="remoteConn", help="Connect to a remote SNAP network via this IP (Ex 74.198.44.1)", default='') parser.add_option("-j", "--remoteBridgeAddress", dest="remoteBrAddr", help="Remote conn requires the bridge SNAP address", default='') (options, args) = parser.parse_args() if options.network: try: net = options.network.split(',') new_chan = int(net[0]) new_nid = int(net[1], 16) except: print "Error: network option must be in form CH,0xNeId (ex: 4,0x1c2c or 4,0x1C2C)" return global DEF_RETRIES, DEF_TIMEOUT DEF_RETRIES = int(options.retry) DEF_TIMEOUT = int(options.timeout) if len(options.macfile) > 4 and options.macfile[-4:] == '.csv': self.parse_csv(options.macfile, int(options.column)) else: self.parse_maclist(options.macfile) if options.comport == 'USB200': s_type = snap.SERIAL_TYPE_SNAPSTICK200 s_port = 0 elif options.comport == 'USB100' or options.comport == "DEFAULT": s_type = snap.SERIAL_TYPE_SNAPSTICK100 s_port = 0 else: s_type = snap.SERIAL_TYPE_RS232 s_port = options.comport if sys.platform == 'linux2' and options.comport == "DEFAULT": # On linux, default to the E10 serial port if no comport is specified s_type = snap.SERIAL_TYPE_RS232 s_port = '/dev/ttyS1' #Add initial function callbacks. These will be replaced with calls to replace_rpc_func funcs = {'tellVmStat': lambda arg,val:None, 'su_recvd_reboot': lambda dummy:None} self.comm = snap.Snap(license_file = 'License.dat', nvparams_file = 'nvparams.dat', funcs=funcs) if not options.remoteConn and options.remoteBrAddr: print "Error: remoteBrAddr without a specified remote IP address (remote Conn)" # Setup NV Param self.comm.save_nv_param(snap.NV_FEATURE_BITS_ID, 0x100) # Send with RPC CRC self.comm.save_nv_param(snap.NV_MESH_ROUTE_AGE_MAX_TIMEOUT_ID, 0) self.comm.save_nv_param(snap.NV_MESH_OVERRIDE_ID, 1) self.comm.save_nv_param(snap.NV_LOCKDOWN_FLAGS_ID, 0x2) self.comm.save_nv_param(snap.NV_MESH_INITIAL_HOPLIMIT_ID, 2+1) #Plus one for the hop to the bridge self.comm.save_nv_param(snap.NV_MESH_MAX_HOPLIMIT_ID, 5+1) #Plus one the hop to the bridge self.comm.save_nv_param(snap.NV_AES128_ENABLE_ID, int(options.encrypt)) self.comm.save_nv_param(snap.NV_AES128_KEY_ID, options.encryption_key) snap.RpcCodec.validateCrc = False # Allow non-crc receive RPCs if options.remoteConn: try: # is this a valid address socket.inet_aton(options.remoteConn) self.comm.connect_tcp(options.remoteConn, tcp_keepalives = True, retry_timeout = 10) except: # Not Legal print "Error: IP address must be proper format xx.xx.xx.xx" return self.comm.set_hook(snap.hooks.HOOK_SNAPCOM_OPENED, callback=self.Snapcom_Opened) self.comm.set_hook(snap.hooks.HOOK_SNAPCOM_CLOSED, callback=self.Snapcom_Closed) # Now check that the user specified a bridge address and it is valid (AA.BB.CC or AABBCC) if len(options.remoteBrAddr) == 6: #AABBCC bridge_mac = binascii.unhexlify(options.remoteBrAddr) print #DEBUG elif len(options.remoteBrAddr) == 8 and (options.remoteBrAddr[2] == '.') and options.remoteBrAddr[5] == '.': #AA.BB.CC #Make sure it fits the pattern, then strip dots for conversion tempStr = options.remoteBrAddr[0:2] + options.remoteBrAddr[3:5] + options.remoteBrAddr[6:8] bridge_mac = binascii.unhexlify(tempStr) else: print "Error: BridgeAddress not configured for remote connection (Ex aabbcc or AA.BB.CC)" return log.info("Attempting to use remote bridge: %s" % (binascii.hexlify(bridge_mac))) else: #Not a remote connection #self.comm.open_serial(s_type, s_port) self.comm.open_serial(snap.SERIAL_TYPE_RS232,2) #(s_type, s_port) initial_mesh_seq_num = random.randint(1,255) self.comm.save_nv_param(snap.NV_MESH_SEQUENCE_NUMBER_ID, initial_mesh_seq_num) snaplib.MeshCodec.sequence_number = initial_mesh_seq_num # Control thread is managed by Sequencer self.seq = Sequencer() if options.remoteConn: # Ping to verify the remote connection/bridge if not bridge_mac: print "Error: BridgeAddress not configured for remote connection (Ex aabbcc or AA.BB.CC)" return self.rem_bridge_finder = FindRemBridge(self.comm, bridge_mac) self.seq.task_list.append(self.rem_bridge_finder) else: # Find the Local bridge self.bridge_finder = FindBridge(self.comm) self.seq.task_list.append(self.bridge_finder) bridge_mac = lambda: self.bridge_finder.bridge_addr # Next we build sequence from input MAC list file for mac in self.macs: pinger = Finder(self.comm, mac, bridge_mac) if options.find else Pinger(self.comm, mac, max_attempts=DEF_RETRIES, timeout=DEF_TIMEOUT) # Skip the ping attempt if we did not find the bridge (remote or local) skip_next_if_no_bridge = SkipSequence(self.seq, lambda pinger=pinger: int(not self.rem_bridge_finder.bridge_found if options.remoteConn else not self.bridge_finder.bridge_addr)) self.seq.task_list.append(skip_next_if_no_bridge) self.seq.task_list.append(pinger) skip_next_if_no_ping = SkipSequence(self.seq, lambda pinger=pinger: int(not pinger.got_response)) if options.network: self.seq.task_list.append(skip_next_if_no_ping) self.seq.task_list.append(NetChanger(self.comm, mac, new_chan, new_nid)) if options.nofwd: self.seq.task_list.append(skip_next_if_no_ping) self.seq.task_list.append(NoForward(self.comm, mac)) if options.spyfile: self.seq.task_list.append(skip_next_if_no_ping) self.seq.task_list.append(Uploader(self.comm, mac, options.spyfile)) elif options.network: # If we made network changes and didn't upload, we need to reboot self.seq.task_list.append(skip_next_if_no_ping) self.seq.task_list.append(RpcInvoker(self.comm, mac, 'reboot', max_attempts=DEF_RETRIES, timeout=DEF_TIMEOUT)) # Finally, we restore the Bridge to original settings if options.find: restore_bridge = RpcInvoker(self.comm, bridge_mac, 'reboot') self.seq.task_list.append(restore_bridge) log.info("----- Bulk Uploader Start -----") self.seq.start() while self.seq.is_running: self.comm.poll() not_uploaded = set(self.macs)-set(Uploader.uploaded_macs) not_responding = set(self.macs)-set(Pinger.responding_macs) print if options.spyfile: if not_uploaded: print "MACs not uploaded" for m in not_uploaded: print binascii.hexlify(m) else: if not_responding: print "MACs not responding" for m in not_responding: print binascii.hexlify(m) # Now let's generate a list of mac for the responding and un-responding nodes not_resp_file = open(not_resp_out_filename, 'w') for m in not_responding: not_resp_file.write("%s\n" % (str(binascii.hexlify(m)))) not_resp_file.close() resp_file = open(resp_out_filename, 'w') for m in Pinger.responding_macs: resp_file.write("%s\n" % (str(binascii.hexlify(m)))) resp_file.close() not_up_file = open(not_uploaded_out_filename, 'w') for m in not_uploaded: not_up_file.write("%s\n" % (str(binascii.hexlify(m)))) not_up_file.close() up_file = open(uploaded_out_filename, 'w') for m in Uploader.uploaded_macs: up_file.write("%s\n" % (str(binascii.hexlify(m)))) up_file.close() if options.remoteConn: self.comm.disconnect_tcp(options.remoteConn) log.info("----- Bulk Uploader End -----") print
global current_key if snap_addr not in key_dict: key_dict[snap_addr] = current_key current_key = chr(ord(current_key) + 1) k.press_key(key_dict[snap_addr]) sleep(0.050) k.release_key(key_dict[snap_addr]) #shell.SendKeys("a") print("Address: {0}, Key: {1}".format(snap_addr, key_dict[snap_addr])) SERIAL_TYPE = snap.SERIAL_TYPE_SNAPSTICK200 SERIAL_PORT = 0 # Create a SNAP instance our_instance = snap.Snap(funcs={}) our_instance.open_serial(SERIAL_TYPE, SERIAL_PORT) def on_error(e): print e get_rpc_observable("report_press") \ .group_by(lambda event: event["snapaddr"]) \ .flat_map(lambda device_taps: \ device_taps \ .map(lambda event: hexlify(event["snapaddr"])) \ #.throttle_first(40) \ ) \ .subscribe(print_value, on_error)
def SampledData(x, y, v): now = datetime.datetime.now() print "Current date and time using str method of datetime object:" print str(now) print("The sampled ADC data of address %s is %s No %s:" % (x, v, y)) AdddataTosqliteDatabase(x, v, y, 9, 9, 9, 9) # Required IO loop setup: scheduler = apy.ioloop_scheduler.IOLoopScheduler.instance( ) # Create an apy IOLoopScheduler comm = snap.Snap( scheduler=scheduler, funcs={ 'Ackknowledgement': Ackknowledgement, 'SampledData': SampledData, 'MeshNodes': MeshNodes }) # Create a SNAP Connect Instance that uses the apy scheduler tornado.ioloop.PeriodicCallback(comm.poll_internals, 5).start( ) #Setup tornado's IO loop by scheduling calls to SNAP Connect's poll_internals method # Create an SCF instanallbacks automatically: scf = SnapConnectFutures(comm) @coroutine def setup_serial(): """This function won't return until the serial connection is established.""" print "Connecting to serial..." com_port = '/dev/snap1' # Since Windows counts from COM1, 0 is COM1, 1 is COM2, etc. On Linux/OS X, use something like "/dev/ttyS1"
def __init__(self): self.snap = snap.Snap(funcs={'sendImage': self.send_image}) self.snap.open_serial(snap.SERIAL_TYPE_RS232, '/dev/ttyAMA0') self.log = logging.getLogger("JpgStreamClient") self.payload = ''
import pygame.midi from snapconnect import snap pygame.init() pygame.midi.init() comm = snap.Snap() comm.open_serial(snap.SERIAL_TYPE_RS232, 3) inp = pygame.midi.Input(1) #bells = [ #'\x03\xAC\x26', # BellR1 #'\x04\x6D\xC2', # BellR4 #'\x00\x63\x33', # BellR5 #'\x04\x00\x4A', # BellB1 #'\x03\xC4\x2D', # BellR3 #'\x04\x6D\xBA', # BellW2 #'\x04\xC7\x42', # BellW1 #'\x00\x81\x77', # BellR2 #] while True: comm.poll() if inp.poll(): events = inp.read(1000) for event in events: print event[0] r = "" for x in range(0, len(event[0])): r = r + chr(event[0][x])
from snapconnect import snap import sqlite3 # for database global comm comm = snap.Snap(funcs=rpcFuncs) # ist of Datas SensorData = [[1, 2], ["S1Val"], ["S2Val"], ["S3Val"], ["S4Val"], ["S5Val"]] #------------------------------------------------------------# # SensorDatas: database holds the all sensor datas #-----------------------------------------------------------# def sqliteDatabase(nodeId, S1T, S2T, S3T, S4T, S5T, S6T): conn = sqlite3.connect('SensorDatas.db') # ***** should happen only once c = conn.cursor() # create a cursor # ****time stamp of the datas collected with dates has to be added c.execute( 'create table SensorDatas(nodeAddress integer, sensor1 integer, sensor2 integer, sensor3 integer, sensor4 integer, sensor5 integer, sensor6 integer)' ) # Datas can be on the same table it need not be organized, since data can be read based on time and recents with search c.execute("insert into SensorDatas values(?, ?, ?, ?, ?, ?, ?)", (nodeId, S1T, S2T, S3T, S4T, S5T, S6T)) #------------------------------------------------------------# # node - Identity of the node, can be said as an address # sensor - Type of sensor # data - sensor data #-----------------------------------------------------------# # ***** datas from different sensors has not been taken care - which has to be fixed # def SensorValues(nodeId, sensor, data):
def __init__(self): self.comm = snap.Snap(funcs={}) self.comm.open_serial(SERIAL_TYPE, SERIAL_PORT)
from tornado.gen import coroutine import tornado import logging logging.basicConfig(level=logging.INFO) # Modify these values for your configuration. serial_type = snap.SERIAL_TYPE_SNAPSTICK100 serial_port = 0 # Replace node_addr with a specific MAC address. If you leave it as None, the example will use your bridge node. node_addr = None # SNAPconnect Futures (SCF) setup. Check the SCF Quick Start guide for an in-depth explanation of the setup. # Notice that you don't have to pass any callback methods into our SNAP instances. sc = snap.Snap(funcs={}) # These will all be automatically handled by SNAPconnect Futures. scf = SnapConnectFutures(sc) tornado.ioloop.PeriodicCallback(sc.poll, 5).start() @coroutine def setup_serial(): global node_addr logging.info("Connecting to serial...") # The open_serial future returns the bridge node's MAC Address. bridge_address = yield scf.open_serial(serial_type, serial_port) if bridge_address is None: logging.info("Unable to connect to bridge node") else: