Explorar o código

arduino as standalone server

Fabian Peter Hammerle %!s(int64=10) %!d(string=hai) anos
pai
achega
0324881e91
Modificáronse 6 ficheiros con 122 adicións e 122 borrados
  1. 0 2
      99-usb-serial.rules
  2. 0 58
      Arduino/Arduino.ino
  3. 122 0
      arduino/arduino.ino
  4. 0 4
      ardvindo-command
  5. 0 4
      ardvindo-server-start
  6. 0 54
      ardvindo-server.py

+ 0 - 2
99-usb-serial.rules

@@ -1,2 +0,0 @@
-SUBSYSTEM=="tty", ATTRS{idVendor}=="2341", ATTRS{idProduct}=="0043", ATTRS{serial}=="64032373833351F0B021", SYMLINK+="ardvindo"
-

+ 0 - 58
Arduino/Arduino.ino

@@ -1,58 +0,0 @@
-#include <RCSwitch.h>
-#include <Streaming.h>
-
-RCSwitch rcswitch = RCSwitch();
-
-void setup() 
-{
-  Serial.begin(9600);
-  //timeout for Serial.find(), 
-  Serial.setTimeout(100);
-  
-  rcswitch.enableTransmit(4);
-  
-  Serial.println("ardvindo started");
-}
-
-void loop() 
-{
-  if(Serial.available() > 0) 
-  {
-    // - 'i' info for identification
-    // - 'e' enable / switch on
-    // - 'd' disable / switch off
-    char command = Serial.read();
-    
-    if(command == 'i')
-    {
-      Serial.println("ardvindo");
-    }
-    else if(command == 'e' || command == 'd')
-    {
-      //wait for space and family
-      while(Serial.available() < 2)
-      {
-        delay(1);
-      }
-      
-      Serial.read(); //space
-      char family = Serial.read();
-      int group = Serial.parseInt();
-      int device = Serial.parseInt();
-
-      if(command == 'e')
-      {
-        rcswitch.switchOn(family, group, device);
-      }
-      else
-      {
-        rcswitch.switchOff(family, group, device);
-      }
-      
-      Serial << command << " " << family << " " << group << " " << device << "\n";
-    }
-    
-    // strip all further chars until end of line
-    Serial.find("\n");
-  }
-}

+ 122 - 0
arduino/arduino.ino

@@ -0,0 +1,122 @@
+#include <SPI.h>
+#include <Ethernet.h>
+#include <RCSwitch.h>
+
+byte mac[] = {0xDE, 0xAD, 0xBE, 0xAA, 0xDE, 0x01};
+IPAddress ip(192,168,2,114);
+const int serverPort = 2313;
+const int senderPin = 6;
+const int requestBufferLength = 16;
+const int attemptsCount = 3;
+
+EthernetServer server(serverPort);
+RCSwitch sender = RCSwitch();
+char requestBuffer[requestBufferLength];
+
+void setup() 
+{
+  Serial.begin(9600);
+  
+  sender.enableTransmit(senderPin);
+  sender.switchOn('b', 3, 2);
+  Serial.println("transmission enabled");
+  
+  Ethernet.begin(mac, ip);
+  server.begin();
+  
+  Serial.print("started ardvindo server at ");
+  Serial.print(Ethernet.localIP());
+  Serial.print(":");
+  Serial.println(serverPort);
+}
+
+void errorResponse(EthernetClient& client, const char* cmd, const char* msg) 
+{
+  Serial.print("error: ");
+  Serial.println(msg);
+  
+  client.print("cmd: ");
+  client.println(cmd);
+  client.print("error: ");
+  client.println(msg);
+}
+
+void processCmd(EthernetClient& client, const char* cmd) 
+{
+  if(cmd[0] == 'e' || cmd[0] == 'd') {
+    char family = requestBuffer[2];
+    int group = requestBuffer[4] - '0';
+    int device = requestBuffer[6] - '0';
+    
+    if(family < 'a' || family > 'f') {
+      errorResponse(client, cmd, "error: family < 'a' || family > 'f'");
+    } else if(group < 0) {
+      errorResponse(client, cmd, "group < 0");
+    } else if(device < 0) {
+      errorResponse(client, cmd, "device < 0");
+    } else {     
+      bool on = (requestBuffer[0] == 'e');
+         
+      for(int i = 0; i < attemptsCount; i++) {
+        if(on) {
+          sender.switchOn(family, group, device);
+        } else {
+          sender.switchOff(family, group, device);
+        }
+        delay(1);
+      }
+      
+      client.print(family);
+      client.print(" ");
+      client.print(group);
+      client.print(" ");
+      client.print(device);
+      client.print(" ");
+      if(on) {
+        client.println("switched on");
+        Serial.println("switched on");
+      } else {
+        client.println("switched off");
+        Serial.println("switched off");
+      }
+      
+      //sender.switchOn('b', 3, 2);
+      //delay(1500);
+      //sender.switchOff('b', 3, 2);
+    }
+  } else {
+    errorResponse(client, cmd, "unknown command");
+  }
+}
+
+void loop() 
+{
+  EthernetClient client = server.available();
+  if (client) {
+    Serial.println("client connected");
+    
+    client.println("ardvindo");
+    
+    while(client.connected()) {
+      if(client.available()) {
+        for(int i=0; i<requestBufferLength && client.available(); i++) {
+          char c = client.read();
+          if(c == '\n') {
+            break;
+          }
+          requestBuffer[i] = c;
+          requestBuffer[i+1] = '\0';
+        }
+        Serial.print("> ");
+        Serial.println(requestBuffer);
+        processCmd(client, requestBuffer);
+      }
+    }
+    
+    delay(1);
+    client.stop();
+    
+    Serial.println("client disonnected");
+  }
+}
+

+ 0 - 4
ardvindo-command

@@ -1,4 +0,0 @@
-#!/bin/bash
-
-echo -n "$@" >/dev/udp/localhost/61291
-

+ 0 - 4
ardvindo-server-start

@@ -1,4 +0,0 @@
-#!/bin/bash
-
-/usr/bin/screen -dmS ardvindo-server /usr/local/bin/ardvindo-server.py
-

+ 0 - 54
ardvindo-server.py

@@ -1,54 +0,0 @@
-#!/usr/bin/python3
-
-import serial
-import serial.tools.list_ports
-import time
-import datetime
-import socket 
-import socketserver
-
-def log(msg):
-    print("[" + str(datetime.datetime.now()) + "] " + msg)
-
-class Ardvindo:
-
-    def __init__(self, comPort):
-        self.comPort = comPort
-        self.comConnection = serial.Serial(self.comPort, 9600, timeout = 0.5)
-        # establishing an serial connection automatically resets the arduino
-        # wait for arduino to restart
-        time.sleep(4)
-        if self._readline() == "ardvindo started":
-            log("Connection established!")
-        else:
-            log("Failed to connect!")
-            raise Exception("Failed to connect!")
-
-    def _writeline(self, line):
-        log("Sending '" + line + "'... ")
-        self.comConnection.write(line.encode() + b"\n")
-
-    def _readline(self):
-        line = self.comConnection.readline().decode().strip()
-        log("Received '" + line + "' !")
-        return line
-
-    def sendCommand(self, cmd):
-        self.comConnection.flushInput()
-        self._writeline(cmd)
-
-#ardvindo = Ardvindo(serial.tools.list_ports.comports()[0][0])
-ardvindo = Ardvindo("/dev/ardvindo")
-
-class ServerRequestHandler(socketserver.BaseRequestHandler):
-    
-    def handle(self):
-        data = self.request[0].decode().strip()
-        ardvindo.sendCommand(data)
-
-server = socketserver.UDPServer(('', 61291), ServerRequestHandler)
-log("Server is started!")
-
-log("Waiting for commands... ")
-server.serve_forever()
-