Jump to content

andy_b_1502

Members
  • Posts

    397
  • Joined

  • Last visited

Profile Information

  • Gender
    Male
  • Location
    Cannock

andy_b_1502's Achievements

Regular Member

Regular Member (3/5)

0

Reputation

  1. I have been following a devicehive tutorial to make a temperature sensor, everything is working as expected up until making the thing update itself temps and relay them into my client. The script (raspi_led_thermo.py): #/usr/bin/env python # @author astaff # # This sample is to demonstrate DeviceHive Python library # Connect LED to PIN11 of the board and 1-wire sensor to GPIO4 board PIN #7, # use pins #1 (3v3) or #2 (5v) for power and pin #6 for ground # # (C) DataArt Apps, 2012 # Distributed under MIT license # import sys import os import time from time import sleep try : import RPi.GPIO as GPIO except ImportError: class FakeGPIO(object): OUT = 'OUTPUT BCM.GPIO17' BOARD = 'BOARD' def __init__(self): print 'Fake gpio initialized' def setmode(self, value): print 'Set mode {0}.'.format(value) def setup(self, io, mode): print 'Set gpio {0}; Mode: {1};'.format(io, mode) def output(self, io, vlaue): print 'Set gpio {0}; Value: {1};'.format(io, vlaue) GPIO = FakeGPIO() sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from zope.interface import implements from twisted.python import log from twisted.internet import reactor, task import devicehive import devicehive.auto # change it to match your address for 1-wire sensor _W1_FILENAME='/sys/bus/w1/devices/28-000004bc15aa/w1_slave' if not os.path.exists(_W1_FILENAME) : _W1_FILENAME = '/dev/null' # Board's pin #11 (GPIO17) _LED_PIN=11 # API URL (register for free playground at http://beta2.devicehive.com/playground _API_URL = 'http://nn1269.pg.devicehive.com/api/' # # for easier reading, this class holds all registration information for DeviceHive # class RasPiConfig(object): implements(devicehive.interfaces.IDeviceInfo) @property def id(self): return '9f33566e-1f8f-11e2-8979-c42c030dd6a5' @property def key(self): return 'device-key' @property def name(self): return 'Device1' @property def status(self): return 'Online' @property def network(self): return devicehive.Network(key = 'Netname', name = 'Netname', descr = 'RasPi/Py LED/w1 sample') @property def device_class(self): return devicehive.DeviceClass(name = 'Class1', version = '1.0', is_permanent = False) @property def equipment(self): return [devicehive.Equipment(name = 'LED', code = 'LED', type = 'Controllable LED'), devicehive.Equipment(name = 'THERMO', code = 'temp', type = 'TempSensor')] # # This class handles DeviceHive API calls for our device # class RasPiApp(object): implements(devicehive.interfaces.IProtoHandler) def __init__(self, led, sensor): super(RasPiApp, self).__init__() self.connected = False self.notifs = [] self.info = RasPiConfig() self.led = led self.sensor = sensor def on_apimeta(self, websocket_server, server_time): log.msg('on_apimeta') def on_connected(self): lc = task.LoopingCall(self.sensor.get_temp, self) lc.start(1) log.msg('Connected to devicehive server.') self.connected = True for onotif in self.notifs : self.factory.notify(onotif['notification'], onotif['parameters'], device_id = self.info.id, device_key = self.info.key) self.notifs = [] def on_subscribe(result) : self.factory.subscribe(self.info.id, self.info.key) def on_failed(reason) : log.err('Failed to save device {0}. Reason: {1}.'.format(self.info, reason)) self.factory.device_save(self.info).addCallbacks(on_subscribe, on_failed) def on_connection_failed(self, reason) : pass def on_closing_connection(self): pass def on_failure(self, device_id, reason): pass def do_short_command(self, finished, equipment = None, state = 0): log.msg('Setting {0} equipment to {1}'.format(equipment, state)) if equipment == 'LED' : if int(state) == 0 : self.led.set_off() else: self.led.set_on() # upon completion post the result back self.factory.notify('equipment', {'state': state, 'equipment': 'LED'}, device_id = self.info.id, device_key = self.info.key) finished.callback(devicehive.CommandResult('Completed')) def on_command(self, device_id, command, finished): # Expecting command as 'UpdateState' and parameters as {"equipment" : "LED", "state" : "0"} if command.command == 'UpdateLedState' : self.do_short_command(finished, **command.parameters) else : finished.errback() # end do_command def notify(self, notif, **params): if self.connected : self.factory(notif, params, device_id = self.info.id, device_key = self.info.key) else : self.notifs.append({'notification': notif, 'parameters': params}) # # Temperature sensor wrapper. Gets temperature readings form file, parses them # and notifies the services is the difference is greater than a certain threshold # class TempSensor(object): def __init__(self, file_name): self.file_name = file_name self.last_temp = 0 self.last_good_temp = 0 # internal, get temperature readings from device and check CRC def _get_temp(self): with open(self.file_name) as f: content = f.readlines() for line in content: # sometimes CRC is bad, so we will return last known good temp if line.find('crc=')>=0 and line.find('NO')>=0: return self.last_good_temp p = line.find('t=') if p >= 0: self.last_good_temp = float(line[p+2:])/1000.0 return self.last_good_temp return 0.0 # check temperature, if greater than threshold, notify def get_temp(self, dev): temp = self._get_temp() if abs(temp - self.last_temp) > 0.2: log.msg('Temperature {0} -> {1}'.format(self.last_temp, temp)) dev.notify('equipment', temperature = temp, equipment = "temp") self.last_temp = temp # # Wrapper from LED connected to RasPi # class LedDevice(object): def __init__(self, pin): # We are using board PIN numbering (as opposed to chip's numbers) GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.OUT) def blink(self, count): for i in range(count): GPIO.output(_LED_PIN,True) sleep(0.2) GPIO.output(_LED_PIN,False) sleep(0.2) def set_on(self): GPIO.output(_LED_PIN, True) def set_off(self): GPIO.output(_LED_PIN, False) # # main # if __name__ == '__main__' : log.startLogging(sys.stdout) led = LedDevice(_LED_PIN) # Blink on start to ensure device is working led.blink(3) # create temp sensor and queue it to check for temperature in a separate thread tempSensor = TempSensor(_W1_FILENAME) # create a delegate to handle commands device = RasPiApp(led, tempSensor) led_factory = devicehive.auto.AutoFactory(device) reactor.connectDeviceHive(_API_URL, led_factory) # off we go! reactor.run() Using my API URL is sends off the data and on changing the temp it should update itself and notify me, this at the minute just records the 1st temp when the log is started and nothing more. The L.E.D on/off works fine as a consolation prize. Before i go through the logs and main errors, i wanted to post the working code of the thermal sensor using commands to manually update/refresh it (just incase any of you were thinking there's a fault with this): I was pinching the sensor supplying warmth and reloading the command, which you can see works well like that but not automatically? t= "temp in binary" root@raspberrypi:/home/pi/devicehive/python/examples# cat /sys/bus/w1/devices/28-000004bc15aa/w1_slave 44 01 4b 46 7f ff 0c 10 a9 : crc=a9 YES 44 01 4b 46 7f ff 0c 10 a9 t=20250 root@raspberrypi:/home/pi/devicehive/python/examples# cat /sys/bus/w1/devices/28-000004bc15aa/w1_slave 6f 01 4b 46 7f ff 01 10 67 : crc=67 YES 6f 01 4b 46 7f ff 01 10 67 t=22937 root@raspberrypi:/home/pi/devicehive/python/examples# cat /sys/bus/w1/devices/28-000004bc15aa/w1_slave 85 01 4b 46 7f ff 0b 10 5f : crc=5f YES 85 01 4b 46 7f ff 0b 10 5f t=24312 root@raspberrypi:/home/pi/devicehive/python/examples# Now the error im getting when running raspi_led_thermo.py to log temps: root@raspberrypi:/home/pi/devicehive/python/examples# sudo python raspi_led_thermo.py 2013-06-23 13:39:03+0100 [-] Log opened. 2013-06-23 13:39:03+0100 [-] raspi_led_thermo.py:197: exceptions.RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings. 2013-06-23 13:39:04+0100 [-] Starting factory <devicehive.auto.AutoFactory instance at 0x13ead50> 2013-06-23 13:39:05+0100 [AutoProtocol,client] The call to "/info" api has finished successfully. 2013-06-23 13:39:05+0100 [AutoProtocol,client] on_apimeta 2013-06-23 13:39:05+0100 [AutoProtocol,client] WebSocket protocol has been selected. URL: http://nn1269.pg.devicehive.com:8010/; HOST: nn1269.pg.devicehive.com; PORT: 8010; 2013-06-23 13:39:05+0100 [AutoProtocol,client] Starting factory <devicehive.device.ws.WebSocketFactory instance at 0x17452d8> 2013-06-23 13:39:05+0100 [AutoProtocol,client] Stopping factory <devicehive.auto.AutoFactory instance at 0x13ead50> 2013-06-23 13:39:06+0100 [WebSocketDeviceHiveProtocol,client] Temperature 0 -> 20.187 2013-06-23 13:39:06+0100 [WebSocketDeviceHiveProtocol,client] Connected to devicehive server. 2013-06-23 13:39:06+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "notification/insert", "notification": {"notification": "equipment", "parameters": {"equipment": "temp", "temperature": 20.187}}, "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 1} 2013-06-23 13:39:06+0100 [WebSocketDeviceHiveProtocol,client] device_save <__main__.RasPiConfig object at 0x172ed70> 2013-06-23 13:39:06+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "device/save", "device": {"status": "Online", "name": "Device1", "equipment": [{"code": "LED", "type": "Controllable LED", "name": "LED"}, {"code": "temp", "type": "TempSensor", "name": "THERMO"}], "deviceClass": {"version": "1.0", "is_permanent": false, "name": "Class1"}, "key": "device-key", "network": {"name": "Netname", "key": "Netname", "description": "RasPi/Py LED/w1 sample"}}, "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 2} 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"notification/insert","status":"success","requestId":1,"notification":{"id":65,"timestamp":"2013-06-23T12:39:07.094000"}}. 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"notification/insert","status":"success","requestId":1,"notification":{"id":65,"timestamp":"2013-06-23T12:39:07.094000"}}. 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"device/save","status":"success","requestId":2}. 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"device/save","status":"success","requestId":2}. 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Subscribe device 9f33566e-1f8f-11e2-8979-c42c030dd6a5. 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "command/subscribe", "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 3} 2013-06-23 13:39:08+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"command/subscribe","status":"success","requestId":3}. 2013-06-23 13:39:08+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"command/subscribe","status":"success","requestId":3}. 2013-06-23 13:39:45+0100 [-] Temperature 20.187 -> 20.437 2013-06-23 13:39:45+0100 [-] Unhandled error in Deferred: 2013-06-23 13:39:45+0100 [-] Unhandled Error Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1169, in run self.mainLoop() File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1178, in mainLoop self.runUntilCurrent() File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 800, in runUntilCurrent call.func(*call.args, **call.kw) File "/usr/lib/python2.7/dist-packages/twisted/internet/task.py", line 215, in __call__ d = defer.maybeDeferred(self.f, *self.a, **self.kw) --- <exception caught here> --- File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 134, in maybeDeferred result = f(*args, **kw) File "raspi_led_thermo.py", line 187, in get_temp dev.notify('equipment', temperature = temp, equipment = "temp") File "raspi_led_thermo.py", line 153, in notify self.factory(AutoFactory, notif, params, device_id = self.info.id, device_key = self.info.key) exceptions.NameError: global name 'AutoFactory' is not defined ^C2013-06-23 13:40:35+0100 [-] Received SIGINT, shutting down. 2013-06-23 13:40:35+0100 [WebSocketDeviceHiveProtocol,client] Stopping factory <devicehive.device.ws.WebSocketFactory instance at 0x17452d8> 2013-06-23 13:40:35+0100 [-] Main loop terminated. root@raspberrypi:/home/pi/devicehive/python/examples# sudo python raspi_led_thermo.py 2013-06-23 16:18:52+0100 [-] Log opened. 2013-06-23 16:18:52+0100 [-] raspi_led_thermo.py:197: exceptions.RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings. 2013-06-23 16:18:54+0100 [-] Starting factory <devicehive.auto.AutoFactory instance at 0xddbd50> 2013-06-23 16:18:54+0100 [AutoProtocol,client] The call to "/info" api has finished successfully. 2013-06-23 16:18:54+0100 [AutoProtocol,client] on_apimeta 2013-06-23 16:18:54+0100 [AutoProtocol,client] WebSocket protocol has been selected. URL: http://nn1269.pg.devicehive.com:8010/; HOST: nn1269.pg.devicehive.com; PORT: 8010; 2013-06-23 16:18:54+0100 [AutoProtocol,client] Starting factory <devicehive.device.ws.WebSocketFactory instance at 0x11342d8> 2013-06-23 16:18:54+0100 [AutoProtocol,client] Stopping factory <devicehive.auto.AutoFactory instance at 0xddbd50> 2013-06-23 16:18:56+0100 [WebSocketDeviceHiveProtocol,client] Temperature 0 -> 20.437 2013-06-23 16:18:56+0100 [WebSocketDeviceHiveProtocol,client] Connected to devicehive server. 2013-06-23 16:18:56+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "notification/insert", "notification": {"notification": "equipment", "parameters": {"equipment": "temp", "temperature": 20.437}}, "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 1} 2013-06-23 16:18:56+0100 [WebSocketDeviceHiveProtocol,client] device_save <__main__.RasPiConfig object at 0x111dd70> 2013-06-23 16:18:56+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "device/save", "device": {"status": "Online", "name": "Device1", "equipment": [{"code": "LED", "type": "Controllable LED", "name": "LED"}, {"code": "temp", "type": "TempSensor", "name": "THERMO"}], "deviceClass": {"version": "1.0", "is_permanent": false, "name": "Class1"}, "key": "device-key", "network": {"name": "Netname", "key": "Netname", "description": "RasPi/Py LED/w1 sample"}}, "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 2} 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"notification/insert","status":"success","requestId":1,"notification":{"id":67,"timestamp":"2013-06-23T15:18:56.722000"}}. 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"notification/insert","status":"success","requestId":1,"notification":{"id":67,"timestamp":"2013-06-23T15:18:56.722000"}}. 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"device/save","status":"success","requestId":2}. 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"device/save","status":"success","requestId":2}. 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Subscribe device 9f33566e-1f8f-11e2-8979-c42c030dd6a5. 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "command/subscribe", "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 3} 2013-06-23 16:18:58+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"command/subscribe","status":"success","requestId":3}. 2013-06-23 16:18:58+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"command/subscribe","status":"success","requestId":3}. 2013-06-23 16:19:22+0100 [-] Temperature 20.437 -> 20.687 2013-06-23 16:19:22+0100 [-] Unhandled error in Deferred: 2013-06-23 16:19:22+0100 [-] Unhandled Error Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1169, in run self.mainLoop() File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1178, in mainLoop self.runUntilCurrent() File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 800, in runUntilCurrent call.func(*call.args, **call.kw) File "/usr/lib/python2.7/dist-packages/twisted/internet/task.py", line 215, in __call__ d = defer.maybeDeferred(self.f, *self.a, **self.kw) --- <exception caught here> --- File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 134, in maybeDeferred result = f(*args, **kw) File "raspi_led_thermo.py", line 187, in get_temp dev.notify('equipment', temperature = temp, equipment = "temp") File "raspi_led_thermo.py", line 153, in notify self.factory(notif, params, device_id = self.info.id, device_key = self.info.key) exceptions.AttributeError: AutoFactory instance has no __call__ method It has no call method. I tried to add AutoFactory to call it in: notify self.factory but then it said that it wasn't defined, couldn't see correctly where to define AutoFactory so i revoked those changes. I need some help completing this as im no expert i just want a temp sensor for my fish tank. Could somebody tell me how to change this file so it works right please? If i have missed something that might help, please let me know. I have tried to include what i think it needed to resolve the issue.
  2. Just found this: http://docs.python.org/2/library/sqlite3.html To use the module, you must first create a Connection object that represents the database. Here the data will be stored in the example.db file: Its stops and starts here: 2013-06-23 13:39:05+0100 [AutoProtocol,client] Starting factory <devicehive.device.ws.WebSocketFactory instance at 0x17452d8> 2013-06-23 13:39:05+0100 [AutoProtocol,client] Stopping factory <devicehive.auto.AutoFactory instance at 0x13ead50> Could somebody point me in the right direction to create the connection object? Or am i barking up the wrong proccess-tree??
  3. I found the following URL: http://twistedmatrix.com/documents/13.0.0/api/twisted.internet.protocol.ReconnectingClientFactory.html Un-fortunately it doesn't mean much to me. It does state to make sure it starts but that Factory and not AutoFactory: Method doStart Make sure startFactory is called. Method doStop Make sure stopFactory is called.
  4. I have been following a devicehive tutorial to make a temperature sensor, everything is working as expected up until making the thing update itself temps and relay them into my client. The script (raspi_led_thermo.py): #/usr/bin/env python # @author astaff # # This sample is to demonstrate DeviceHive Python library # Connect LED to PIN11 of the board and 1-wire sensor to GPIO4 board PIN #7, # use pins #1 (3v3) or #2 (5v) for power and pin #6 for ground # # (C) DataArt Apps, 2012 # Distributed under MIT license # import sys import os import time from time import sleep try : import RPi.GPIO as GPIO except ImportError: class FakeGPIO(object): OUT = 'OUTPUT BCM.GPIO17' BOARD = 'BOARD' def __init__(self): print 'Fake gpio initialized' def setmode(self, value): print 'Set mode {0}.'.format(value) def setup(self, io, mode): print 'Set gpio {0}; Mode: {1};'.format(io, mode) def output(self, io, vlaue): print 'Set gpio {0}; Value: {1};'.format(io, vlaue) GPIO = FakeGPIO() sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from zope.interface import implements from twisted.python import log from twisted.internet import reactor, task import devicehive import devicehive.auto # change it to match your address for 1-wire sensor _W1_FILENAME='/sys/bus/w1/devices/28-000004bc15aa/w1_slave' if not os.path.exists(_W1_FILENAME) : _W1_FILENAME = '/dev/null' # Board's pin #11 (GPIO17) _LED_PIN=11 # API URL (register for free playground at http://beta2.devicehive.com/playground _API_URL = 'http://nn1269.pg.devicehive.com/api/' # # for easier reading, this class holds all registration information for DeviceHive # class RasPiConfig(object): implements(devicehive.interfaces.IDeviceInfo) @property def id(self): return '9f33566e-1f8f-11e2-8979-c42c030dd6a5' @property def key(self): return 'device-key' @property def name(self): return 'Device1' @property def status(self): return 'Online' @property def network(self): return devicehive.Network(key = 'Netname', name = 'Netname', descr = 'RasPi/Py LED/w1 sample') @property def device_class(self): return devicehive.DeviceClass(name = 'Class1', version = '1.0', is_permanent = False) @property def equipment(self): return [devicehive.Equipment(name = 'LED', code = 'LED', type = 'Controllable LED'), devicehive.Equipment(name = 'THERMO', code = 'temp', type = 'TempSensor')] # # This class handles DeviceHive API calls for our device # class RasPiApp(object): implements(devicehive.interfaces.IProtoHandler) def __init__(self, led, sensor): super(RasPiApp, self).__init__() self.connected = False self.notifs = [] self.info = RasPiConfig() self.led = led self.sensor = sensor def on_apimeta(self, websocket_server, server_time): log.msg('on_apimeta') def on_connected(self): lc = task.LoopingCall(self.sensor.get_temp, self) lc.start(1) log.msg('Connected to devicehive server.') self.connected = True for onotif in self.notifs : self.factory.notify(onotif['notification'], onotif['parameters'], device_id = self.info.id, device_key = self.info.key) self.notifs = [] def on_subscribe(result) : self.factory.subscribe(self.info.id, self.info.key) def on_failed(reason) : log.err('Failed to save device {0}. Reason: {1}.'.format(self.info, reason)) self.factory.device_save(self.info).addCallbacks(on_subscribe, on_failed) def on_connection_failed(self, reason) : pass def on_closing_connection(self): pass def on_failure(self, device_id, reason): pass def do_short_command(self, finished, equipment = None, state = 0): log.msg('Setting {0} equipment to {1}'.format(equipment, state)) if equipment == 'LED' : if int(state) == 0 : self.led.set_off() else: self.led.set_on() # upon completion post the result back self.factory.notify('equipment', {'state': state, 'equipment': 'LED'}, device_id = self.info.id, device_key = self.info.key) finished.callback(devicehive.CommandResult('Completed')) def on_command(self, device_id, command, finished): # Expecting command as 'UpdateState' and parameters as {"equipment" : "LED", "state" : "0"} if command.command == 'UpdateLedState' : self.do_short_command(finished, **command.parameters) else : finished.errback() # end do_command def notify(self, notif, **params): if self.connected : self.factory(notif, params, device_id = self.info.id, device_key = self.info.key) else : self.notifs.append({'notification': notif, 'parameters': params}) # # Temperature sensor wrapper. Gets temperature readings form file, parses them # and notifies the services is the difference is greater than a certain threshold # class TempSensor(object): def __init__(self, file_name): self.file_name = file_name self.last_temp = 0 self.last_good_temp = 0 # internal, get temperature readings from device and check CRC def _get_temp(self): with open(self.file_name) as f: content = f.readlines() for line in content: # sometimes CRC is bad, so we will return last known good temp if line.find('crc=')>=0 and line.find('NO')>=0: return self.last_good_temp p = line.find('t=') if p >= 0: self.last_good_temp = float(line[p+2:])/1000.0 return self.last_good_temp return 0.0 # check temperature, if greater than threshold, notify def get_temp(self, dev): temp = self._get_temp() if abs(temp - self.last_temp) > 0.2: log.msg('Temperature {0} -> {1}'.format(self.last_temp, temp)) dev.notify('equipment', temperature = temp, equipment = "temp") self.last_temp = temp # # Wrapper from LED connected to RasPi # class LedDevice(object): def __init__(self, pin): # We are using board PIN numbering (as opposed to chip's numbers) GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.OUT) def blink(self, count): for i in range(count): GPIO.output(_LED_PIN,True) sleep(0.2) GPIO.output(_LED_PIN,False) sleep(0.2) def set_on(self): GPIO.output(_LED_PIN, True) def set_off(self): GPIO.output(_LED_PIN, False) # # main # if __name__ == '__main__' : log.startLogging(sys.stdout) led = LedDevice(_LED_PIN) # Blink on start to ensure device is working led.blink(3) # create temp sensor and queue it to check for temperature in a separate thread tempSensor = TempSensor(_W1_FILENAME) # create a delegate to handle commands device = RasPiApp(led, tempSensor) led_factory = devicehive.auto.AutoFactory(device) reactor.connectDeviceHive(_API_URL, led_factory) # off we go! reactor.run() Using my API URL is sends off the data and on changing the temp it should update itself and notify me, this at the minute just records the 1st temp when the log is started and nothing more. The L.E.D on/off works fine as a consolation prize. Before i go through the logs and main errors, i wanted to post the working code of the thermal sensor using commands to manually update/refresh it (just incase any of you were thinking there's a fault with this): root@raspberrypi:/home/pi/devicehive/python/examples# cat /sys/bus/w1/devices/28-000004bc15aa/w1_slave 44 01 4b 46 7f ff 0c 10 a9 : crc=a9 YES 44 01 4b 46 7f ff 0c 10 a9 t=20250 root@raspberrypi:/home/pi/devicehive/python/examples# cat /sys/bus/w1/devices/28-000004bc15aa/w1_slave 6f 01 4b 46 7f ff 01 10 67 : crc=67 YES 6f 01 4b 46 7f ff 01 10 67 t=22937 root@raspberrypi:/home/pi/devicehive/python/examples# cat /sys/bus/w1/devices/28-000004bc15aa/w1_slave 85 01 4b 46 7f ff 0b 10 5f : crc=5f YES 85 01 4b 46 7f ff 0b 10 5f t=24312 root@raspberrypi:/home/pi/devicehive/python/examples# I was pinching the sensor supplying warmth and reloading the command, which you can see works well like that but not automatically? t= "temp in binary" Now the error im getting when running raspi_led_thermo.py to log temps: root@raspberrypi:/home/pi/devicehive/python/examples# sudo python raspi_led_thermo.py 2013-06-23 13:39:03+0100 [-] Log opened. 2013-06-23 13:39:03+0100 [-] raspi_led_thermo.py:197: exceptions.RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings. 2013-06-23 13:39:04+0100 [-] Starting factory <devicehive.auto.AutoFactory instance at 0x13ead50> 2013-06-23 13:39:05+0100 [AutoProtocol,client] The call to "/info" api has finished successfully. 2013-06-23 13:39:05+0100 [AutoProtocol,client] on_apimeta 2013-06-23 13:39:05+0100 [AutoProtocol,client] WebSocket protocol has been selected. URL: http://nn1269.pg.devicehive.com:8010/; HOST: nn1269.pg.devicehive.com; PORT: 8010; 2013-06-23 13:39:05+0100 [AutoProtocol,client] Starting factory <devicehive.device.ws.WebSocketFactory instance at 0x17452d8> 2013-06-23 13:39:05+0100 [AutoProtocol,client] Stopping factory <devicehive.auto.AutoFactory instance at 0x13ead50> 2013-06-23 13:39:06+0100 [WebSocketDeviceHiveProtocol,client] Temperature 0 -> 20.187 2013-06-23 13:39:06+0100 [WebSocketDeviceHiveProtocol,client] Connected to devicehive server. 2013-06-23 13:39:06+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "notification/insert", "notification": {"notification": "equipment", "parameters": {"equipment": "temp", "temperature": 20.187}}, "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 1} 2013-06-23 13:39:06+0100 [WebSocketDeviceHiveProtocol,client] device_save <__main__.RasPiConfig object at 0x172ed70> 2013-06-23 13:39:06+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "device/save", "device": {"status": "Online", "name": "Device1", "equipment": [{"code": "LED", "type": "Controllable LED", "name": "LED"}, {"code": "temp", "type": "TempSensor", "name": "THERMO"}], "deviceClass": {"version": "1.0", "is_permanent": false, "name": "Class1"}, "key": "device-key", "network": {"name": "Netname", "key": "Netname", "description": "RasPi/Py LED/w1 sample"}}, "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 2} 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"notification/insert","status":"success","requestId":1,"notification":{"id":65,"timestamp":"2013-06-23T12:39:07.094000"}}. 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"notification/insert","status":"success","requestId":1,"notification":{"id":65,"timestamp":"2013-06-23T12:39:07.094000"}}. 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"device/save","status":"success","requestId":2}. 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"device/save","status":"success","requestId":2}. 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Subscribe device 9f33566e-1f8f-11e2-8979-c42c030dd6a5. 2013-06-23 13:39:07+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "command/subscribe", "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 3} 2013-06-23 13:39:08+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"command/subscribe","status":"success","requestId":3}. 2013-06-23 13:39:08+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"command/subscribe","status":"success","requestId":3}. 2013-06-23 13:39:45+0100 [-] Temperature 20.187 -> 20.437 2013-06-23 13:39:45+0100 [-] Unhandled error in Deferred: 2013-06-23 13:39:45+0100 [-] Unhandled Error Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1169, in run self.mainLoop() File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1178, in mainLoop self.runUntilCurrent() File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 800, in runUntilCurrent call.func(*call.args, **call.kw) File "/usr/lib/python2.7/dist-packages/twisted/internet/task.py", line 215, in __call__ d = defer.maybeDeferred(self.f, *self.a, **self.kw) --- <exception caught here> --- File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 134, in maybeDeferred result = f(*args, **kw) File "raspi_led_thermo.py", line 187, in get_temp dev.notify('equipment', temperature = temp, equipment = "temp") File "raspi_led_thermo.py", line 153, in notify self.factory(AutoFactory, notif, params, device_id = self.info.id, device_key = self.info.key) exceptions.NameError: global name 'AutoFactory' is not defined ^C2013-06-23 13:40:35+0100 [-] Received SIGINT, shutting down. 2013-06-23 13:40:35+0100 [WebSocketDeviceHiveProtocol,client] Stopping factory <devicehive.device.ws.WebSocketFactory instance at 0x17452d8> 2013-06-23 13:40:35+0100 [-] Main loop terminated. root@raspberrypi:/home/pi/devicehive/python/examples# sudo python raspi_led_thermo.py 2013-06-23 16:18:52+0100 [-] Log opened. 2013-06-23 16:18:52+0100 [-] raspi_led_thermo.py:197: exceptions.RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings. 2013-06-23 16:18:54+0100 [-] Starting factory <devicehive.auto.AutoFactory instance at 0xddbd50> 2013-06-23 16:18:54+0100 [AutoProtocol,client] The call to "/info" api has finished successfully. 2013-06-23 16:18:54+0100 [AutoProtocol,client] on_apimeta 2013-06-23 16:18:54+0100 [AutoProtocol,client] WebSocket protocol has been selected. URL: http://nn1269.pg.devicehive.com:8010/; HOST: nn1269.pg.devicehive.com; PORT: 8010; 2013-06-23 16:18:54+0100 [AutoProtocol,client] Starting factory <devicehive.device.ws.WebSocketFactory instance at 0x11342d8> 2013-06-23 16:18:54+0100 [AutoProtocol,client] Stopping factory <devicehive.auto.AutoFactory instance at 0xddbd50> 2013-06-23 16:18:56+0100 [WebSocketDeviceHiveProtocol,client] Temperature 0 -> 20.437 2013-06-23 16:18:56+0100 [WebSocketDeviceHiveProtocol,client] Connected to devicehive server. 2013-06-23 16:18:56+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "notification/insert", "notification": {"notification": "equipment", "parameters": {"equipment": "temp", "temperature": 20.437}}, "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 1} 2013-06-23 16:18:56+0100 [WebSocketDeviceHiveProtocol,client] device_save <__main__.RasPiConfig object at 0x111dd70> 2013-06-23 16:18:56+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "device/save", "device": {"status": "Online", "name": "Device1", "equipment": [{"code": "LED", "type": "Controllable LED", "name": "LED"}, {"code": "temp", "type": "TempSensor", "name": "THERMO"}], "deviceClass": {"version": "1.0", "is_permanent": false, "name": "Class1"}, "key": "device-key", "network": {"name": "Netname", "key": "Netname", "description": "RasPi/Py LED/w1 sample"}}, "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 2} 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"notification/insert","status":"success","requestId":1,"notification":{"id":67,"timestamp":"2013-06-23T15:18:56.722000"}}. 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"notification/insert","status":"success","requestId":1,"notification":{"id":67,"timestamp":"2013-06-23T15:18:56.722000"}}. 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"device/save","status":"success","requestId":2}. 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"device/save","status":"success","requestId":2}. 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Subscribe device 9f33566e-1f8f-11e2-8979-c42c030dd6a5. 2013-06-23 16:18:57+0100 [WebSocketDeviceHiveProtocol,client] Sending websocket text frame. Payload: {"action": "command/subscribe", "deviceKey": "device-key", "deviceId": "9f33566e-1f8f-11e2-8979-c42c030dd6a5", "requestId": 3} 2013-06-23 16:18:58+0100 [WebSocketDeviceHiveProtocol,client] Websocket frame (1) has been received. Frame data: {"action":"command/subscribe","status":"success","requestId":3}. 2013-06-23 16:18:58+0100 [WebSocketDeviceHiveProtocol,client] Websocket message has been received {"action":"command/subscribe","status":"success","requestId":3}. 2013-06-23 16:19:22+0100 [-] Temperature 20.437 -> 20.687 2013-06-23 16:19:22+0100 [-] Unhandled error in Deferred: 2013-06-23 16:19:22+0100 [-] Unhandled Error Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1169, in run self.mainLoop() File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1178, in mainLoop self.runUntilCurrent() File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 800, in runUntilCurrent call.func(*call.args, **call.kw) File "/usr/lib/python2.7/dist-packages/twisted/internet/task.py", line 215, in __call__ d = defer.maybeDeferred(self.f, *self.a, **self.kw) --- <exception caught here> --- File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 134, in maybeDeferred result = f(*args, **kw) File "raspi_led_thermo.py", line 187, in get_temp dev.notify('equipment', temperature = temp, equipment = "temp") File "raspi_led_thermo.py", line 153, in notify self.factory(notif, params, device_id = self.info.id, device_key = self.info.key) exceptions.AttributeError: AutoFactory instance has no __call__ method It has no call method. I tried to add AutoFactory to call it in: notify self.factory but then it said that it wasn't defined, couldn't see correctly where to define AutoFactory so i revoked those changes. I need some help completing this as im no expert i just want a temp sensor for my fish tank. Could somebody tell me how to change this file so it works right please? If i have missed something that might help, please let me know. I have tried to include what i think it needed to resolve the issue.
  5. Okay, okay. It is going to require more help from you lot as your in the know much more than me. Breaking it down. Ive moved the }'s so the update is inside. Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path); }else{ //Gives and error if its not $error_message .= "Sorry, there was a problem uploading your file."; if (count($setArray) > 0) // do we have at least on field to update? $setstr = join (', ', $setArray); // form a comma separated string of our updates $query = "UPDATE companies SET $setstr WHERE id = $id"; // update it echo $query; mysql_query($query) or die(mysql_error()); }} header("Location: view01.php?id=" . $id); exit(0); ?> The form's action is set to post. Now no images upload AT ALL. so it's broke.... :'(
  6. Then i just dont understand why its working (partly) with action=get in place
  7. PFMaBiSmAd: action=get updates to an old image (an image that already exists on the server) action=post doesn't. I felt i was at least half way there with action=get.
  8. Like that: <?php include ('php only scripts/db.php'); include('php only scripts/resize.php'); if (isset($_POST['Submit'])){ $id = intval($_GET['id']); // guarantee it's a harmless number value if (isset($_GET['website']) && $_GET['website']) { // does the GET value exists and has it a value ? $website = mysql_real_escape_string($_GET['website']); // get its value and escape it $setArray[] = "website = '$website'"; // ok to update this field in the query so store it } if (isset($_GET['phone']) && $_GET['phone']) { $phone = mysql_real_escape_string($_GET['phone']); $setArray[] = "phone = '$phone'"; } if (isset($_GET['phone2']) && $_GET['phone2']) { $phone2 = mysql_real_escape_string($_GET['phone2']); $setArray[] = "phone2 = '$phone2'"; } if (isset($_GET['premiumuser_description']) && $_GET['premiumuser_description']) { $premiumuser_description = mysql_real_escape_string($_GET['premiumuser_description']); $setArray[] = "premiumuser_description = '$premiumuser_description'"; } if (isset($_GET['username']) && $_GET['username']) { $username = mysql_real_escape_string($_GET['username']); $setArray[] = "username = '$username'"; } if (isset($_GET['password']) && $_GET['password']) { // These are the same so you'd need to make them different if your comparing the password to ensure they entered it correctly ex: $_GET['password1'] for another field in your form $password= mysql_real_escape_string($_GET['password']); // This is fine if the 2 values above are first compared $setArray[] = "password = SHA('$password')"; // If they are compared and validation checks out then just do the query to update the password here.. } if (isset($_GET['upload']) && $_GET['upload']) { $upload = mysql_real_escape_string($_GET['upload']); $setArray[] = "upload = '$upload'"; } /* check if form was submitted */ $error_message = ""; /* This is the directory where images will be saved */ $target = "/home/users/web/b109/ipg.removalspacecom/images/COMPANIES/"; $target = $target . basename( $_FILES['upload']['name']); /* include validation script */ include ('php only scripts/validation.php'); $uploadDir = 'images/COMPANIES'; /* main picture folder */ $max_height = 450; /* largest height you allowed; 0 means any */ $max_width = 450; /* largest width you allowed; 0 means any */ $max_file = 2000000; /* set the max file size in bytes */ $image_overwrite = 1; /* 0 means overwite; 1 means new name */ /* add or delete allowed image types */ $allowed_type01 = array("image/gif", "image/pjpeg", "image/jpeg", "image/png", "image/x-png", "image/jpg"); $do_thumb = 1; /* 1 make thumbnails; 0 means do NOT make */ $thumbDir = "/images/thumbs"; /* thumbnail folder */ $thumb_prefix = ""; /* prefix for thumbnails */ $thumb_width = 90; /* max thumb width */ $thumb_height = 70; // max thumb height //Writes the photo to the server if(move_uploaded_file($_FILES['upload']['tmp_name'], $target)) { /* HERE IS WHERE WE WILL DO THE ACTUAL RESIZING */ /* THESE SIX PARAMETERS MAY BE CHANGED TO SUIT YOUR NEEDS */ $upload = $_FILES['upload']['name']; $o_path ="images/COMPANIES/"; $s_path = "images/thumbs/"; $file = $upload; $save = $file; $t_w = 200; $t_h = 150; /* DO NOT CHANGE THIS NEXT LINE */ Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path); }else{ //Gives and error if its not $error_message .= "Sorry, there was a problem uploading your file."; }} if (count($setArray) > 0) { // do we have at least on field to update? $setstr = join (', ', $setArray); // form a comma separated string of our updates $query = "UPDATE companies SET $setstr WHERE id = $id"; // update it echo $query; mysql_query($query) or die(mysql_error()); } header("Location: view01.php?id=" . $id); exit(0); ?> my form had a named-submit button: <input type="submit" name="submit" value="submit" />
  9. No error's are present, if i was to upload an image NOT already in the /thumbs folder (i.e a new image) it just displays an image placeholder. so it must be uploading the image to /companies folder (main image folder) but not re-sizing and moving to the /thumbs folder (re-sized thumbnail folder). In view01.php and throughout the website the images i want to display are called with: <img src="images/thumbs/<?PHP echo $row['upload']; ?>" alt="logo"/>
  10. It works fine with images already there to choose from. New images dont upload.
  11. Looks like i need to be embarrassed further......
  12. ChristianF i have error reporting on. If it is move_uploaded_file, what can i do to get to what it could be if i have error reporting on? sorry bit of a rookie here still as you might of guessed. Do i have to add something like mysql_error somewhere?
  13. Haha, i knew there would be few answers like that, there are 2 files in question here. The page with the form (view01.php) and the page that handles the form (view02.php). view01.php: <?PHP ini_set('display_errors',1); error_reporting(E_ALL); session_start(); if(!isset($_SESSION['id']) || !isset($_SESSION['valid_user']) || $_SESSION['valid_user'] != "yes") { $_SESSION = array(); session_destroy(); header("Location: index.php"); exit(); } include ('php only scripts/db.php'); $id = $_GET['id']; $query ="SELECT * FROM companies WHERE id = '$id'"; $result = mysql_query($query) or die(mysql_error()); $row = mysql_fetch_array($result); ?> <!DOCTYPE html> <head> <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" /> <title>Removalspace.com</title> <style type="text/css"> <!-- body { background-image: url(styles/downloaded%20styles/todo/todo/images/bg.png); } --> </style> <link href="styles/downloaded styles/todo/todo/css/style.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="styles/downloaded styles/todo/todo/css/style9.css" /> <link rel="stylesheet" type="text/css" href="styles/downloaded styles/todo/todo/css/demo.css" /> <link href='http://fonts.googleapis.com/css?family=Terminal+Dosis' rel='stylesheet' type='text/css' /> <style type="text/css"> <!-- .Stile1 {color: #333333} #apDiv1 { position:absolute; width:427px; height:183px; z-index:1; left: 533px; top: 52px; } --> </style> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-31656176-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body> <!--start container --> <div id="container"> <header> <nav> <div id="logo"><a href="index.php"><img src="images/header2.png" alt="Logo here" width="219" height="161" /></a> </div> <div id="search-top"><img src="styles/downloaded styles/todo/todo/images/quote-right.png" alt="images" /><span class="cursive">enter your postcode here</span><img src="styles/downloaded styles/todo/todo/images/quote-left.png" alt="images" /> <form method="post" action="search.php"> <input type="text" name="strSearch" onFocus="if(this.value=='Search Area')this.value='';" onBlur="if(this.value=='')this.value='Search Area';" value="Search Area" id="search-field"/> <input type="submit" value="" id="search-btn"/> </form> <p> </p> <p> </p> <p><em style="font-size: 9px">e.g first two letters and number</em>: i.e: AA1 or AA12</p> </div> <div id="nav_social"><a href="http://www.facebook.com/pages/Removalspace/181434181939226"><img src="styles/downloaded styles/todo/todo/images/facebook_32.png" alt="Become a fan" width="32" height="32" /></a><a href="#"><img src="styles/downloaded styles/todo/todo/images/twitter_32.png" alt="Follows on Twitter" /></a><a href="id=183427956&trk=tab_pro"><img src="styles/downloaded styles/todo/todo/images/linkedin_32.png" alt="Linked in" /></a><a href="contact.php"><img src="styles/downloaded styles/todo/todo/images/email_32.png" alt="Contact" width="32" height="32" /></a><!-- Place this tag where you want the +1 button to render --> <g:plusone size="small" annotation="inline"></g:plusone> <!-- Place this render call where appropriate --> <script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> </div> </nav> </header> <p><figure><a href="removals.php">Search Removals</a></figure> |</p> <p><figure><a href="storage.php">Search Storage</a></figure> |</p> <p><figure><a href="register00.php">Add Listing</a></figure> |</p> <p><figure><a href="about.php">About</a></figure> |</p> <p><figure><a href="contact.php">Contact</a></figure> |</p> <p><figure><a href="login00.php">Login</a></figure></p> <div class="content"> <!--star main --> <main></main> <!--end main --> <!--start middle --> <middle> <div class="section_slogan"><table width="845"> <tr> <td width="827" height="72" valign="top"><div class="abox"> <figure> <fcapion> <h1>Your Logo:</h1> <div id="apDiv1"><img src="images/furniture-removals-sydney.jpg" width="417" height="173"></div> <h1><img src="images/thumbs/<?PHP echo $row['upload']; ?>" alt="logo"/></h1> </fcaption></figure></div></td> </tr> <tr> <td><div class="abox"> <figure> <fcapion> <h2> <h1>Company Location:</h1> <h1><?PHP echo $row['street1'] . "<br>" . $row['street2'] . "<br>" . $row['city'] . "," . $row['postcode'] ; ?> </h1></h2> <h1></img></h1> </fcaption></figure> </div> </td> </tr> <tr> <td><div class="abox"> <figure> <fcapion> <h2> <h1>Contact Details:</h1> <h1><?PHP echo "phone: " . $row['phone'] . "<br>email: " . $row['email'] . "<br>website: " . $row['website'] ; ?> </h1></h2> <h1></img></h1> </fcaption></figure> </div> </td> </tr></table> <?PHP /* create an email validation function */ function validateEmailAddress($email) { return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email); } /** * CALLBACK - determine if the provided postcode is valid. * * @param string $postcode * @return bool TRUE if valid, FALSE otherwise * @author George Edwards */ function is_valid_uk_postcode($postcode) { $pattern = "/^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/"; if (preg_match($pattern, $postcode)) { return TRUE; } $this->validation->set_message('is_valid_uk_postcode', 'That is not a valid %s.'); return FALSE; } /* FUNCTION TO CREATE SALT */ function createSalt() { $string = md5(uniqid(rand(), true)); return substr($string, 0, 3); } /* check if form was submitted */ if (isset($_POST['Submit'])){ $error_message = ""; /* This is the directory where images will be saved */ $target = "/home/users/web/b109/ipg.removalspacecom/images/COMPANIES/"; $target = $target . basename( $_FILES['upload']['name']); /* include validation script */ include ('php only scripts/validation.php'); $uploadDir = 'images/COMPANIES'; /* main picture folder */ $max_height = 450; /* largest height you allowed; 0 means any */ $max_width = 450; /* largest width you allowed; 0 means any */ $max_file = 2000000; /* set the max file size in bytes */ $image_overwrite = 1; /* 0 means overwite; 1 means new name */ /* add or delete allowed image types */ $allowed_type01 = array( "image/gif", "image/pjpeg", "image/jpeg", "image/png", "image/x-png", "image/jpg"); $do_thumb = 1; /* 1 make thumbnails; 0 means do NOT make */ $thumbDir = "/images/thumbs"; /* thumbnail folder */ $thumb_prefix = ""; /* prefix for thumbnails */ $thumb_width = 90; /* max thumb width */ $thumb_height = 70; // max thumb height //Writes the photo to the server if(move_uploaded_file($_FILES['upload']['tmp_name'], $target)) { /* HERE IS WHERE WE WILL DO THE ACTUAL RESIZING */ /* THESE SIX PARAMETERS MAY BE CHANGED TO SUIT YOUR NEEDS */ $upload = $_FILES['upload']['name']; $o_path ="images/COMPANIES/"; $s_path = "images/thumbs/"; $file = $upload; $save = $file; $t_w = 200; $t_h = 150; /* DO NOT CHANGE THIS NEXT LINE */ Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path); }else{ //Gives and error if its not $error_message .= "Sorry, there was a problem uploading your file."; } /* PREPARE DATA FOR INSERTION INTO TABLE */ //Writes the information to the database if(strlen(trim($error_message)) <1){ $salt = createsalt(); $username = trim($_POST['username']); $password = trim($_POST['password']); $hash = hash('sha256', $salt, $password); $approved = 0; $company_name = mysql_real_escape_string(trim($_POST['company_name'])); $website = mysql_real_escape_string(trim($_POST['website'])); $contact_name = mysql_real_escape_string(trim($_POST['contact_name'])); $location = mysql_real_escape_string(trim($_POST['location'])); $postcode = mysql_real_escape_string(trim($_POST['postcode'])); $street1 = mysql_real_escape_string(trim($_POST['street1'])); $street2 = mysql_real_escape_string(trim($_POST['street2'])); $city = mysql_real_escape_string(trim($_POST['city'])); $phone = mysql_real_escape_string(trim($_POST['phone'])); $phone2 = mysql_real_escape_string(trim($_POST['phone2'])); $email = mysql_real_escape_string(trim($_POST['email'])); $premiumuser_description = mysql_real_escape_string(trim($_POST['premiumuser_description'])); $salt = mysql_real_escape_string($salt); $upload = mysql_real_escape_string($upload); $query ="INSERT INTO `companies` (company_name, what_services, website, contact_name, location, postcode, street1, street2, city, phone,phone2, email, premiumuser_description, username, password, salt, approved, upload) VALUES ('$company_name', '$what_services', '$website', '$contact_name', '$location', '$postcode', '$street1', '$street2', '$city', '$phone', '$phone2', '$email', '$premiumuser_description', '$username', '$hash', '$salt', '$approved', '$upload')"; $result = mysql_query($query) or die(mysql_error()); if ($result) { } /* at this point we can send an email to the admin as well as the user. DO NOT send the user's password to ANYONE!!!! */ } }//if (isset($_POST['submit'])) ?> <?php if (!empty($error_message)){ echo $error_message; } ?> <div class="abox"> <figure> <fcapion> <h1><hr> <form action="view02.php" method="get" enctype="multipart/form-data" class="cursive"> <table width="316" border="0"> <tr> <td colspan="2"><h1>Edit Your details </h1><p>fill out the form with your details...</p></td> </tr> <tr> <td> </td> <td><p> </p> <p>Click submit to update...</p><p> </p></td> </tr> <tr> <td> </td> <td><p> </p><p></p><p><input type="hidden" name="id" value="<?php echo $row['id']; ?>"/><p> </p></td> </tr> <tr> <td>Website:</td> <td><p> </p><p><input name="website" type="text" id="website" /></p> <p> </p></td> </tr> <tr> <td>Primary Number:</td> <td><p> </p><p><input name="phone" type="text" id="phone" /></p> <p> </p></td> </tr> <tr> <td>Secondary Number:</td> <td><p> </p> <p><input name="phone2" type="text" id="phone2" /></p> <p> </p></td> </tr> <tr> <td>Company Description:</td> <td><p><em>Write a description of what your company does, the services it offers and any additional information here.</em> </p> <p><textarea rows="10" cols="100" name="premiumuser_description" id="premiumuser_description"></textarea></p> <p> </p></td> </tr> <tr> <td>Images:</td> <td><p><em>Upload your company image here.</em> </p> <p><input name="upload" type="file" class="style7" id="upload"></p> <p> </p></td> </tr> <tr> <td><p> </p></td> </tr> <tr> <td colspan="2"><input type="submit" name="submit" value="submit" /></td> </tr> </table> </form></h1> </fcaption></figure> </div> </div> </middle> </div> <!--end middle --> <!--start footer --> <footer> <div id="footer"></div> </footer> <!--end footer --> </div> <!--end container --> <!-- Free template distributed by http://freehtml5templates.com --> </body> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> </html> View02.php: <?php include ('php only scripts/db.php'); include('php only scripts/resize.php'); $id = intval($_GET['id']); // guarantee it's a harmless number value if (isset($_GET['website']) && $_GET['website']) { // does the GET value exists and has it a value ? $website = mysql_real_escape_string($_GET['website']); // get its value and escape it $setArray[] = "website = '$website'"; // ok to update this field in the query so store it } if (isset($_GET['phone']) && $_GET['phone']) { $phone = mysql_real_escape_string($_GET['phone']); $setArray[] = "phone = '$phone'"; } if (isset($_GET['phone2']) && $_GET['phone2']) { $phone2 = mysql_real_escape_string($_GET['phone2']); $setArray[] = "phone2 = '$phone2'"; } if (isset($_GET['premiumuser_description']) && $_GET['premiumuser_description']) { $premiumuser_description = mysql_real_escape_string($_GET['premiumuser_description']); $setArray[] = "premiumuser_description = '$premiumuser_description'"; } if (isset($_GET['username']) && $_GET['username']) { $username = mysql_real_escape_string($_GET['username']); $setArray[] = "username = '$username'"; } if (isset($_GET['password']) && $_GET['password']) { // These are the same so you'd need to make them different if your comparing the password to ensure they entered it correctly ex: $_GET['password1'] for another field in your form $password= mysql_real_escape_string($_GET['password']); // This is fine if the 2 values above are first compared $setArray[] = "password = SHA('$password')"; // If they are compared and validation checks out then just do the query to update the password here.. } if (isset($_GET['upload']) && $_GET['upload']) { $upload = mysql_real_escape_string($_GET['upload']); $setArray[] = "upload = '$upload'"; } /* check if form was submitted */ if (isset($_POST['Submit'])){ $error_message = ""; /* This is the directory where images will be saved */ $target = "/home/users/web/b109/ipg.removalspacecom/images/COMPANIES/"; $target = $target . basename( $_FILES['upload']['name']); /* include validation script */ include ('php only scripts/validation.php'); $uploadDir = '/home/users/web/b109/ipg.removalspacecom/images/COMPANIES'; /* main picture folder */ $max_height = 450; /* largest height you allowed; 0 means any */ $max_width = 450; /* largest width you allowed; 0 means any */ $max_file = 2000000; /* set the max file size in bytes */ $image_overwrite = 1; /* 0 means overwite; 1 means new name */ /* add or delete allowed image types */ $allowed_type01 = array("image/gif", "image/pjpeg", "image/jpeg", "image/png", "image/x-png", "image/jpg"); $do_thumb = 1; /* 1 make thumbnails; 0 means do NOT make */ $thumbDir = "/home/users/web/b109/ipg.removalspacecom/images/thumbs"; /* thumbnail folder */ $thumb_prefix = ""; /* prefix for thumbnails */ $thumb_width = 90; /* max thumb width */ $thumb_height = 70; // max thumb height //Writes the photo to the server if(move_uploaded_file($_FILES['upload']['tmp_name'], $target)) { /* HERE IS WHERE WE WILL DO THE ACTUAL RESIZING */ /* THESE SIX PARAMETERS MAY BE CHANGED TO SUIT YOUR NEEDS */ $upload = $_FILES['upload']['name']; $o_path ="images/COMPANIES/"; $s_path = "images/thumbs/"; $file = $upload; $save = $file; $t_w = 200; $t_h = 150; /* DO NOT CHANGE THIS NEXT LINE */ Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path); }else{ //Gives and error if its not $error_message .= "Sorry, there was a problem uploading your file."; }} if (count($setArray) > 0) { // do we have at least on field to update? $setstr = join (', ', $setArray); // form a comma separated string of our updates $query = "UPDATE companies SET $setstr WHERE id = $id"; // update it echo $query; mysql_query($query) or die(mysql_error()); } header("Location: view01.php?id=" . $id); exit(0); ?> Now awaiting standard reply of: DO NOT SEND HUNDREDS OF LINES OF CODE. lol. p.s Any image that already exists in on the server in /thumbs will update, im guessing because it finds the file name and uses. But any image not on the server it does not update. Here's where im having the problem. I need to update with a fresh/new image that is uploaded. I hope that helps more and hope i have pee'd any off by adding full code.
  14. Hello. I need some help please. Topology is like this: After registration (when users register they choose a company logo themselves). Homepage> users login> users choose another logo they want to change to using form> they hit submit> image is sent to a main folder on the server> it is re-sized> it is sent to a thumbnail folder> and is updated on their profiles and thus the website (using UPDATE set).. I have all the code set up fine for when users register, the image uploads fine first time. What im having trouble with is the update on their profiles? when you click submit, the image doesn't update? I am trying to use the same coding as the register script because i know no other way, could someone share how to update the profile picture or logo? thanks. I will post code i have when im back from work but if you need any specific code let me know. p.s. All other text fields are updated on submit, it's just the browse/upload button that does not work.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.