def __init__(self, mode=BME280_OSAMPLE_1, address=BME280_I2CADDR, i2c=None, **kwargs): # Check that mode is valid. if mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4, BME280_OSAMPLE_8, BME280_OSAMPLE_16]: raise ValueError( 'Unexpected mode value {0}. Set mode to one of ' 'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or ' 'BME280_ULTRAHIGHRES'.format(mode)) self._mode = mode # Create I2C device. if i2c is None: raise ValueError('An I2C object is required.') self._device = Device(address, i2c) # Load calibration values. self._load_calibration() self._device.write8(BME280_REGISTER_CONTROL, 0x3F) self.t_fine = 0
def __init__(self, i2c, mode=_BME280_OSAMPLE_1, address=_BME280_I2CADDR, debug=False, raw=False, calibrate=None): # Check that mode is valid. if mode not in [ _BME280_OSAMPLE_1, _BME280_OSAMPLE_2, _BME280_OSAMPLE_4, _BME280_OSAMPLE_8, _BME280_OSAMPLE_16 ]: raise ValueError( 'Unexpected mode value {0}. Set mode to one of ' 'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or ' 'BME280_ULTRAHIGHRES'.format(mode)) self._mode = mode # Create I2C device. if not type(i2c) is I2C: raise ValueError('An I2C object is required.') self._device = Device(address, i2c) # Load calibration values. self._load_calibration() self._device.write8(_BME280_REGISTER_CONTROL, 0x3F) self.t_fine = 0 self.sea_level_pressure = 1010.25 """Pressure in hectoPascals at sea level. Used to calibrate ``altitude``.""" self.raw = raw self.calibrate = { 'temperature': None, 'pressure': None, 'humidity': None, 'altitude': None } if (not raw) and (type(calibrate) is dict): for k in calibrate.keys(): if (not k in self.calibrate.keys()) or ( not type(calibrate[k]) is list): continue self.calibrate[k] = calibrate[k]
def details(): global api if (api.login_token is None): raise LoginError data = api.get_qos_detail() devices = data['data']['list'] devs = [] for device in devices: util.log(device, file=True, mode='w+') device_object = Device() device_object.from_response(device) """storage.save_device_detail(device_object) stored_device = storage.get_by("mac", device_object.mac) device_object.details = stored_device['data']['details']""" devs.append(device_object.to_dict()) devs = sorted(devs, reverse=True, key=lambda i: (i['statistics']['downspeed'])) return jsonify(devs)
def read_Xml(devices): inTagGroup = False inDevicesContent = False inTagDevice = False #xmlFile=open('prueba.xml','r') xmlFile = open('wurfl-2.3.xml', 'r') line = xmlFile.readline() while line != '': line = xmlFile.readline() if not (inDevicesContent): if searchDevices(line) != -1: inDevicesContent = True else: if not (inTagDevice): if searchDevice(line) != -1: #Instancia de dispositivo provisional hasta que se finalic el tag device = Device.Device() inTagDevice = True extractDeviceAtt(line, device) else: if not (inTagGroup): if searchGroup(line) != -1: inTagGroup = True temp = extractGroupId(line) extractGroupAtt(line, device) else: if searchCapability(line) != -1: capability = Capability.Capability() extractNameCapability(line, capability) extractValueCapability(line, capability) addCapabilities(device.get_groups().get(temp), capability) if searchEndGroup(line) != -1: inTagGroup = False if searchEndDevice(line) != -1: devices[device.get_id()] = device inTagDevice = False if searchEndDevices(line) != -1: inDevicesContent = False
def preprocessing(pcap_input=None, captured_object=None): # Prepare some variables one_hot_protocol = {"TCP": 0, "UDP": 1, "HTTP": 2} device = {} # group by source IP if captured_object is None: cap = ps.FileCapture(pcap_input, only_summaries=True) else: cap = captured_object # Fisrt, extract packet infomations for value in cap: # only TCP, UDP, and ICMP protocol if value.protocol != "TCP" and value.protocol != "UDP" and value.protocol != "HTTP": continue # packet info packet_info = { "size": value.length, "time": value.time, "protocol": value.protocol, "destination": value.destination, } IP = value.source if IP in device: device[IP].packet_info.append(packet_info) else: device[IP] = dv.Device() device[IP].packet_info.append(packet_info) # Second, record time slice with 10 sec time window. for source_IP in device: # initialize time window first = float(device[source_IP].packet_info[0]["time"]) start = 0 index = 0 for value in device[source_IP].packet_info: current = float(value["time"]) if current - first > 10: # 10 sec time window device[source_IP].time_window.append( start) # record time slice # update time slice first = current start = index index = index + 1 # last slice device[source_IP].time_window.append(start) device[source_IP].time_window.append(index) # Third, feature engineering for source_IP in device: for i in range(0, len(device[source_IP].time_window) - 1): # loop over time window start = device[source_IP].time_window[i] end = device[source_IP].time_window[i + 1] num_of_endpoint = device[source_IP].count_endpoint(start, end) index = 0 for value in range(start, end): # one time window feature_data = { "size": int(device[source_IP].packet_info[value]["size"]), "one_hot_protocol": one_hot_protocol[device[source_IP].packet_info[value] ["protocol"]], "bandwidth": 0.0, "endpoint": num_of_endpoint, "T1": 0.0, "T2": 0.0, "T3": 0.0, } device[source_IP].feature_data.append(feature_data) # delta time, get T1 feature_data["T1"] = float( device[source_IP].packet_info[value]["time"]) - float( device[source_IP].packet_info[value - 1]["time"]) # delta T1, get T2 feature_data["T2"] = feature_data["T1"] - device[ source_IP].feature_data[index - 1]["T1"] # delta T2, get T3 feature_data["T3"] = feature_data["T2"] - device[ source_IP].feature_data[index - 1]["T2"] device[source_IP].feature_data[index] = feature_data index = index + 1 # The first three packets have abnormal feature data for T1, T2, T3 since they can not be defined. # So we'll gonna drop those three packets. return device
#!/usr/bin/env python # # This Beastie will receive all communication from mod_com.py #import socket import zmq import time import sys import Device as dev import Direction as dir #initialise device servo = dev.Device() #set initial positions to neutral neutral = [1500, 1500, 1500, 1500] servo.set_targets(4, 0, neutral) def processCmd(message): global servo mes = message.split(':') if mes[1] == 'all': dir.stop_all(servo) if mes[1] == 'forward': dir.forward_all(servo, int(mes[2])) if mes[1] == 'reverse': dir.reverse_all(servo, int(mes[2])) if mes[1] == 'left': dir.turn_left(servo, int(mes[2])) if mes[1] == 'right':
# "water" when the water flooding sensor pin is triggered. # The goal of this example is to show you how you can receive network commands # to your devices through the AWS device communication infrastructure, after # setting one of the device's environmental inputs. # # This is one real world example of a very simple functional test you would run # for your devices. import time import spanner import Device from AWSDevice import Testboard device = Device("DEVID_1") testboard = Testboard("Wubby_Test") # Our Product's Input will be connected the Testboard's Pin D3, making it our # Output Pin OUTPUT_PIN = "D3" def test_raise_flooding_alarm(): # set PIN state testboard.digitalWrite(OUTPUT_PIN, HIGH) time.sleep(2) # Ask spanner to wait for 3 seconds while at the same time checking if we
# The goal of this example is to show you how you can receive network commands # to your devices through the AWS device communication infrastructure, after # setting one of the device's environmental inputs. # # This is one real world example of a very simple functional test you would run # for your devices. import time import spanner import Device from AWSDevice import Testboard DEVICE_ID = "200023001347343438323536" device = Device(DEVICE_ID) TESTBOARD_ID = "200023001347343438323536" testboard = Testboard(TESTBOARD_ID) # Our Product's Input will be connected the Testboard's Pin D3, making it our # Output Pin OUTPUT_PIN = "D3" def test_raise_flooding_alarm(): # set PIN state testboard.digitalWrite(OUTPUT_PIN, HIGH) time.sleep(2)
from Services import EnvironmentService, BatterySensor, UserInterfaceService, MotionService, DeviceDelegate import Device from Device import Device from urllib.request import urlopen ##Mac 1: FD:88:50:58:E7:45 ##Mac 2: E4:F6:C5:F7:03:39 ## MAC address Device device global MAC if __name__ == "__main__": MAC = str(sys.argv[1]) print("Connecting to " + MAC) Device1 = Device(MAC) print("Connected...") print("Bonding...") Device1.setSecurityLevel("medium") print("Bonded...") print("Enabling Services...") Device1.battery.enable() #~ Device1.ui.enable() Device1.motion.enable() Device1.setDelegate(DeviceDelegate()) print('Services Enabled...') print('Battery Level(1): ', Device1.battery.b_read(), '%')
def message_received(self, client, server, message): logging.debug("received: " + message) with self.clientLock: if self.client != client: logging.debug("dropping message from unknown client") return try: jsonMessage = json.loads(message) if self.autoRegister: if jsonMessage['message_type'] == "gateway_register": self.WSServer.send_message( self.client, '{ "message_type" : "gateway_accepted" }') self.connected = True self.newConnection.notify_all() return if self.autoData: if jsonMessage['message_type'] == "sensor_data_export": sensorData = SensorData.SensorData() sensorData.fromJSON(jsonMessage['data'][0]) self.dataMessages.append(sensorData) self.newDataMessage.notify_all() response = {} response['message_type'] = "sensor_data_confirm" response['id'] = jsonMessage['id'] logging.debug("sending message: " + json.dumps(response)) self.WSServer.send_message(self.client, json.dumps(response)) return if self.prePaired is not None: if jsonMessage['message_type'] == "device_list_request": if jsonMessage['device_prefix'] in self.prePaired: response = {} response['message_type'] = "device_list_response" response['id'] = jsonMessage['id'] response['status'] = 1 response['devices'] = self.prePaired[ jsonMessage['device_prefix']] logging.debug("sending message: " + json.dumps(response)) self.WSServer.send_message(self.client, json.dumps(response)) return if self.autoResponse: if jsonMessage['message_type'] == "response_with_ack": self.responseMessages.append(jsonMessage) self.newResponseMessage.notify_all() response = {} response['message_type'] = "generic_ack" response['id'] = jsonMessage['id'] response['status'] = jsonMessage['status'] logging.debug("sending message: " + json.dumps(response)) self.WSServer.send_message(self.client, json.dumps(response)) return if jsonMessage['message_type'] == "generic_response": self.responseMessages.append(jsonMessage) self.newResponseMessage.notify_all() return if self.autoNewDevice: if jsonMessage['message_type'] == "new_device_request": device = Device.Device(jsonMessage) self.newDevices.append(device) self.newDeviceMessage.notify_all() response = {} response['message_type'] = "generic_ack" response['id'] = jsonMessage['id'] response['status'] = 1 logging.debug("sending message: " + json.dumps(response)) self.WSServer.send_message(self.client, json.dumps(response)) return except Exception as ex: logging.error("Exception: " + str(ex)) pass self.messages.append(message) self.newMessage.notify_all()
import pickle, os from Device import * keys = {} devices = {} current_permission = 0 max_level_permission = 5 current_device = Device("none", max_level_permission, lambda: None) def add_device(name, level, purpose): devices.append(Device(name, level, purpose)) def allow_run(level, device): if device in devices: if level == max_level_permission: return device.run else: if device.perms(level): return device.run else: print("Insufficient permissions. Please ask a parent for help.") else: print("Device not installed. Please install the device, or select an already installed device.") def select_device(): nonlocal current_permission, current_device, devices print("Please select a device from the list below:") active = [dev.append() for dev in devices.keys() if devices[dev].perms(current_permission)] user_input = input("") if user_input in active: current_device = devices[user_input]
def discover_device(self, ip, id): d = Device(ip, id) if (d.info): self.devices.append(d)
def discover_device(self, ip, id): """Attempts to connect with a single device""" d = Device(ip, id) if (d.info): self.devices.append(d)
def reply_handler_wrapper(obj_path): if not callable(reply_handler): return reply_handler(Device.Device(obj_path))
def pars_yaml(self, filename): try: with open(filename, "r", encoding="utf8") as f: s = yaml.load(f) except Exception as e: logging.warning("open file error, filename : %s, try another method" % filename) s = yaml.load(file(filename)) finally: # if True: # Initialize configuration information if 'config' in s: cfg = s['config'] if 'version' in cfg: self.config.version = cfg['version'] if 'id' in cfg: self.config.id = cfg['id'] else: self.config.id = '' if 'desc' in cfg: self.config.desc = cfg['desc'] if 'cloud' in cfg: self.config.cloud = cfg['cloud'] if 'mode' in cfg: self.config.mode = cfg['mode'] if 'others' in cfg: self.config.others = cfg['others'] # Initialize device information for dev in s['devices']: d = Device.Device() d.id = dev['id'] d.protocol = dev['protocol'] d.address = dev['address'] d.port = str(dev['port']) d.machine_address = int(dev['machine_address']) if 'param' in dev: d.param = dev['param'] d.byte_order = dev['byte_order'] for group in dev['groups']: group_name = str(group['name']) g = Group.Group(name=group_name, interval=group['interval']) g.read_backoff = group["read_backoff"] for var in group['vars']: try: address = var['address'] var_type = var['type'] var_id = var['id'] var_desc = var['desc'] if 'writeable' in var: writeable = var['writeable'] else: writeable = None io = ModbusIO.ModbusIO(mb_id=var_id, address=address, mb_type=var_type, desc=var_desc, writeable=writeable) io.expression = var['expression'] g.io[var_id] = io except Exception as e: logging.warning('IO setting error:%s', e) d.groups[group_name] = g self.devices[d.id] = d
"//android.widget.Button[@resource-id='com.rebtel.android:id/next_button']" ) el.click() time.sleep(1) writeInfo('Hang up ...') el = self.driver.find_element_by_xpath( "//android.widget.ImageView[@resource-id='com.rebtel.android:id/hangupButton']" ) el.click() time.sleep(3) self.nevigateTo('Recent') writeInfo('Verifying the call in Recent menu ...') try: el = self.driver.find_element_by_xpath( "//android.widget.TextView[@resource-id='com.rebtel.android:id/phoneNumber']" ) phoneNumber = el.text except: phoneNumber = None self.assertEqual( phoneNumber, '+8801717379480', "Dialed phone number doesn't exist in the Recent menu!") if __name__ == 'RebtelAndroidTest': ''' Recruit the intended device to run at. ''' d = Device() device = d.getDevice('RebtelAndroidTest')
def add_device(name, level, purpose): devices.append(Device(name, level, purpose))
# Simulation temporal window, step and saving interval tWidth = 2.0 dt = 2.5e-3 samplingInterval = 5 # Kernel file KernelPath = "kernel_tracer.cl" ######################## SIMULATION ############################ # Init image im = Image.Image(sourcePath, Z, Kx, Ky, Kz) # Init device dvc = Device.Device(KernelPath) dvc.initialize(im.Grid) # Time grid tGrid = np.arange(0.0, tWidth + dt, dt) # Photons push for i in range(len(tGrid)): t = np.float32(tGrid[i]) dvc.push((im.Rays, ), t, dt) if i % samplingInterval == 0: # Copy from device to host dvc.copyToHost(im.Grid) # Save the result im.saveImage("output.png")
print("Loaded! Gattlib works?") serviceB = BeaconService() serviceD = DiscoveryService() beacons = serviceB.scan(2) beacons2 = beacons devices = serviceD.discover(2) devices2 = devices service = BeaconService() print("Beacons: \n {}".format(beacons)) beaconsL = BeaconList('Beacons') i = 0 for address, data in list(beacons.items()): b = Beacon(data, address, beacons2, i) beaconsL.add(b) i += 1 print(b) print("Devices: \n {}".format(devices)) devicesL = DeviceList('Devices') j = 0 for address, name in list(devices.items()): # print("name: {}, address: {}".format(name, address)) d = Device(address, name, devices2, j) devicesL.add(d) j += 1 print(d) print("Successfully Initialized.") print(devicesL) print(beaconsL)
def getvalues(self): self.logr.info('Starting to apply values....') items = str(self.devicelist.GetValue()) list = items.split('\n') sc = ''.join(list[0]) freq = '' dlubr = '' ulubr = '' cp = '' chsize = '' radio_mode = '' adapt = '' cir = '' pir = '' syslog = '' upgrade_value = '' vlanfilter = '' if self.dlulcir.IsEnabled(): cir = str(self.dlulcir.GetValue()) self.logr.info('Set CIR') if self.dlulpir.IsEnabled(): pir = str(self.dlulpir.GetValue()) self.logr.info('Set PIR') if self.valuefreq.IsEnabled(): freq = str(self.valuefreq.GetValue()) freq = 'set rffreq ' + freq self.logr.info('Set Frequency') if self.valuedlubr.IsEnabled(): dlubr = str(self.valuedlubr.GetValue()) self.logr.info('Set DL UBR') if self.valueulubr.IsEnabled(): ulubr = str(self.valueulubr.GetValue()) self.logr.info('Set UL UBR') if self.cyclic_prefix.GetSelection() != 2: if self.cyclic_prefix.GetSelection() == 0: cp = 'set cp 0' else: cp = 'set cp 1' self.logr.info('Change cycle prefix') if self.radio_mode.GetSelection() != 2: if self.radio_mode.GetSelection() == 0: radio_mode = 'set radio on' else: radio_mode = 'set radio off' self.logr.info('Set radio mode') if self.chsize.GetSelection() != 10: if self.chsize.GetSelection() == 0: chsize = 'set chwidth 0.875' elif self.chsize.GetSelection() == 1: chsize = 'set chwidth 1.25' elif self.chsize.GetSelection() == 2: chsize = 'set chwidth 1.75' elif self.chsize.GetSelection() == 3: chsize = 'set chwidth 2.5' elif self.chsize.GetSelection() == 4: chsize = 'set chwidth 3.5' elif self.chsize.GetSelection() == 5: chsize = 'set chwidth 5' elif self.chsize.GetSelection() == 6: chsize = 'set chwidth 7' elif self.chsize.GetSelection() == 7: chsize = 'set chwidth 10' elif self.chsize.GetSelection() == 8: chsize = 'set chwidth 14' elif self.chsize.GetSelection() == 9: chsize = 'set chwidth 20' self.logr.info('Change channel size') if self.text_vlan.IsEnabled(): vlanfilter = str(self.text_vlan.GetValue()) vlanfilter = 'set vlanfilter on ' + '\n' + 'set allowedvlans ' + vlanfilter self.logr.info('Set Vlan Filter') else: vlanfilter = 'set vlanfilter off ' + '\n' self.logr.info('Set Vlan Filter') if self.text_syslog.IsEnabled(): syslog = str(self.text_syslog.GetValue()) syslog = 'set syslogip ' + syslog self.logr.info('Set Syslog ip address:') if self.adapt.GetSelection() != 2: if self.adapt.GetSelection() == 0: adapt = 'on ' else: adapt = 'off ' self.logr.info('Set modulation type') items = str(self.addtcommands.GetValue()) listcommands = items.split('\n') device = Device.Device(sc, freq, dlubr, ulubr, cp, chsize, radio_mode, adapt, cir, pir, vlanfilter, syslog, listcommands) return device
sys.stderr.write( "Error: Can't find the file 'ligtweaveComponenet.py' in the directory containing %r. \n" % __file__) sys.exit(1) #-------------------------------------------------------------- # global vars #-------------------------------------------------------------- selectedroom_defaultvalue = {'name': 'Hallway', 'roomConfigCollection': []} selectedroom = selectedroom_defaultvalue selectedfloor = 1 testJSONCollection = [[{ 'name': 'Livingroom', 'roomConfigCollection': [ device.Device(1, 1, "lamp", "Lamp"), device.Device(1, 1, "lamp", "StaLamp") ] }], [{ 'name': 'Bedroom', 'roomConfigCollection': [device.Device(2, 1, "lamp", "Lamp")] }, { 'name': 'Library', 'roomConfigCollection': [device.Device(1, 1, "lamp", "Lamp")] }, { 'name':
import os import sys from time import sleep from kthread import KThread sys.path.append('src\\') sys.path.append('src/') from NetSocket import * from Device import * from TTS import * from SpeechRecognition import * s = NetSocket() s.open_connection("192.168.0.30") device = Device({'name': 'WinDesktop', 'target': 'phone'}) threads = [] tts = TTS() sr = SpeechRecognition() # Threads that receives data from server def receive_thread(): try: while (True): message = s.recv() tts.speak(message) pass except KeyboardInterrupt: kill_all() sys.exit()
# import json # import requests successCount = 0 # not needed in production. Used for script testing. failureCount = 0 # not needed in production. Used for script testing. exceptionCount = 0 # not needed in production. Used for script testing. startTime = time.time() # Set the up required variables for Azure Iot Hub AzureDeviceName = "TestPi" AzureDeviceKey = "1Hfen5Do2lS+RgtCe8RftdfqzmpgmMbXOj0i8ucEk+A=" AzureHubName = "SPMOilMonitor" sasTimeOut = 86400 #24 hours # Create the device object and get the initial sas device = Device.Device(AzureHubName.lower(), AzureDeviceName, AzureDeviceKey) device.create_sas(sasTimeOut) print('Initial sas created: ' + device._sas) print('Started at: ' + str(datetime.datetime.utcnow()) + ' in seconds: ' + str(time.time())) while True: # Acquire and format the time stamp timeStamp = datetime.datetime.utcnow() timeStamp_str = timeStamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ') # Acquire the CPU core temperature temp = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3 # Create the data string
reg = resolve(my_json['payload']) except ValueError: print "Value Erro on returning Json" ini = Init(Config.get("Amqp", "user"), Config.get("Amqp", "pass"), Config.get("couchDB", "user"), Config.get("couchDB", "pass")) channel.basic_consume(on_request, queue=Config.get("Admin", "queue")) dev_status = Config.get("Admin", "dev_status") route = Route.Route(channel) karaf = Karaf.Karaf(Config.get("Karaf", "user"), Config.get("Karaf", "pass"), Config.get("Admin", "app_storage"), Config.get("General", "location") + "/apps/", Config.get("General", "location") + "/configs/", Config.get("Karaf", "location") + "/") device = Device.Device(Config.get("couchDB", "user"), Config.get("couchDB", "pass"), Config.items("DeviceQ")) res = Resource.Resource( Config.get("couchDB", "user"), Config.get("couchDB", "pass"), Config.get("General", "Gateway_Name"), Config.items("ResourceQ") ) ##Redo Resource so that they are store in config not admin reg = Region.Region(Config.get("Amqp", "user"), Config.get("Amqp", "pass"), Config.get("Amqp", "virt"), Config.get("couchDB", "user"), Config.get("couchDB", "pass")) #Do Initial Request and Modify what needs to be modified print("Sending Initial Request to Cloud") initialRequest(Config, reg) #Set variables for later use and start RPC request queueu controller_name = Config.get("General", "Gateway_Name") print(" [x] Awaiting RPC requests")
# a product's actual usage # # The goal of this example is to show you how you can expect a network command # from your devices through the AWS device communication infrastructure. # # In our particular example, we are only waitinf for a "heartbeat" command which # should happen every two seconds, so we should definitely get one if we wait # for 3. Of course this would never be a real world example, it's only for # educational purposes import time import spanner import Device from AWSDevice device = Device("device_name") def expect_network_cmd(): # Ask spanner to wait for 3 seconds while at the same time checking if we # got a command from the device result = device.waitForCommand(3) # Make sure we actually got a command, and we didn't just time out spanner.assertTrue(result.commandReceived) # Double check the name of the command spanner.assertEqual("heartbeat_event", command.name) spanner.assertEqual("", command.value) if __name__ == "__main__":
import os import sys sys.path.append('src\\') sys.path.append('src/') from NetSocket import * from Device import * s = NetSocket(t="ROUTER") s.open_connection("0.0.0.0") message = None server_device = Device({'name': 'Sky_server', 'target': 'None'}) name_to_client = {} # Gets the name of a client def map_client(client): for k in name_to_client.keys(): if (name_to_client[k] == client): return k # Formats string to usable format def clean(text): text = text.replace("\'s", " is") text = text.replace("n\'t", " not") return text try: while (1):