class BridgeGlobal: def __init__(self): """ Create global bridge, initialize the bridge client and the lock for synchronization. """ # initialize bridge self.bridge = BridgeClient() # initialize synchronization lock self.lock = Lock() def get(self, key): """ Get from the bridge with synchronization. :param key: Key of the value (memory address). :return: Value of the key. """ # acquire the synchronization lock self.lock.acquire() # get the value value = self.bridge.get(key) # release the synchronization lock self.lock.release() # return the value return value def put(self, key, value): """ Put the value in the bridge with synchronization. :param key: Key of the value (memory address). :param value: Value to set. """ # acquire the synchronization lock self.lock.acquire() # set the value self.bridge.put(key, value) # release the synchronization lock self.lock.release()
import socket import time from bridgeclient import BridgeClient bridge = BridgeClient() sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(("", 5555)) while True: try: msg = sock.recv(1024) if msg: print msg bridge.put("FLAG", msg) except KeyboardInterrupt: break except Exception as err: print err pass sock.close()
time.sleep(5) count += 1 def numberOfSteps(previous, current): diff = current - previous if abs(diff) > 180: steps = (360 - max(previous, current)) + min(previous, current) if current > previous: steps = steps - (2 * steps) else: steps = diff steps = int(steps * (512.0 / 360.0)) return (steps) if resp == 200: weatherData = json.loads(urlobj.read()) windDir = weatherData['wind']['deg'] steps = numberOfSteps(prev_windDir, windDir) else: windDir = prev_windDir steps = -1 #creates a bridge object bricli = BridgeClient() #Pass variables to the bridge memory bricli.put('steps', str(steps)) bricli.put('windDir', str(int(windDir)))
check_list=[t[0] for t in odf_list] for f_name, index, pin_name in odf_list: if f_name not in cache.keys(): os.system(r'echo "default-on" > /sys/class/leds/arduino:blue:wlan/trigger') PIN = DAN.pull(f_name) cache[f_name] = PIN else: PIN = cache[f_name] if PIN != None: check_list.remove(f_name) if PIN[index] != None: client.put(pin_name, str(int(PIN[index]))) else: continue if f_name not in check_list: incomming[f_name] = (incomming[f_name] + 1) % 10000 #client.put('incomming_'+f_name, str(incomming[f_name])) #print ('Bridge: change incomming state of '+f_name) print '{f}[{d}] -> {p} = {v}, incomming[{f}] = {i}'.format( f=f_name, d=index, p=pin_name, v=str(int(PIN[index])), i=incomming[f_name], )
#!/usr/bin/python import sys sys.path.insert(0,"/usr/lib/python2.7/bridge/") from bridgeclient import BridgeClient client = BridgeClient() client.put("temp", 20.0) client.put("humid",60.0) client.put("water_duration_min", 10) client.put("food_duration_hr",5) client.put("ctempp",35.0) client.put("chumit",60.0)
import socket import time from bridgeclient import BridgeClient bridge = BridgeClient() sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind(("",5555)) while True : try : msg = sock.recv(1024) if msg : if msg == 'U' : bridge.put("D13","1") elif msg == 'D' : bridge.put("D13","0") print msg except KeyboardInterrupt : break except Exception as err: print err pass
# udpBridge.py import socket import time from bridgeclient import BridgeClient serverAddress = "192.168.1.2" serverPort = 8888 bridge = BridgeClient() inSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) inSocket.bind(("",8888)) while True: try: incoming = inSocket.recv(255) bridge.put("in", incoming) except KeyboardInterrupt: break except Exception as err: print err pass
for f_name, index, pin_name in odf_list: if f_name not in cache.keys(): os.system( r'echo "default-on" > /sys/class/leds/ds:green:wlan/trigger' ) PIN = DAN.pull(f_name) cache[f_name] = PIN else: PIN = cache[f_name] if PIN != None: check_list.remove(f_name) if PIN[index] != None: client.put(pin_name, str(int(PIN[index]))) else: continue if f_name not in check_list: incomming[f_name] = (incomming[f_name] + 1) % 10000 client.put('incomming_' + f_name, str(incomming[f_name])) print('Bridge: change incomming state of ' + f_name) print '{f}[{d}] -> {p} = {v}, incomming[{f}] = {i}'.format( f=f_name, d=index, p=pin_name, v=str(int(PIN[index])), i=incomming[f_name], )
if f_name not in cache.keys(): os.system( r'echo "default-on" > /sys/class/leds/arduino:blue:wlan/trigger' ) PIN = DAN.pull(f_name) cache[f_name] = PIN else: PIN = cache[f_name] if PIN != None: check_list.remove(f_name) if PIN[index] != None: client.put(pin_name, str(int(PIN[index]))) else: continue if f_name not in check_list: incomming[f_name] = (incomming[f_name] + 1) % 10000 #client.put('incomming_'+f_name, str(incomming[f_name])) #print ('Bridge: change incomming state of '+f_name) print '{f}[{d}] -> {p} = {v}, incomming[{f}] = {i}'.format( f=f_name, d=index, p=pin_name, v=str(int(PIN[index])), i=incomming[f_name], )
import sys, time, os sys.path.insert(0, "/usr/lib/python2.7/bridge/") from bridgeclient import BridgeClient client = BridgeClient() #ctempp = form.getvalue("tempp") #chumit = form.getvalue("Humit") client.put("ctempp",ctempp) client.put("chumit",chumit) print "Content-type: text/plain" print try: print "TEST !!!" except: print "Error"
addr = None #----- print "Setup the UDP Socket..." # set up UDP server. Python can do a simple server # in just a few lines.. sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind(("", UDP_PORT)) sock.settimeout(1.0) #----- # loop #repeats ad nauseam while True: # check if theres packets from serial, send if they are available arduino_data = bridge.get('from_arduino') if arduino_data and addr: #print "received %r with size %r" % (arduino_data, len(arduino_data)) sock.sendto(arduino_data, (addr[0], UDP_PORT)) bridge.put('from_arduino', "") # waits to receive data, timeout try: udp_data, addr = sock.recvfrom(512) #print "received %r from %r" % (udp_data, addr) if udp_data: bridge.put('from_udp', udp_data) except socket.timeout as err: pass
check_list=[t[0] for t in odf_list] for f_name, index, pin_name in odf_list: if f_name not in cache.keys(): os.system(r'echo "default-on" > /sys/class/leds/ds:green:wlan/trigger') PIN = DAN.pull(f_name) cache[f_name] = PIN else: PIN = cache[f_name] if PIN != None: check_list.remove(f_name) if PIN[index] != None: client.put(pin_name, str(int(PIN[index]))) else: continue if f_name not in check_list: incomming[f_name] = (incomming[f_name] + 1) % 10000 #client.put('incomming_'+f_name, str(incomming[f_name])) #print ('Bridge: change incomming state of '+f_name) print '{f}[{d}] -> {p} = {v}, incomming[{f}] = {i}'.format( f=f_name, d=index, p=pin_name, v=str(int(PIN[index])), i=incomming[f_name], )
import sys sys.path.insert(0, '/usr/lib/python2.7/bridge/') from bridgeclient import BridgeClient as BridgeClient bridge = BridgeClient() bridge.put('IsCold', '1')
sock2.connect((msg[1][0],3479)) queryIp = str(msg[1][0]) setIp = queryIp.split('.') del setIp[3] setwlan = [] seteth = [] a,b = commands.getstatusoutput('cat /sys/class/net/wlan0/operstate') if b=='up': ipwlan = get_ip_address('wlan0') setwlan = ipwlan.split('.') del setwlan[3] a,b = commands.getstatusoutput('cat /sys/class/net/eth1/operstate') if b=='up': iplan = get_ip_address('eth1') seteth = iplan.split('.') del seteth[3] print setIp, setwlan, seteth if setIp==setwlan: sock2.sendto( bytes("{\"uid\":\"arduinozero\",\"DisplayName\":\"SamiDevice\",\"ip\":\""+get_ip_address('wlan0')+"\",\"type\":\"Transformer\"}"), (msg[1][0], 3479) ) elif setIp==seteth: sock2.sendto( bytes("{\"uid\":\"arduinozero\",\"DisplayName\":\"SamiDevice\",\"ip\":\""+get_ip_address('eth1')+"\",\"type\":\"Transformer\"}"), (msg[1][0], 3479) ) sock2.close() bridge.put("to_arduino",msg[1][0]) #server ip address except Exception as err: print err pass
DAN.profile['df_list'] = [t[0] for t in idf_list] for t in odf_list: if t[0] not in DAN.profile['df_list']: DAN.profile['df_list'].append(t[0]) print('Detected features:') for f_name in DAN.profile['df_list']: print(' {}'.format(f_name)) DAN.device_registration_with_retry(custom.ServerIP) #os.system(r'echo "heartbeat" > /sys/class/leds/ds:green:usb/trigger') #For ArduinoYun Only, need to install packages. "opkg install kmod-ledtrig-heartbeat" #os.system(r'echo "default-on" > /sys/class/leds/ds:green:usb/trigger') #For ArduinoYun Only. LED constant ON. os.system(r'echo "timer" > /sys/class/leds/ds:green:usb/trigger' ) #For ArduinoYun Only. LED Blink. client.put('Reg_done', '1') incomming = {} for f_name in [t[0] for t in odf_list]: incomming[f_name] = 0 ################################################## Open Counter storage file previous_counter = {'Bugs': 0, 'RainMeter': 0} current_counter = {'Bugs': 0, 'RainMeter': 0} f_cache_name = r'/root/previous_counter' try: f_cache = open(f_cache_name, 'r+') except: f_cache = open(f_cache_name, 'w+') timestamp = str(datetime.datetime.now()) f_cache.write('0,0,' + timestamp + ',')
#----- # loop #repeats ad nauseam while True: # waits until it receives data data, addr = sock.recvfrom(512) # print "received %r from %r" % (data, addr) if data == "DISCOVERY_PACKET": hardware_count = bridge.get('hardware_count') data += ',' data += str(hardware_count) state_update = bridge.get('state_update') data += ',' data += state_update # sends discovery packet sock.sendto(data, (addr[0], UDP_PORT)) elif data == "7": bridge.put('udp', data) state_update = bridge.get('state_update') sock.sendto(state_update, (addr[0], UDP_PORT)) else: # puts data on arduino bridge bridge.put('udp', data) if should_echo and (data != last_packet): sock.sendto(data, (addr[0], UDP_PORT)) last_packet = data
import socket import time from bridgeclient import BridgeClient bridge = BridgeClient() sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(("", 5555)) while True: try: msg = sock.recv(1024) if msg: if msg == 'U': bridge.put("D13", "1") elif msg == 'D': bridge.put("D13", "0") print msg except KeyboardInterrupt: break except Exception as err: print err pass
os.system( r'echo "none" > /sys/class/leds/ds:green:wlan/trigger') if reConnecting: LED_flash(1) reConnecting = 0 except Exception as e: print(e) LED_flash(0) if str(e).find('mac_addr not found:') != -1: print('Reg_addr is not found. Try to re-register...') reConnection = 1 device_registration_with_retry() else: print('Connection failed due to unknow reasons.') reConnecting = 1 time.sleep(1) if datetime.datetime.now( ).hour == 0 and not isChange: # reset counter to zero at 00 o'clock client.put('resetCounter', str(resetCounter)) isChange = 1 resetCounter = resetCounter + 1 % 1000 print('Reset Bug and RainMeter counter.') if datetime.datetime.now().hour == 12: isChange = 0 time.sleep(Comm_interval)
DAN.profile['df_list'] = [t[0] for t in idf_list] for t in odf_list: if t[0] not in DAN.profile['df_list']: DAN.profile['df_list'].append(t[0]) print('Detected features:') for f_name in DAN.profile['df_list']: print(' {}'.format(f_name)) DAN.device_registration_with_retry(custom.ServerIP) #os.system(r'echo "heartbeat" > /sys/class/leds/ds:green:usb/trigger') #For ArduinoYun Only, need to install packages. "opkg install kmod-ledtrig-heartbeat" #os.system(r'echo "default-on" > /sys/class/leds/ds:green:usb/trigger') #For ArduinoYun Only. LED constant ON. os.system(r'echo "timer" > /sys/class/leds/ds:green:usb/trigger' ) #For ArduinoYun Only. LED Blink. client.put('Reg_done', '1') incomming = {} for f_name in [t[0] for t in odf_list]: incomming[f_name] = 0 while True: try: cache = {} check_list = [t[0] for t in odf_list] for f_name, index, pin_name in odf_list: if f_name not in cache.keys(): os.system( r'echo "default-on" > /sys/class/leds/ds:green:wlan/trigger' )
# loop to store most recent 20 temp/humid values max_str = 20 ttt = client.get("temp") jjj = ttt[0:len(ttt)-2] #for num in range(19): # shift former values, drop the oldest values if (len(jjj) < max_str): for num in range(len(jjj),20): jjj.append(0) #first_query = os.environ["QUERY_STRING"] #chk = client.get("temp"); #pp = len(chk) #if (first_query == ""): # ttt[0] = temps #else: # ttt[0] = 20 jjj.insert(0,temps) #ttt = [122.0,125,111,temps] ttt = jjj client.put("temp",ttt); # store the recent value hhh = client.get("temp") print "Content-type: text/plain" print try: for num in range(20): if (num < len(hhh)): print hhh[num] except: print "Error"
from time import sleep from bridgeclient import BridgeClient # Init Arduino Bridge bridgeClient = BridgeClient() # Init IOT Server Socket Object socketClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: # Connect IOT Server socketClient.connect(('39.104.87.214', 7280)) socketClient.settimeout(15) # No Error bridgeClient.put('ERROR', '2') break except socket.error, e: print "Can't connect to Server as ", e.errno sleep(1) # Has Error bridgeClient.put('ERROR', '1') continue while True: # Get Server Data try: data = socketClient.recv(1024) if not data: print('Not data') elif 'LED_ON' == data: