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()
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()
def custom_callback_accepted(client, userdata, message): """ Callback to handle passing a custom message to the other processor via the bridge """ print('Callback', message.payload) msg = json.loads(message.payload) brightness = msg['state']['desired']['brightness'] color = msg['state']['desired']['color'] power = msg['state']['desired']['power'] code = 'NOOP' if brightness != '*': code = 'B' + str(brightness) if color != '*': code = 'C' + color if power != '*': code = 'P' + power client = BridgeClient() client.mailbox(code) print("Sent Message:", code)
#!/usr/bin/python import cgi,sys,os form = cgi.FieldStorage() sys.path.insert(0,"/usr/lib/python2.7/bridge/") from bridgeclient import BridgeClient temps = float(form.getvalue("tempp")) client = BridgeClient() # 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
from iottalkpy import dan from config import IoTtalk_URL, device_model, device_name, Comm_interval, idf_list import sys import time import os import datetime import json sys.path.insert(0, '/usr/lib/python2.7/bridge/') from bridgeclient import BridgeClient client = BridgeClient() def LED_flash(LED_state): if LED_state: client.put('Reg_done', '1') os.system(r'echo "timer" > /sys/class/leds/ds:green:usb/trigger' ) #For ArduinoYun Only. LED Blink. else: client.put('Reg_done', '0') os.system(r'echo "none" > /sys/class/leds/ds:green:usb/trigger') ''' IoTtalk data handler ''' def on_data(odf_name, data): print("[da] [data] ", odf_name, data)
# port for the UDP connection to bind to UDP_PORT = 10008 last_packet = "" # Echoing back commands slows down the speed that lights update but it gives # more reliability since you know when a packet is received. Set this to # false to increase the light update speed. should_echo = True #----- # bridge setup # set up the serial port for communication with # the yun's microprocessor print "Setup the Arduino bridge..." bridge = BridgeClient() # Very important! Without this comannd, communication will work # but will be significantly slower, since it will open and close # sockets in each function. bridge.begin() #----- 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))
import commands import fcntl import struct sys.path.insert(0, '/usr/lib/python2.7/bridge/') from bridgeclient import BridgeClient def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) bridge = BridgeClient() sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind(('',3479)) while True : try: msg = sock.recvfrom(1024) print msg[1] #Get IP, Port sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock2.connect((msg[1][0],3479)) queryIp = str(msg[1][0]) setIp = queryIp.split('.') del setIp[3]
odf_list = custom.odf() idf_list = custom.idf() 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) BridgeClient().put('Reg_done', '1') incomming = {} previous_outcomming = {} for f_name in [t[0] for t in odf_list]: incomming[f_name] = 0 for f_name in [t[0] for t in idf_list]: previous_outcomming[f_name] = '' while True: try: cache = {} check_list = [t[0] for t in odf_list] for f_name, index, pin_name in odf_list:
import sys import time import DAN import requests import os sys.path.insert(0, '/usr/lib/python2.7/bridge/') from bridgeclient import BridgeClient import custom client = BridgeClient() custom.profile_init() odf_list = custom.odf() idf_list = custom.idf() 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)) def LED_flash(LED_state): if LED_state: client.put('Reg_done', '1') os.system(r'echo "timer" > /sys/class/leds/arduino:white:usb/trigger') #For ArduinoYun Only. LED Blink.
#!/usr/bin/python import sys,time,socket sys.path.insert(0,"/usr/lib/python2.7/bridge/") from bridgeclient import BridgeClient client = BridgeClient() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(5) while 1: ttt = client.get("temp") dur = client.get("water_duration_min") print ttt[0] print dur if float(ttt[0]) > 35.0: print "turn on valve\n" try: s.connect(("192.168.240.146",8081)) except: print "Unable to connect" exit() s.send("GET /a0 /HTTP1.1 \r\n") time.sleep(int(dur)) print "turn off valve\n" s.send("GET /a1 HTTP/1.1\r\n") s.close() time.sleep(5) time.sleep(5)
#!/usr/bin/python import sys sys.path.insert(0, '/usr/lib/python2.7/bridge/') from bridgeclient import BridgeClient if len(sys.argv) < 2: print "Missing message." sys.exit(1) bridge = BridgeClient() msg = sys.argv[1] print "Sending message: ", msg bridge.send(msg)
import sys import time import DAN import requests import os import datetime sys.path.insert(0, '/usr/lib/python2.7/bridge/') from bridgeclient import BridgeClient import custom client = BridgeClient() custom.profile_init() odf_list = custom.odf() idf_list = custom.idf() 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)) def LED_flash(LED_state): if LED_state: client.put('Reg_done', '1')
import sys sys.path.insert(0, '/usr/lib/python2.7/bridge/') from bridgeclient import BridgeClient as BridgeClient bridge = BridgeClient() bridge.put('IsCold', '1')
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
#!/usr/bin/python2.7 import sys, socket sys.path.insert(0, '/usr/lib/python2.7/bridge') 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
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # Test for pin thread # - # @author giuliobosco # @version 1.0 (2019-04-21 - 2019-04-21) import sys sys.path.insert(0, '/usr/lib/python2.7/bridge') from pin_thread import PinThread from key_manager import KeyManager from bridgeclient import BridgeClient from time import sleep bridge = BridgeClient() key_manager = KeyManager('000000000000', '000000001234', '10.8.16.111:8080') pin_thread = PinThread(key_manager=key_manager, pin='D6', bridge=bridge) pin_thread.start() sleep(10) pin_thread.interrupt()
from bridgeclient import BridgeClient #----- # config # port for the UDP connection to bind to UDP_PORT = 10008 #----- # bridge setup # set up the serial port for communication with # the yun's microprocessor print "Setup the Arduino bridge..." bridge = BridgeClient() # Very important! Without this comannd, communication will work # but will be significantly slower, since it will open and close # sockets in each function. bridge.begin() 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)
#!/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 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"
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)))
import sys import time import DAN import requests import os sys.path.insert(0, '/usr/lib/python2.7/bridge/') from bridgeclient import BridgeClient import custom client = BridgeClient() custom.profile_init() odf_list = custom.odf() idf_list = custom.idf() 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)) def LED_flash(LED_state): if LED_state: client.put('Reg_done', '1') os.system(r'echo "timer" > /sys/class/leds/arduino:white:usb/trigger'
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()
import sys import time import DAN import requests import os import datetime sys.path.insert(0, '/usr/lib/python2.7/bridge/') from bridgeclient import BridgeClient import custom client = BridgeClient() custom.profile_init() odf_list = custom.odf() idf_list = custom.idf() 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'
if key in self.bridge_var: r = self.bridge_var[key] else: r = None return r def getall(self): return self.bridge_var def put(self, key, value): self.bridge_var.update({key: value}) # run httpd server here # end of abstraction bridge_client = BridgeClient() # required values, if any error in bridge then defaults is used [1] # format codeword: ["codeword in bridge", default value, literal processing, variable] cw = { "mode": ["mode", "auto", True, "var.mode"], # valve position in % to start heating "valve": ["valve_pos", 35, True, "setup.valve_pos"], # start heating if single valve position in %, no matter how many valves are needed to start to heating "svpnmw": ["svpnmw", 75, True, "setup.svpnmw"], # how many valves must be in position stated above "valves": ["valves", 2, True, "setup.valves"], # if in total mode, sum of valves position to start heating "total": ["total_switch", 150, True, "setup.total_switch"], # preference, "per" = per valve, "total" to total mode "pref": ["preference", "per", True, "setup.preference"],
"no_oww": "no_oww"} stp.statMsg = { "idle": "idle", "heat": "heating", "start": "starting", "dead": "dead" } var = variables() # heat times; total: [totalheattime, time.time()] var.ht = {"total": [0, 0.0]} var.dev_log = {} var.msgQ = [] # initialize bridge var.value = BridgeClient() if path.ismount("/mnt/sda1"): stp.place = "/mnt/sda1/" elif path.ismount("/mnt/sdb1"): stp.place = "/mnt/sdb1/" else: err_str = "Error: can't find mounted storage device! Please mount SD card or USB key and run program again." llError(err_str) var.value.put(stp.cw["msg"], "Q") exit() try: stp.myip = socket.gethostbyname(socket.gethostname()) except Exception, e: err_str = "Error getting IP address from hostname, please check resolv.conf or hosts or both!\r\n"
import sys import time import DAN import requests import os sys.path.insert(0, '/usr/lib/python2.7/bridge/') from bridgeclient import BridgeClient import custom client = BridgeClient() custom.profile_init() odf_list = custom.odf() idf_list = custom.idf() 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)) '''def LED_flash(LED_state): if LED_state: client.put('Reg_done', '1') os.system(r'echo "timer" > /sys/class/leds/ds:green:usb/trigger') #For ArduinoYun Only. LED Blink. else: client.put('Reg_done', '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
#!/usr/bit/python # script for logging temperatures with time stamps into a file import sys import time sys.path.insert(0, '/usr/lib/python2.7/bridge') from bridgeclient import BridgeClient client = BridgeClient() logBuffer = [] logBufferMaxLen = 24 def writeBufferToFile(): logFile = open('tempLog.log', 'w') for entry in logBuffer: logFile.write(entry + '\n') logFile.close() while True: timeStruct = time.localtime(time.time()) # write into log every hour if timeStruct[4] == 0: val = client.get('temp') currentTime = time.strftime('%H:%M%:%S', timeStruct) entry = currentTime + ' ' + val logBuffer.append(entry)
@staticmethod def forODF(odf_name, data): os.system(r'echo "default-on" > /sys/class/leds/ds:green:wlan/trigger') global ODFcache if ODFcache[odf_name].qsize(): ODFcache[odf_name].get() ODFcache[odf_name].put(data) else: ODFcache[odf_name].put(data) os.system(r'echo "none" > /sys/class/leds/ds:green:wlan/trigger') BClient = BridgeClient() def Bridge2Arduino(): global incomming, ODFcache, IDFcache, timestamp, IDFsignal while True: for ODF in ODFcache: if ODFcache[ODF].qsize(): data = ODFcache[ODF].get() if data == None: continue for dimension in odf2Bridge[ODF]: if data[dimension[0]] is None:
# This code is provided by ArduinoMeetsLinux.com on an "AS IS" # basis. ArduinoMeetsLinux.com makes no warranties, express or # implied, regarding use of the code alone or in combination with # your projects. # # In no event shall ArduinoMeetsLinux.com be liable for any special, # indirect, incidental, or consequential damages (including, but not # limited to, loss of data and damage to systems) arising in any way # out of the use, reproduction, modification and/or distribution of # this code. import sys, time, os sys.path.insert(0, "/usr/lib/python2.7/bridge/") from bridgeclient import BridgeClient client = BridgeClient() #client.put("MCP9808_Temperature",54) #temp = float(client.get("MCP9808_Temperature")) temp1 = client.get("temp") temp = temp1[0] unit = os.environ["QUERY_STRING"] if unit == "": unit = "C" print "Content-type: text/html" print print """ <!DOCTYPE html> <html> <head> <title>Project 1 - Building a Web-Based Temperature Monitor</title>