예제 #1
0
def on_connect(client, userdata, flags, rc):
    connectionMsg = "VALFR BROKER Connected with result code " + str(rc) + "\n"
    #print(connectionMsg)
    journal.write(connectionMsg)
    client.subscribe("#")
    fichierLog = open(pathLogs + "broker.txt", "a")
    fichierLog.write(connectionMsg)
    fichierLog.close()
예제 #2
0
def GetGPSPacket():
    while True:
        try:
            Gps_packet = gpsd.get_current()  #Hent gps data
            if Gps_packet.mode > 1:  #Sjekk om fix er minst 2D
                return Gps_packet
        except:  #hvis ikke prøv igjen
            journal.write("myGps: Bad gps packet, retrying in 5 sec")
            time.sleep(5)
예제 #3
0
def interfaces_added(path, interfaces):
    try:
        bt_mac = extract_br_add_as_mac(path)
        os.system('echo "default-agent\n pair %s\n quit" | bluetoothctl' %
                  bt_mac)
        os.system('echo "default-agent\n connect %s\n quit" | bluetoothctl' %
                  bt_mac)
        os.system('echo "default-agent\n trust %s\n quit" | bluetoothctl' %
                  bt_mac)
    except Exception as e:
        journal.write(str(e))
예제 #4
0
def GPSInit():
    gps_ok = 1
    while gps_ok:
        gps_ok = 0
        try:
            gpsd.connect()  #Koble til gpsd
            journal.write("myGps: GPS connected")
        except:
            #print("gpsd error")
            journal.write("myGps: No GPS")
            gps_ok = 1
예제 #5
0
def GetGPSPacket():
    """ 
    Henter gps pakke fra gpsd, vil forsøke helt til en god pakke (fix > 1) er klar
    """
    while True:
        try:
            Gps_packet = gpsd.get_current()  #Hent gps data
            if Gps_packet.mode > 1:  #Sjekk om fix er minst 2D
                return Gps_packet
        except:  #hvis ikke prøv igjen
            journal.write("myGps: Bad gps packet, retrying in 5 sec")
            time.sleep(5)
예제 #6
0
def gpsInit():
    # Starter kobling til gpsd, vil forsøke til koblingen er oppe
    gps_ok = 1
    while gps_ok:
        gps_ok = 0
        try:
            gpsd.connect()  #Koble til gpsd
            journal.write("pyMon: GPS init ok")
        except:
            #print("gpsd error")
            journal.write("pyMon: GPS init Error")
            gps_ok = 1
예제 #7
0
def log(log_entry, log_file=APP_LOG_FILE):
    logFile = open(log_file, "a")
    logfile_entry = get_date_and_time() + ': ' + log_entry + '\n'
    logFile.write(logfile_entry)
    logFile.close()
    if log_file == TEMP_LOG_FILE:
        logQue.appendleft(logfile_entry)
        webFile = open(WEB_PAGE_FILE, "w")
        for line in logQue:
            webFile.write(line + '<br>')
        webFile.close()
    else:
        journal.write(log_entry)
예제 #8
0
def gpsInit():
    """
    Starter kobling til gpsd, vil forsøke til koblingen er oppe
    """
    gps_ok = 1
    while gps_ok:
        gps_ok = 0
        try:
            gpsd.connect()  #Koble til gpsd
            journal.write("myGps: GPS connected")
        except:
            #print("gpsd error")
            journal.write("myGps: No GPS")
            gps_ok = 1
예제 #9
0
def GetGPSPacket():

    #Henter gps pakke fra gpsd, vil forsøke helt til en god pakke (fix > 1) er klar

    while True:
        try:
            Gps_packet = gpsd.get_current()  #Hent gps data
            if Gps_packet.mode > 1:  #Sjekk om fix er minst 2D
                wiringpi.digitalWrite(LEDgps, 1)
                return Gps_packet
        except:  #hvis ikke prøv igjen
            journal.write("pyMon: GPS packet exception, retrying in 5 sec")
            wiringpi.digitalWrite(LEDgps, 0)
            time.sleep(5)
예제 #10
0
def isConnected():
    try:
        # connect to the host -- tells us if the host is actually
        # reachable
        sock = socket.create_connection(("www.google.com", 80))
        if sock is not None:
            #print('Closing socket')
            wiringpi.digitalWrite(LEDnet, 1)
            journal.write("pyMon: Internet connection ok")
            sock.close
        return True
    except OSError:
        pass
    wiringpi.digitalWrite(LEDnet, 0)
    return False
예제 #11
0
def switched(pos):
    global currentState
    wert_des_schalters = not bool(GPIO.input(pin_number))
    if pos != wert_des_schalters:
        journal.write("state changed to: %s " % wert_des_schalters)
        chn_time = time.time()
        icons = data.get("state").get('icon')
        data.update({
            'state': {
                'open': wert_des_schalters,
                'lastchange': chn_time,
                "icon": icons
            }
        })
        currentState = wert_des_schalters
        with open('/var/www/html/spaceapi.json', 'w') as outfile:
            json.dump(data, outfile, sort_keys=True)
예제 #12
0
def scan(iface, channel_weights, mongodb_url):
    mongodb = MongoClient(mongodb_url)
    db = mongodb.networks

    def Packet_info(pkt):
        # finding APs by Beacons (subtype == 8)
        if pkt.haslayer(Dot11Beacon):
            infos = {}
            # ssid, channel, crypto, rates
            infos.update(pkt[Dot11Beacon].network_stats())
            infos['crypto'] = str(infos['crypto'])
            infos['lastSeen'] = datetime.datetime.now().timestamp()
            infos['signal'] = pkt[RadioTap].dBm_AntSignal

            db.ap.update(
                {'_id': pkt.addr2},
                {"$set": infos},
                #                          "$inc":{'beacons' : 1},
                #                         },
                upsert=True)

        # finding corresponding clients by Probes
        if pkt.haslayer(Dot11ProbeReq):
            ap = {'ap': pkt.info.decode("utf-8")}
            infos = {}
            infos['signal'] = pkt[RadioTap].dBm_AntSignal
            infos['lastSeen'] = datetime.datetime.now().timestamp()

            channel = m2i(pkt[RadioTap].ChannelFrequency)
            channel_weights[channel - 1] += 1

            db.client.update({'_id': str(pkt.addr2)}, {
                '$addToSet': {
                    'ap': ap
                },
                '$set': infos
            },
                             upsert=True)

    journal.write("Start sniffing on interface {}".format(iface))
    sniff(iface=iface, prn=Packet_info)
예제 #13
0
def WriteToLog(info,firstEntry=False,level='I'):
	logEntry = str(info) + "\n"
	journal.write(logEntry)
	print(logEntry)
예제 #14
0
#! /usr/bin/python3
###################################################################################
# Logging software
#
# Gets gps location and accelerometer data and sends theese to a rest API
#
#
###################################################################################
import json, time, gpsd, requests, socket
from systemd import journal
journal.write("pyMon Starting")
from mpu6050 import mpu6050
from mySerial import getshortserial as getserial
import wiringpi as wiringpi

wiringpi.wiringPiSetupGpio()
LEDnet = 22
LEDgps = 23
LEDsend = 24
wiringpi.pinMode(LEDnet, 1)
wiringpi.pinMode(LEDgps, 1)
wiringpi.pinMode(LEDsend, 1)
wiringpi.digitalWrite(LEDnet, 0)
wiringpi.digitalWrite(LEDgps, 0)
wiringpi.digitalWrite(LEDsend, 0)

sensor = mpu6050(0x68)

report_freq = 60 * 5  #Seconds between sending report
bump_debounce = 2  #  seconds between bounce alerts
rest_url = 'https://hneve.com/log/insert.php'
예제 #15
0
def WriteToLog(info,firstEntry=False):
	logEntry = str(info) + "\n"
	journal.write(logEntry)
	#print(logEntry)
	return
from systemd import journal

# https://pypi.org/project/systemd/
journal.write("Hello Lennart")
예제 #17
0
                      self.storeID + "/roller/0/command -m " +
                      self.storeAction)
        if self.storeAction[0:3] == "pos":
            os.system("mosquitto_pub -h localhost -t shellies/" +
                      self.storeID + "/roller/0/command/pos -m " +
                      self.storeAction.replace("pos", ""))
        fichierLog = open("/mnt/ram/worker.txt", "a")
        fichierLog.write("Action$SHELLY$stores$" + self.storeID + "$" +
                         self.storeAction + "\n")
        fichierLog.close()


#MAIN
startupMsg = "VALFR WORKER v1.0 starting up at " + datetime.today().strftime(
    '%Y-%m-%d %H:%M:%S') + "\n"
journal.write(startupMsg)
fichierLog = open("/mnt/ram/worker.txt", "a")
fichierLog.write(startupMsg)
fichierLog.close()
thread_0 = LoadRules("/home/data/rules-worker.txt")
thread_0.daemon = True
thread_0.start()

while True:
    #print(datetime.today().strftime('%Y-%m-%d %H:%M:%S')+" ")
    #if datetime.today().strftime('%S') == "10" or datetime.today().strftime('%S') == "20" or datetime.today().strftime('%S') == "30" or datetime.today().strftime('%S') == "40" or datetime.today().strftime('%S') == "50" or datetime.today().strftime('%S') == "00":
    if datetime.today().strftime('%S') == "00":
        thread_2 = LoadRules("/home/data/rules-worker.txt")
        thread_2.daemon = True
        thread_2.start()
    for rule in myRules:
예제 #18
0
    parser.add_argument('-i',
                        '--iface',
                        required=True,
                        help="Interface of Wifi Card")
    parser.add_argument('-m',
                        '--mongodb',
                        default=MONGO_DB,
                        help="Default: {}".format(MONGO_DB))
    args = parser.parse_args()

    # set card into monitor mode
    pyw_card = pyw.getcard(args.iface)
    pyw.down(pyw_card)
    pyw.modeset(pyw_card, 'monitor')
    pyw.up(pyw_card)
    journal.write("Interface {} set to promiscuous mode".format(args.iface))

    # start scanning
    sniffer = Process(name='sniffer',
                      target=scan,
                      args=(args.iface, channel_weights, args.mongodb))
    sniffer.start()

    journal.write("Start channel hopping on interface {}".format(args.iface))
    while (sniffer.is_alive):
        weights = list(channel_weights)
        channels = list(range(1, CHANNEL_COUNT + 1))
        ch = choices(channels, weights)[0]
        pyw.chset(pyw_card, ch, None)
        sleep(0.5)
예제 #19
0
#########################################################################

# to make sure that everything does not happen at once
import time
# json and raspi imports
import json
# for using GPIO pins of the raspi
import RPi.GPIO as GPIO
# for logging
import logging
from systemd import journal

########################################################

#start init
journal.write("CCCHB space api switch v. 0.3")
currentState = False

#################################################################################
#function definitons:
#################################################################################


# will read the GPIO header of the pi and write the current state in the www spaceapi json file
def switched(pos):
    global currentState
    wert_des_schalters = not bool(GPIO.input(pin_number))
    if pos != wert_des_schalters:
        journal.write("state changed to: %s " % wert_des_schalters)
        chn_time = time.time()
        icons = data.get("state").get('icon')
예제 #20
0
realtimeHUEcolorAmbianceColorSaturation = dict()
devicesSHELLYplugS = dict()
realtimeSHELLYplugS = dict()
devicesSHELLYrelayOne = dict()
realtimeSHELLYrelayOne = dict()
devicesSHELLYrelay1pm = dict()
realtimeSHELLYrelay1pm = dict()
#pathLogs = "/mnt/ram/"
#pathData = "/mnt/ram/"
pathLogs = "/home/logs/"
pathData = "/home/data/iot/"
doLogs = False

startupMsg = "VALFR BROKER v3.6 starting up at " + datetime.today().strftime(
    '%Y-%m-%d %H:%M:%S') + "\n"
journal.write(startupMsg)
fichierLog = open(pathLogs + "broker.txt", "a")
fichierLog.write(startupMsg)
with open("/home/data/devices.txt") as f:
    for line in f:
        line = line.replace("\n", "")
        data = line.split('!')
        if data[0] == "XIAOMIdoor":
            devicesXIAOMIdoorSensors[data[1]] = data[2]
        if data[0] == "XIAOMImotion":
            devicesXIAOMImotionSensors[data[1]] = data[2]
        if data[0] == "XIAOMIswitchD1s1":
            devicesXIAOMIswitchD1s1[data[1]] = data[2]
            devicesXIAOMIswitchD1s1scene[data[1]] = data[3]
            devicesXIAOMIswitchD1s1target[data[1]] = data[4]
        if data[0] == "XIAOMIswitchD1s2":